Files
Anubis/tests/Anubis.Tests/TournamentTests.cs
T
Alby96andClaude Opus 5.5 8aafa5ad32
ci / test (postgres) (push) Successful in 7m47s
ci / test (sqlite) (push) Successful in 6m27s
ci / image (push) Successful in 1m57s
Plan, run and judge a tournament of contenders in the laboratory
A tournament judges many contenders together so that a rule cannot win by
chance alone. Its plan (contenders with rules version and grid, data, costs,
thresholds with the control share, the finalists rule, control repetitions
and seed, combinations, stress windows, variants counted before) is written
with the trials of its contenders in one transaction, before any result, and
keeps its fingerprint like a trial plan. The contender trials read only the
search window; when the last one finishes the tournament goes to its judge.

The judge picks at most eight finalists, one per group and market, by
walk-forward Sharpe, and writes them as the final tract is opened: the
opening is a compare-and-set, so a resumed judge gets back the same
finalists. Each finalist then runs the control against chance on surrogate
series and its chosen variant on the final tract at plain and doubled costs;
these are units in tournament_units, so a judge stopped halfway redoes only
what it had not finished and reads the final tract only for finalists. The
report counts every variant in a common N (field, combinations of the
finalists, the register at the opening, prior protocols), deflates each
finalist against the field variance, computes the common PBO, the effective
number of bets and a block-bootstrap Sharpe interval, and a finalist passes
only if every check passes. Unit outcomes are dropped when it ends.

The trial engine gains LongOnly and Surrogate with default members, so other
engines keep compiling; the daily engine centres its control. Tests cover the
plan written first and never changed, the final tract read once, a resumed
judge, the finalists rule, and a built field where only the two contenders
with an edge pass with 200 repetitions.

refs #123, refs #125

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

632 lines
37 KiB
C#

using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The tournament of the strategies (issues #123 and #125, criteria 2 and 6 of Phase 13): a plan written before any result,
/// the trials of the contenders on the search window, the finalists, the final tract opened once, the control against
/// chance and the common statistics, on synthetic series whose nature is known in advance.
/// </summary>
[TestClass]
public sealed class TournamentTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 0, 0, TimeSpan.Zero);
/// <summary>Warm-up of 450 days before the search, as every trial reads.</summary>
private static readonly DateOnly SearchFrom = Synthetic.Start.AddDays(TrialData.WarmupDays);
private static readonly Dictionary<string, IReadOnlyList<decimal>> OneGrid = new() { ["lookback"] = [20m], ["entry"] = [1m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> EdgeGrid = new() { ["lookback"] = [20m], ["entry"] = [1.5m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> NoiseGrid = new() { ["lookback"] = [20m, 40m, 60m], ["entry"] = [0.5m, 1m, 1.5m] };
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePlanIsWrittenBeforeAnyResultAndNeverChanges()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// A plan that breaks a rule is refused in Italian and leaves nothing behind.
var good = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
(TournamentRequest Request, string Message)[] wrong =
[
(good with { Name = " " }, "Dai un nome al campionato."),
(good with { Contenders = [] }, "Serve almeno un concorrente."),
(good with { Contenders = [good.Contenders[0], good.Contenders[0]] }, "L'etichetta «a» è usata due volte."),
(good with { Contenders = [good.Contenders[0] with { Group = "" }] }, "Il concorrente «a» ha bisogno di un gruppo e di un mercato."),
(good with { Contenders = [good.Contenders[0] with { Strategy = "nessuna" }] }, "Concorrente «a»: strategia sconosciuta."),
(good with { HoldoutFrom = good.Contenders[0].To.AddDays(-10) }, "Il tratto finale di «a» deve durare almeno 30 giorni: i suoi dati finiscono il 04/01/2021."),
(good with { HoldoutFrom = SearchFrom }, "Il tratto finale deve cominciare dopo l'inizio di «a», che comincia il 27/03/2019."),
(good with { Control = new TournamentControl(19, 1) }, "Le ripetizioni del controllo contro il caso vanno da 20 a 10000."),
(good with { Contenders = [good.Contenders[0] with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["lookback"] = [5m] } }] },
"Concorrente «a»: Giorni della media: i valori vanno da 10 a 400."),
(good with { PriorCounted = [new PriorCount("docs/backtests", "crypto_trend", -1)] },
"Le prove già contate hanno bisogno di una strategia e di un numero non negativo di varianti."),
];
foreach (var (request, message) in wrong)
{
var error = await Assert.ThrowsExactlyAsync<TournamentPlanException>(() => lab.PlanTournamentAsync(request, _none)).ConfigureAwait(false);
Assert.AreEqual(message, error.Message);
}
Assert.AreEqual(0, await CountAsync(test, "tournaments").ConfigureAwait(false));
Assert.AreEqual(0, await CountAsync(test, "backtest_trials").ConfigureAwait(false));
// The plan and the trials of its contenders are written together, before anything runs or is read.
var tournament = await lab.PlanTournamentAsync(good, _none).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Planned, tournament.Status);
Assert.IsTrue(tournament.PlanIntact);
var before = await RawPlanAsync(test, tournament.Id).ConfigureAwait(false);
Assert.AreEqual(TrialPlan.Hash(before.Plan), before.Hash);
var plan = tournament.Plan;
Assert.AreEqual(TournamentThresholds.Default, plan.Thresholds);
Assert.AreEqual(0.05, plan.Thresholds.MaxControlShare);
Assert.AreEqual(TrialThresholds.Default.MinDeflatedSharpe, plan.Thresholds.MinDeflatedSharpe);
CollectionAssert.AreEqual(new[] { 1m, 2m, 3m }, plan.CostMultipliers.ToArray());
Assert.AreEqual(new TournamentFinalists(8, "group_and_market", "walk_forward_sharpe"), plan.Finalists);
Assert.AreEqual(180, plan.Combinations.LookbackDays);
CollectionAssert.AreEqual(new[] { "equal", "inverse_volatility", "risk_parity" }, plan.Combinations.WeightSchemes.ToArray());
Assert.AreEqual(27, plan.PriorCounted.Sum(p => p.Variants));
Assert.AreEqual(18, plan.PriorCounted.Single(p => p.Strategy == "crypto_trend").Variants);
Assert.IsNotEmpty(plan.StressWindows);
Assert.AreEqual(TrialValidation.Default, plan.Validation);
Assert.AreEqual(Now, plan.WrittenAt);
Assert.AreEqual(0, plan.RegistryVariantsAtPlanning);
Assert.AreEqual(1 + 1 + TournamentStatistics.Combinations(2, 3) + 27, plan.PlannedTrials, "N planned: the variants, the combinations of two finalists, what was tried before.");
Assert.AreEqual(TournamentStatistics.Bar(plan.PlannedTrials), plan.Bar);
Assert.IsGreaterThan(2.0, plan.Bar, "The plan shows the bar before the start.");
Assert.AreEqual(TournamentPlan.FromJson(before.Plan).ToJson(), before.Plan, "The stored plan is its own text.");
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(2, trials);
var trialPlans = new List<(string Plan, string Hash)>();
foreach (var trial in trials)
{
Assert.AreEqual(tournament.Id, trial.TournamentId);
Assert.AreEqual(TrialStatuses.Planned, trial.Status);
Assert.AreEqual(good.HoldoutFrom.AddDays(-1), trial.Plan.Data.To, "A contender's trial never reads the final tract.");
Assert.IsNull(await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false));
trialPlans.Add(await RawTrialPlanAsync(test, trial.Id).ConfigureAwait(false));
}
CollectionAssert.AreEqual(new[] { "EAA-EUR" }, trials[0].Plan.Data.Symbols.ToArray());
Assert.AreEqual(0, await CountAsync(test, "tournament_units").ConfigureAwait(false), "No result exists yet.");
Assert.IsEmpty(field.Reads, "No data was read yet.");
Assert.IsNull(await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false));
// The contenders run, the tournament is judged; the plans have not changed by a byte.
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
Assert.AreEqual(before, await RawPlanAsync(test, tournament.Id).ConfigureAwait(false), "The plan text and its hash are never updated.");
for (var i = 0; i < trials.Count; i++)
{
Assert.AreEqual(trialPlans[i], await RawTrialPlanAsync(test, trials[i].Id).ConfigureAwait(false));
}
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(before.Hash, report.PlanHash);
Assert.AreEqual(tournament.Id, report.TournamentId);
// The units of the tournament lose their outcomes when it ends: the rows stay as a record.
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
Assert.IsNotEmpty(units);
Assert.IsTrue(units.All(u => u.Status == TrialUnitStatuses.Done && !u.HasOutcome));
CollectionAssert.IsSubsetOf(new[] { "variant", "control", "holdout" }, units.Select(u => u.Kind).Distinct().ToArray());
// A plan changed after it was written no longer gives its hash: the tournament is not judged.
var tampered = await lab.PlanTournamentAsync(good with { Contenders = [good.Contenders[0] with { Symbols = ["XYZ-EUR"] }] }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", tampered.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.IsFalse(refused.PlanIntact);
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
StringAssert.Contains(refused.Error, "impronta");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFinalTractIsReadOnce()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// a and b share a group and a market: only the better of the two goes on. c has its own.
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g1", "m1", ["NAA-EUR"], OneGrid), ("c", "g2", "m1", ["NAB-EUR"], OneGrid));
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
CollectionAssert.AreEquivalent(new[] { "a", "c" }, done.Finalists!.ToArray());
CollectionAssert.AreEqual(done.Finalists!.ToArray(), report.Finalists.Select(f => f.Label).ToArray());
CollectionAssert.AreEqual(new[] { true, false, true }, report.Contenders.Select(c => c.Finalist).ToArray());
Assert.IsNotNull(done.HoldoutOpenedAt);
// The final tract was read once, only for the finalists; the trials read up to the day before it.
var tract = field.Reads.Where(r => r.To > request.HoldoutFrom.AddDays(-1)).ToList();
Assert.IsTrue(tract.All(r => r.From == request.HoldoutFrom), "Only the runs of the final tract read past the search.");
CollectionAssert.AreEquivalent(new[] { "EAA-EUR", "NAB-EUR" }, tract.SelectMany(r => r.Symbols).ToArray());
Assert.IsTrue(field.Reads.Where(r => r.Symbols.Contains("NAA-EUR")).All(r => r.To == request.HoldoutFrom.AddDays(-1)), "A contender that is not a finalist never sees it.");
// The finalists cannot change once the tract is open: a second opening gets back the first, at the first moment.
clock.Advance(TimeSpan.FromHours(1));
var again = await lab.Tournaments.OpenHoldoutAsync(tournament.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(done.Finalists!.ToArray(), again.Finalists.ToArray());
Assert.AreEqual(done.HoldoutOpenedAt, again.OpenedAt);
// A tournament judged is not judged again.
var reads = field.Reads.Count;
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(reads, field.Reads);
// On a fresh tournament the first opening writes, the second gets it back.
var store = lab.Tournaments;
var other = await lab.PlanTournamentAsync(request with { Name = "Altro" }, _none).ConfigureAwait(false);
var first = await store.OpenHoldoutAsync(other.Id, ["c", "a"], _none).ConfigureAwait(false);
clock.Advance(TimeSpan.FromHours(1));
var second = await store.OpenHoldoutAsync(other.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { "c", "a" }, first.Finalists.ToArray());
CollectionAssert.AreEqual(new[] { "c", "a" }, second.Finalists.ToArray());
Assert.AreEqual(first.OpenedAt, second.OpenedAt);
CollectionAssert.AreEqual(new[] { "c", "a" }, (await store.GetAsync(other.Id, _none).ConfigureAwait(false))!.Finalists!.ToArray());
}
/// <summary>
/// Criterion 6: a field built on purpose, two contenders with an edge (the reversion rule on prices that revert to their
/// mean) and four of noise (the same rule on random walks without drift), each in its own group and market so all six are
/// finalists, judged with 200 repetitions of the control. Only the two with an edge pass. The variance of the field is
/// mostly the gap between edge and noise when a third of the field has an edge, and the bar of 113 trials rises with
/// it: the edges here are searched less (one variant against nine), as in a real field where noise is most of the search.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFieldWithTwoEdgesAndFourNoisesPassesOnlyTheTwo()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
const int days = 2314;
var field = new SyntheticField();
foreach (var (symbol, seed) in new[] { ("EAA-EUR", 101), ("EAB-EUR", 102), ("EAC-EUR", 103), ("EBA-EUR", 201), ("EBB-EUR", 202), ("EBC-EUR", 203) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.MeanRevertingReturns(days, seed, halfLife: 2, volatility: 0.02), seed));
}
foreach (var (symbol, seed) in new[] { ("NAA-EUR", 301), ("NAB-EUR", 302), ("NAC-EUR", 303), ("NAD-EUR", 304) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.WalkReturns(days, seed, drift: 0, volatility: 0.02), seed));
}
using var lab = Lab(test, clock, field, workers: 4);
var to = Synthetic.Start.AddDays(days);
var holdoutFrom = to.AddDays(-364);
var request = new TournamentRequest("Campo costruito apposta",
[
Contender("bordo-1", "g1", "m1", ["EAA-EUR", "EAB-EUR", "EAC-EUR"], EdgeGrid, to),
Contender("bordo-2", "g2", "m2", ["EBA-EUR", "EBB-EUR", "EBC-EUR"], EdgeGrid, to),
Contender("rumore-1", "g3", "m3", ["NAA-EUR"], NoiseGrid, to),
Contender("rumore-2", "g4", "m4", ["NAB-EUR"], NoiseGrid, to),
Contender("rumore-3", "g5", "m5", ["NAC-EUR"], NoiseGrid, to),
Contender("rumore-4", "g6", "m6", ["NAD-EUR"], NoiseGrid, to),
], holdoutFrom, 10_000m);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
Assert.AreEqual(200, tournament.Plan.Control.Repetitions);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
var said = Describe(report);
Assert.HasCount(6, report.Finalists, said);
Assert.AreEqual(new TournamentTrialsCount(2 + (4 * 9), TournamentStatistics.Combinations(6, 3), 0, 27, 113), report.Trials, said);
Assert.AreEqual(TournamentStatistics.Bar(113), report.Bar);
CollectionAssert.AreEquivalent(new[] { "bordo-1", "bordo-2" }, report.Finalists.Where(f => f.Passed).Select(f => f.Label).ToArray(), said);
Assert.AreEqual(2, report.PassedCount);
Assert.IsTrue(report.Passed);
Assert.AreEqual(TrialVerdicts.Passed, done.Verdict);
foreach (var edge in report.Finalists.Where(f => f.Label.StartsWith("bordo", StringComparison.Ordinal)))
{
Assert.IsTrue(edge.Checks.All(c => c.Passed == true), said);
Assert.AreEqual(200, edge.Control.Repetitions);
Assert.IsTrue(edge.Control.Centred, "The daily engine only buys: its control turns around the mean.");
Assert.IsLessThanOrEqualTo(0.05, edge.Control.Share!.Value, said);
Assert.IsGreaterThan(0.0, edge.SharpeInterval.Low, said);
}
foreach (var noise in report.Finalists.Where(f => f.Label.StartsWith("rumore", StringComparison.Ordinal)))
{
Assert.IsFalse(noise.Passed, said);
Assert.IsLessThan(0.90, noise.DeflatedSharpe.Value, said);
}
Assert.IsLessThanOrEqualTo(0.40, report.Overfitting!.Probability, said);
Assert.AreEqual(38, report.Overfitting.Variants);
Assert.IsNotNull(report.EffectiveBets);
Assert.IsTrue(report.EffectiveBets is > 4 and <= 6, said);
Assert.AreEqual(TournamentReport.FromJson(report.ToJson()).ToJson(), report.ToJson());
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingDoesNotRedoFinishedControlUnits()
{
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
const int total = 2 * 20;
// The same tournament judged without a stop, for comparison.
TournamentReport whole;
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var reference = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, reference.Id).ConfigureAwait(false);
var json = await lab.Tournaments.ReportJsonAsync(reference.Id, _none).ConfigureAwait(false);
Assert.IsNotNull(json, (await lab.Tournaments.GetAsync(reference.Id, _none).ConfigureAwait(false))!.Error);
whole = TournamentReport.FromJson(json);
}
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The process stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
var before = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), before, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Judging, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
var symbols = trials.ToDictionary(t => t.Id, t => t.Plan.Data.Symbols[0]);
var finished = (await DoneControlsAsync(test, tournament.Id).ConfigureAwait(false)).Select(u => FormattableString.Invariant($"control {symbols[u.Trial]} {u.Key.Split(':')[1]}")).ToList();
Assert.IsGreaterThanOrEqualTo(5, finished.Count);
Assert.IsTrue(units.Where(u => u.Status == TrialUnitStatuses.Done).All(u => u.HasOutcome), "The tournament keeps its outcomes until it ends.");
Assert.IsFalse(field.Reads.Any(r => r.From == plan.HoldoutFrom), "The stop came before the final tract.");
// The next start judges it again: only the repetitions not finished run, the final tract is read once.
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(total - finished.Count, controls);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(controls, key, "A finished repetition does not run again: " + key);
}
CollectionAssert.AreEquivalent(controls.Concat(finished).ToArray(), controls.Concat(finished).Distinct().ToArray());
Assert.HasCount(total, controls.Concat(finished).Distinct().ToList(), "Every repetition of both finalists is done once.");
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList(), "Two finalists, plain and doubled costs.");
Assert.HasCount(2, field.Reads.Where(r => r.From == plan.HoldoutFrom).ToList(), "The final tract of each finalist is read once.");
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(Comparable(whole), Comparable(report));
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFinalistsAreTheBestOfEachGroupAndMarketAndAtMostEight()
{
var golden = BacktestReport.FromJson(Fixture.Text(Path.Combine("golden", "sma_cross.report.json")));
var trialPlan = Laboratory.BuildPlan(LaboratoryTests.Request(), Now).Plan;
var contenders = new List<TournamentContender>();
var outcomes = new List<ContenderOutcome>();
void Add(string label, string group, string market, double? walkForward, string status = TrialStatuses.Done)
{
var contender = new TournamentContender(label, "sma_cross", "1", group, market, trialPlan.Grid, trialPlan.Data, 4);
contenders.Add(contender);
var trial = new Trial(Guid.NewGuid(), "sma_cross", "1", trialPlan, "h", 4, status, null, null, null, null, Now, Now, Now);
var report = status != TrialStatuses.Done ? null
: golden with { WalkForward = walkForward is { } s ? new ReportWalkForward([], 0, 0, s) : null };
outcomes.Add(new ContenderOutcome(contender, trial, report, []));
}
Add("a", "trend", "crypto", 0.5);
Add("b", "trend", "crypto", 0.9);
Add("c", "trend", "fx", 0.1);
Add("d", "reversion", "crypto", 0.9);
Add("e", "reversion", "crypto", 0.9);
Add("f", "momentum", "crypto", 2.0, TrialStatuses.Failed);
Add("g", "momentum", "crypto", null);
Add("h", "momentum", "fx", double.NaN);
Add("i", "g1", "m", 0.01);
Add("j", "g2", "m", 0.02);
Add("k", "g3", "m", 0.03);
Add("l", "g4", "m", 0.04);
Add("m", "g5", "m", 0.05);
Add("n", "g6", "m", -0.5);
var plan = TournamentPlans.BuildPlan(new TournamentRequest("x", [new ContenderRequest("z", "sma_cross", "g", "m", TrialSources.Database, Venues.Okx, ["BTC-EUR"],
trialPlan.Data.From, trialPlan.Data.To)], trialPlan.Data.To.AddDays(-60), 10_000m), Now, 0, StrategyCatalog.Find).Plan with
{ Contenders = contenders };
// Best of each pair first, ties to the one written first; a failed trial, or one without walk-forward, never goes on.
CollectionAssert.AreEqual(new[] { "b", "d", "c", "m", "l", "k", "j", "i" }, TournamentJudge.Finalists(plan, outcomes).ToArray());
CollectionAssert.AreEqual(new[] { "b", "d", "c" }, TournamentJudge.Finalists(plan with { Finalists = plan.Finalists with { Max = 3 } }, outcomes).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AControlUnitKeepsOnlyItsSharpeAndItsKeyNamesTheRepetition()
{
var parameters = ReversionFamily.With(20, 1.5m).ToString();
var control = new TrialUnitKey(TrialUnitKind.Control, 7, parameters, 1m);
var holdout = new TrialUnitKey(TrialUnitKind.Holdout, 0, parameters, 2m);
Assert.AreEqual("control:7:entry=1.5;lookback=20:x1", control.Text);
Assert.AreEqual("holdout:0:entry=1.5;lookback=20:x2", holdout.Text);
foreach (var sharpe in new[] { -0.0123456789012345, 0.0, 0.1 + 0.2, double.Epsilon })
{
var back = TrialUnitOutcomes.Decode(control, TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null) { Sharpe = sharpe }));
Assert.AreEqual(sharpe, back.Sharpe);
Assert.IsNull(back.Run);
Assert.IsNull(back.LookAhead);
}
Assert.ThrowsExactly<InvalidOperationException>(() => TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportOfATournamentRoundTrips()
{
var checks = new List<ReportCheck>
{
new(ReportCheckKeys.DeflatedSharpe, "Deflated Sharpe Ratio sul numero comune di prove", 0.93, "≥", 0.9, "ratio", true),
new(TournamentCheckKeys.Control, "Controllo contro il caso: quota di copie pari o migliori", null, "≤", 0.05, "ratio", false),
};
var report = new TournamentReport(
Guid.Parse("01938a6e-0000-7000-8000-000000000001"),
"Campionato",
"abc",
new TournamentTrialsCount(40, 48, 3, 27, 118),
2.6,
0.123456789,
new ReportOverfitting(16, 12870, 40, 0.1),
4.5,
[
new TournamentContenderResult("a", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Done, 2, "entry=1;lookback=20", 0.1, true),
new TournamentContenderResult("b", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Failed, 9, null, null, false) { Error = "Strumento sconosciuto" },
],
[
new TournamentFinalistResult("a", ReversionFamily.FamilyId, "g", "m", "entry=1;lookback=20", 365, 0.2,
new DeflatedSharpe(0.2, 0.1, 1500, 0.8, 5.5, 118, 0.0027, 0.93), new ReportInterval(double.NegativeInfinity, double.PositiveInfinity), 1234.5678m, 0.12, true,
new TournamentControlResult(200, 7, true, 0.2, null, null, null) { Unavailable = Surrogates.CorporateActionsRefused },
new TournamentHoldoutResult(new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31), 100.10m, 90.05m, 0.01, 0.05, 0.02), checks, false),
],
0,
false,
["Una limitazione."],
Now,
1.5);
var json = report.ToJson();
Assert.AreEqual(json, TournamentReport.FromJson(json).ToJson());
foreach (var name in new[] { "\"passed_count\":", "\"field_variance\":", "\"effective_bets\":", "\"sharpe_interval\":", "\"net_at_double_costs\":", "\"unavailable\":", "\"walk_forward_sharpe\":" })
{
StringAssert.Contains(json, name);
}
StringAssert.Contains(json, "\"low\":\"-Infinity\"");
Assert.AreEqual(1234.5678m, TournamentReport.FromJson(json).Finalists[0].NetAtDoubleCosts);
}
/// <summary>The figures a resumed judge must give again: everything but the identities and the seconds.</summary>
private static string Comparable(TournamentReport report) =>
(report with { TournamentId = Guid.Empty, Seconds = 0, Contenders = [.. report.Contenders.Select(c => c with { TrialId = Guid.Empty })] }).ToJson();
private static string Describe(TournamentReport report) => string.Join(" | ", report.Finalists.Select(f => FormattableString.Invariant(
$"{f.Label}: S={f.Sharpe:F4} dsr={f.DeflatedSharpe.Value:F3} sr0={f.DeflatedSharpe.Benchmark:F4} share={f.Control.Share} net2={f.NetAtDoubleCosts:F0} dd={f.MaxDrawdown:F3} hold2={f.Holdout.NetAtDoubleCosts:F0} [{f.SharpeInterval.Low:F3},{f.SharpeInterval.High:F3}] failed:{string.Join(",", f.Checks.Where(c => c.Passed != true).Select(c => c.Key))}")))
+ FormattableString.Invariant($" | pbo={report.Overfitting?.Probability} var={report.FieldVariance:F4} bets={report.EffectiveBets:F2}");
/// <summary>A short field: 1100 days a series, a final tract of 100 days.</summary>
private static SyntheticField Small()
{
var field = new SyntheticField();
field.Add("EAA-EUR", Synthetic.Bars(Synthetic.MeanRevertingReturns(1099, 11, halfLife: 2, volatility: 0.02), 11));
field.Add("NAA-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 12, volatility: 0.02), 12));
field.Add("NAB-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 13, volatility: 0.02), 13));
return field;
}
private static TournamentRequest SmallRequest(params (string Label, string Group, string Market, string[] Symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> Grid)[] contenders)
{
var to = Synthetic.Start.AddDays(1099);
return new TournamentRequest("Campionato di prova", [.. contenders.Select(c => Contender(c.Label, c.Group, c.Market, c.Symbols, c.Grid, to))], to.AddDays(-99), 10_000m)
{
Control = new TournamentControl(20, 20_261_204),
};
}
private static ContenderRequest Contender(string label, string group, string market, string[] symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> grid, DateOnly to) =>
new(label, ReversionFamily.FamilyId, group, market, TrialSources.Database, Venues.Okx, symbols, SearchFrom, to, grid);
private static Laboratory Lab(TestDb test, IClock clock, SyntheticField field, int workers = 1) =>
new(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers))
{
Families = id => id == ReversionFamily.FamilyId ? ReversionFamily.Instance : StrategyCatalog.Find(id),
DataFor = field.LoadAsync,
};
/// <summary>Runs the trials of a tournament in the order of its plan: the last one brings it to its judge.</summary>
private static async Task RunAllAsync(Laboratory lab, Guid tournament)
{
foreach (var trial in await lab.Trials.OfTournamentAsync(tournament, _none).ConfigureAwait(false))
{
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
}
}
private static async Task<int> CountAsync(TestDb test, string table) =>
(int)await test.Db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT COUNT(*) AS n FROM {table}", r => r.Number("n")), _none).ConfigureAwait(false);
private static int DoneControls(TestDb test, Guid tournament) =>
(int)test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT COUNT(*) AS n FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d", r => r.Number("n"),
("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).GetAwaiter().GetResult();
private static async Task<IReadOnlyList<(Guid Trial, string Key)>> DoneControlsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT trial_id, unit_key FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d",
r => (r.Id("trial_id"), r.Text("unit_key")), ("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).ConfigureAwait(false);
private static async Task<IReadOnlyList<TrialUnitRow>> AllUnitsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT unit_key, kind, status, outcome, seconds, tournament_id FROM tournament_units WHERE tournament_id = @t ORDER BY id",
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), r.IdOrNull("tournament_id")),
("t", tournament)), _none).ConfigureAwait(false);
private static Task<(string Plan, string Hash)> RawPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM tournaments WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
private static Task<(string Plan, string Hash)> RawTrialPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM backtest_trials WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
/// <summary>The signs of a surrogate as text, to tell which repetition an engine was given.</summary>
private static string SignsOf(DaySigns signs) =>
string.Concat(Enumerable.Range(0, Math.Min(signs.Count, 256)).Select(i => signs[signs.First.AddDays(i)] > 0 ? '+' : '-'));
/// <summary>Synthetic series by symbol, read as the laboratory reads data (from the warm-up to the last day asked), with every read recorded.</summary>
private sealed class SyntheticField
{
private readonly Dictionary<string, IReadOnlyList<DailyBar>> _bars = new(StringComparer.Ordinal);
private readonly List<TrialData> _reads = [];
public IReadOnlyList<TrialData> Reads
{
get
{
lock (_reads)
{
return [.. _reads];
}
}
}
public void Add(string symbol, IReadOnlyList<DailyBar> bars) => _bars[symbol] = bars;
public Task<BacktestDataset> LoadAsync(TrialData data, CancellationToken cancellationToken)
{
lock (_reads)
{
_reads.Add(data);
}
var from = data.HistoryStart();
var instruments = data.Symbols.Select(s => new BacktestInstrument(Synthetic.Coin(s),
[.. (_bars.GetValueOrDefault(s) ?? throw new InvalidOperationException("Strumento sconosciuto: " + s)).Where(b => b.Day >= from && b.Day <= data.To)],
source: "sintetico"));
return Task.FromResult(new BacktestDataset(instruments, "EUR"));
}
}
/// <summary>An engine in between: it records the runs on surrogates (with the repetition their signs belong to) and on the final tract.</summary>
private sealed class CountingEngine(ITrialEngine inner, List<string> calls, IReadOnlyDictionary<string, int> replicas, string name, string? tag, Action<int>? onControl = null) : ITrialEngine
{
private readonly Counter _controls = new();
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public bool LongOnly => inner.LongOnly;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
if (tag is not null)
{
Record(FormattableString.Invariant($"{tag} x{costMultiplier}"));
}
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark() => inner.Benchmark();
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => inner.LookAhead(parameters, cuts);
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
public ITrialEngine Surrogate(DaySigns signs, bool centred)
{
var surrogate = inner.Surrogate(signs, centred);
return replicas.TryGetValue(SignsOf(signs), out var k)
? new CountingEngine(surrogate, calls, replicas, name, FormattableString.Invariant($"control {name} {k}"), onControl) { Parent = this }
: surrogate;
}
private CountingEngine? Parent { get; init; }
private void Record(string call)
{
lock (calls)
{
calls.Add(call.Split(' ')[0] == "control" ? call.Split(" x")[0] : call);
}
if (call.StartsWith("control", StringComparison.Ordinal))
{
onControl?.Invoke((Parent ?? this)._controls.Next());
}
}
}
private sealed class Counter
{
private int _value;
public int Next() => Interlocked.Increment(ref _value);
}
}