diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 7c83721..6306c47 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -77,6 +77,8 @@ public sealed partial class Laboratory : IDisposable _workers = workers ?? (_ => Task.FromResult(1)); Trials = new TrialStore(db, clock); Units = new TrialUnitStore(db, clock); + Tournaments = new TournamentStore(db, clock); + DataFor = (data, cancellationToken) => LoadAsync(_db, _clock, _researchRoot, data, cancellationToken); } private const string PoolName = "anubis-laboratory"; @@ -86,9 +88,18 @@ public sealed partial class Laboratory : IDisposable /// The units of the trials: one row per engine execution. public TrialUnitStore Units { get; } + /// The tournaments of the strategies (ADR 0026). + public TournamentStore Tournaments { get; } + /// The engine of a trial: the daily one. Tests put one in between to count or stop the executions. internal Func EngineFor { get; set; } = (plan, family, data) => new DailyTrialEngine(plan, family, data); + /// The families the laboratory knows: the catalogue. Tests add the families that exist only in them. + internal Func Families { get; set; } = StrategyCatalog.Find; + + /// The data a trial reads (). Tests give synthetic series and count what is read. + internal Func> DataFor { get; set; } + /// Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did. public Func? ReviewTrialEnded { get; set; } @@ -145,10 +156,15 @@ public sealed partial class Laboratory : IDisposable } /// The plan of a request: the family's own grid where the request gives none, the default costs, checks and thresholds. - public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null) + public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null) => + BuildPlan(request, now, slippage, StrategyCatalog.Find); + + /// The same, with the families knows (the catalogue, or the test families of a tournament). + internal static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage, Func families) { ArgumentNullException.ThrowIfNull(request); - var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta."); + ArgumentNullException.ThrowIfNull(families); + var family = families(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta."); if (request.Source is not (TrialSources.Database or TrialSources.Research)) { throw new TrialRequestException(TrialRequestErrors.Source, "Origine dei dati sconosciuta."); @@ -248,6 +264,7 @@ public sealed partial class Laboratory : IDisposable } await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); + await ResumeTournamentsAsync(cancellationToken).ConfigureAwait(false); await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) { try @@ -295,25 +312,30 @@ public sealed partial class Laboratory : IDisposable try { trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata."); + if (trial.TournamentId is { } tournament) + { + await Tournaments.StartAsync(tournament, cancellationToken).ConfigureAwait(false); + } + if (!trial.PlanIntact) { throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte."); } - var family = StrategyCatalog.Find(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy); + var family = Families(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy); if (family.Version != trial.StrategyVersion) { throw new InvalidOperationException($"La strategia è cambiata dalla versione {trial.StrategyVersion} alla {family.Version}: pianifica una prova nuova."); } - var data = await LoadAsync(_db, _clock, _researchRoot, trial.Plan.Data, cancellationToken).ConfigureAwait(false); + var data = await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false); var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false); var now = _clock.UtcNow; var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false))); var done = await Units.ResumeAsync(id, cancellationToken).ConfigureAwait(false); var engine = EngineFor(trial.Plan, family, data); var watch = Stopwatch.StartNew(); - var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, null, done), text => _progress[id] = text, + var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done), text => _progress[id] = text, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); _progress[id] = "convalide"; @@ -341,6 +363,12 @@ public sealed partial class Laboratory : IDisposable { await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); } + + // The last trial of a tournament to finish brings it to its judge. + if (trial?.TournamentId is { } judged) + { + await JudgeTournamentAsync(judged, cancellationToken).ConfigureAwait(false); + } } /// diff --git a/src/Anubis/Backtest/LaboratoryTournaments.cs b/src/Anubis/Backtest/LaboratoryTournaments.cs new file mode 100644 index 0000000..2d38993 --- /dev/null +++ b/src/Anubis/Backtest/LaboratoryTournaments.cs @@ -0,0 +1,237 @@ +using System.Diagnostics; +using Anubis.Core; +using Anubis.Strategies; +using Microsoft.Extensions.Logging; + +namespace Anubis.Backtest; + +/// +/// The tournaments of the laboratory (ADR 0026 point 7). The plan and the trials of the contenders are written together; the +/// trials run as any other, on the search window only. When the last one finishes the tournament goes to its judge: the +/// finalists are chosen and written as the final tract is opened, once; the control against chance and the runs on the final +/// tract of every finalist are units on the pool, kept in the database, so a judge stopped halfway runs again only what it +/// had not finished; then the report. +/// +public sealed partial class Laboratory +{ + /// The costs of the runs on the final tract: plain and doubled. + private static readonly decimal[] HoldoutCosts = [1m, 2m]; + + /// Checks the request, writes the plan of the tournament with the trials of its contenders and queues them. The plan is final from here on. + public async Task PlanTournamentAsync(TournamentRequest request, CancellationToken cancellationToken) + { + var slippage = await new Anubis.Learning.CostBook(_db, _clock).TableAsync(cancellationToken).ConfigureAwait(false); + var registry = await Tournaments.RegistryVariantsAsync(null, null, cancellationToken).ConfigureAwait(false); + var (plan, trials) = TournamentPlans.BuildPlan(request, _clock.UtcNow, registry, Families, slippage); + var tournament = await Tournaments.PlanAsync(plan, trials, cancellationToken).ConfigureAwait(false); + foreach (var trial in await Trials.OfTournamentAsync(tournament.Id, cancellationToken).ConfigureAwait(false)) + { + await _queue.Writer.WriteAsync(trial.Id, cancellationToken).ConfigureAwait(false); + } + + return tournament; + } + + // After a restart: the tournaments whose trials are all finished but that were not judged to the end. + private async Task ResumeTournamentsAsync(CancellationToken cancellationToken) + { + IReadOnlyList ids; + try + { + ids = await Tournaments.ResumableAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogQueueFailed(_logger, ex); + return; + } + + foreach (var id in ids) + { + await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Judges a tournament whose trials are all finished; nothing when one is still to run or the tournament is finished. A + /// failure is recorded, not thrown; a stop leaves it being judged, and the next start goes on from the units done. + /// + public async Task JudgeTournamentAsync(Guid id, CancellationToken cancellationToken) + { + var tournament = await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false); + if (tournament is null || tournament.IsFinished) + { + return; + } + + var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false); + if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false)) + { + return; + } + + _progress[id] = "scelta dei finalisti"; + try + { + var watch = Stopwatch.StartNew(); + if (!tournament.PlanIntact) + { + throw new InvalidOperationException("Il piano registrato del campionato non corrisponde più alla sua impronta: il campionato non si giudica."); + } + + var plan = tournament.Plan; + if (trials.Count != plan.Contenders.Count) + { + throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano."); + } + + var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false))); + var contenders = new List(); + for (var i = 0; i < trials.Count; i++) + { + contenders.Add(await ContenderAsync(plan, plan.Contenders[i], trials[i], pool, cancellationToken).ConfigureAwait(false)); + } + + // The final tract opens once: a judge resumed after a restart gets back the finalists written the first time. + var (finalists, openedAt) = await Tournaments.OpenHoldoutAsync(id, TournamentJudge.Finalists(plan, contenders), cancellationToken).ConfigureAwait(false); + var registry = await Tournaments.RegistryVariantsAsync(id, openedAt, cancellationToken).ConfigureAwait(false); + var byLabel = contenders.ToDictionary(c => c.Contender.Label, StringComparer.Ordinal); + var outcomes = new List(); + for (var k = 0; k < finalists.Count; k++) + { + var contender = byLabel.GetValueOrDefault(finalists[k]) ?? throw new InvalidOperationException("Il finalista «" + finalists[k] + "» non è nel piano."); + _progress[id] = $"finalista {k + 1} di {finalists.Count}"; + outcomes.Add(await FinalistAsync(id, plan, contender, pool, cancellationToken).ConfigureAwait(false)); + } + + _progress[id] = "rapporto del campionato"; + var now = _clock.UtcNow; + var elapsed = watch.Elapsed; + var report = await pool.RunAsync(() => TournamentJudge.Report(id, plan, tournament.PlanHash, contenders, finalists, outcomes, registry, now, elapsed)) + .ConfigureAwait(false); + await Tournaments.FinishAsync(id, report.Passed, report.ToJson(), cancellationToken).ConfigureAwait(false); + LogTournamentFinished(_logger, id, report.PassedCount); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; // Left being judged: the next start goes on. + } + catch (Exception ex) + { + LogTournamentFailed(_logger, id, ex); + await Tournaments.FailAsync(id, Redactor.Redact(ex.Message), CancellationToken.None).ConfigureAwait(false); + } + finally + { + _progress.TryRemove(id, out _); + } + } + + // A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept. + private async Task ContenderAsync(TournamentPlan plan, TournamentContender contender, Trial trial, LowPriorityPool pool, CancellationToken cancellationToken) + { + var data = trial.Plan.Data; + if (trial.Strategy != contender.Strategy || trial.StrategyVersion != contender.StrategyVersion || data.To != plan.SearchTo || data.From != contender.Data.From + || !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || trial.Variants != contender.Variants) + { + throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano."); + } + + if (trial.Status != TrialStatuses.Done) + { + return new ContenderOutcome(contender, trial, null, []); + } + + var report = BacktestReport.FromJson(await Trials.ReportJsonAsync(trial.Id, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("La prova di «" + contender.Label + "» non ha un rapporto.")); + var family = FamilyOf(contender); + var stored = await Units.OutcomesAsync(trial.Id, cancellationToken).ConfigureAwait(false); + var variants = await pool.RunAsync(() => ParameterGrid.Of(family, trial.Plan.Grid).Select((v, i) => + { + var key = new TrialUnitKey(TrialUnitKind.Variant, i, v.ToString(), 1m); + var outcome = stored.GetValueOrDefault(key.Text) + ?? throw new InvalidOperationException("Mancano i risultati delle varianti di «" + contender.Label + "»: il campionato non si può giudicare."); + return VariantSeries.Of(v.ToString(), TrialUnitOutcomes.Decode(key, outcome).Run!); + }).ToList()).ConfigureAwait(false); + return new ContenderOutcome(contender, trial, report, variants); + } + + // The units of a finalist: the repetitions of the control on the surrogates of its search data, then its chosen variant on + // the final tract at plain and doubled costs. The final tract is read only when its runs are not done yet. + private async Task FinalistAsync(Guid tournamentId, TournamentPlan plan, ContenderOutcome contender, LowPriorityPool pool, CancellationToken cancellationToken) + { + var trial = contender.Trial; + var family = FamilyOf(contender.Contender); + var chosenText = contender.Chosen.Parameters; + var chosen = ParameterGrid.Of(family, trial.Plan.Grid).FirstOrDefault(v => v.ToString() == chosenText)?.Parameters + ?? throw new InvalidOperationException("La variante scelta di «" + contender.Contender.Label + "» non è nella sua griglia."); + var done = await Units.ResumeAsync(trial.Id, cancellationToken).ConfigureAwait(false); + var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done); + + // Every finalist draws the signs of a day from the same first day, so a day has one sign across the whole field. + var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart()); + var engine = EngineFor(trial.Plan, family, await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false)); + var centred = engine.LongOnly; + List control = [.. Enumerable.Range(0, plan.Control.Repetitions).Select(k => new TrialUnitKey(TrialUnitKind.Control, k, chosenText, 1m))]; + string? unavailable = null; + if (control.Any(k => !done.ContainsKey(k.Text))) + { + unavailable = await pool.RunAsync(() => + { + try + { + engine.Surrogate(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, 0)), centred); + return null; + } + catch (NotSupportedException ex) + { + return ex.Message; + } + }).ConfigureAwait(false); + } + + var replicas = new List(); + if (unavailable is null) + { + TrialUnitResult Replica(TrialUnitKey key) + { + cancellationToken.ThrowIfCancellationRequested(); + var surrogate = engine.Surrogate(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, key.Index)), centred); + return new TrialUnitResult(key, null, null) { Sharpe = Moments.Of(surrogate.Run(chosen).DailyReturns()).Sharpe }; + } + + replicas.AddRange((await units.RunAsync(control, Replica, cancellationToken).ConfigureAwait(false)).Select(r => r.Sharpe ?? double.NaN)); + } + + List holdout = [.. HoldoutCosts.Select(m => new TrialUnitKey(TrialUnitKind.Holdout, 0, chosenText, m))]; + ITrialEngine? tract = null; + if (holdout.Any(k => !done.ContainsKey(k.Text))) + { + var data = trial.Plan.Data with { From = plan.HoldoutFrom, To = contender.Contender.Data.To }; + var holdoutPlan = trial.Plan with { Data = data }; + tract = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false)); + } + + TrialUnitResult Final(TrialUnitKey key) + { + cancellationToken.ThrowIfCancellationRequested(); + return new TrialUnitResult(key, (tract ?? throw new InvalidOperationException("The final tract was not read.")).Run(chosen, key.CostMultiplier), null); + } + + var runs = await units.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false); + return new FinalistOutcome(contender.Contender.Label, centred, replicas, unavailable, runs.ToDictionary(r => r.Key.CostMultiplier, r => r.Run!)); + } + + private IStrategyFamily FamilyOf(TournamentContender contender) + { + var family = Families(contender.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + contender.Strategy); + return family.Version == contender.StrategyVersion ? family + : throw new InvalidOperationException($"La strategia di «{contender.Label}» è cambiata dalla versione {contender.StrategyVersion} alla {family.Version}: pianifica un campionato nuovo."); + } + + [LoggerMessage(Level = LogLevel.Information, Message = "Tournament {Id} judged, finalists passed: {Passed}")] + private static partial void LogTournamentFinished(ILogger logger, Guid id, int passed); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} failed")] + private static partial void LogTournamentFailed(ILogger logger, Guid id, Exception exception); +} diff --git a/src/Anubis/Backtest/TournamentReport.cs b/src/Anubis/Backtest/TournamentReport.cs new file mode 100644 index 0000000..64365f0 --- /dev/null +++ b/src/Anubis/Backtest/TournamentReport.cs @@ -0,0 +1,261 @@ +using System.Text.Json; +using Anubis.Strategies; + +namespace Anubis.Backtest; + +/// The common number of trials N and where it comes from (ADR 0026 point 3): nothing is ever taken away. +public sealed record TournamentTrialsCount(int Field, int Combinations, int Registry, int Prior, int Total); + +/// A contender of the report: its trial, the variant chosen on its plateau and the Sharpe of its walk-forward windows. +public sealed record TournamentContenderResult( + string Label, + string Strategy, + string Group, + string Market, + Guid TrialId, + string Status, + int Variants, + string? Chosen, + double? WalkForwardSharpe, + bool Finalist) +{ + /// Why its trial failed; null when it did not. + public string? Error { get; init; } +} + +/// An interval of a statistic: infinite on both sides when the series is too short to say anything. +public sealed record ReportInterval(double Low, double High); + +/// +/// The control against chance of a finalist: its daily Sharpe ratio on the real search data, the share of surrogate +/// repetitions that do as well or better, and the median and the 95th percentile of the repetitions. Null figures and +/// when the control cannot be run on its data. +/// +public sealed record TournamentControlResult(int Repetitions, int Seed, bool Centred, double Observed, double? Share, double? ReplicaMedian, double? ReplicaHigh) +{ + /// Why the control could not run, in Italian; null when it ran. + public string? Unavailable { get; init; } +} + +/// The chosen variant of a finalist on the final tract, read once: net result at plain and doubled costs, return, Sharpe and drawdown at plain costs. +public sealed record TournamentHoldoutResult(DateOnly From, DateOnly To, decimal NetResult, decimal NetAtDoubleCosts, double TotalReturn, double Sharpe, double MaxDrawdown); + +/// A finalist with every figure of its verdict and the checks: it passes only when all of them pass. +public sealed record TournamentFinalistResult( + string Label, + string Strategy, + string Group, + string Market, + string Chosen, + int PeriodsPerYear, + double Sharpe, + DeflatedSharpe DeflatedSharpe, + ReportInterval SharpeInterval, + decimal NetAtDoubleCosts, + double MaxDrawdown, + bool LookAheadPassed, + TournamentControlResult Control, + TournamentHoldoutResult Holdout, + IReadOnlyList Checks, + bool Passed); + +/// +/// The report of a tournament (ADR 0026 point 9): the common number of trials with its parts, the bar it sets, the variance of +/// the field, the common probability of overfitting, the effective number of bets of the finalists, every contender, every +/// finalist with its checks, and what the judge does not do yet. It passes when at least one finalist passes. +/// +public sealed record TournamentReport( + Guid TournamentId, + string Name, + string PlanHash, + TournamentTrialsCount Trials, + double Bar, + double FieldVariance, + ReportOverfitting? Overfitting, + double? EffectiveBets, + IReadOnlyList Contenders, + IReadOnlyList Finalists, + int PassedCount, + bool Passed, + IReadOnlyList Limitations, + DateTimeOffset ComputedAt, + double Seconds) +{ + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); + + public static TournamentReport FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty tournament report"); +} + +/// Keys of the checks of a finalist that a single trial does not have. +public static class TournamentCheckKeys +{ + public const string Control = "control"; + public const string Holdout = "holdout"; +} + +/// The daily returns of one variant and the days they fall on (the day of the equity point each return ends at). +public sealed record VariantSeries(string Parameters, IReadOnlyList Days, double[] Returns) +{ + public static VariantSeries Of(string parameters, BacktestRun run) + { + ArgumentNullException.ThrowIfNull(run); + return new VariantSeries(parameters, [.. run.Equity.Skip(1).Select(p => p.Day)], run.DailyReturns()); + } +} + +/// What the judge knows of a contender: its trial and, when it is done, its report and the series of every variant of its grid. +public sealed record ContenderOutcome(TournamentContender Contender, Trial Trial, BacktestReport? Report, IReadOnlyList Variants) +{ + /// The Sharpe ratio of the walk-forward windows; null when the trial failed or had too few days for them. + public double? WalkForwardSharpe => Report?.WalkForward is { } wf && double.IsFinite(wf.Sharpe) ? wf.Sharpe : null; + + /// The series of the chosen variant. + public VariantSeries Chosen => Variants.FirstOrDefault(v => v.Parameters == (Report?.Judged ?? Report?.Chosen)) + ?? throw new InvalidOperationException("The chosen variant of " + Contender.Label + " has no run."); +} + +/// What the units of a finalist gave: the repetitions of its control (none when unavailable) and its runs on the final tract by cost multiplier. +public sealed record FinalistOutcome(string Label, bool Centred, IReadOnlyList Replicas, string? ControlUnavailable, IReadOnlyDictionary Holdout); + +/// +/// The judge of a tournament on what its trials and units gave (ADR 0026 point 7): pure, no clock and no database. It chooses +/// the finalists, counts the trials, computes the common statistics and writes the report. +/// +public static class TournamentJudge +{ + /// Rounds of the block bootstrap of the Sharpe interval of a finalist. + public const int IntervalRounds = 1000; + + public const double IntervalConfidence = 0.95; + + /// + /// The finalists, best first: among the contenders whose trial is done and has a walk-forward Sharpe, the best of every pair + /// of group and market, then the best of them. Ties go to the contender written first. + /// + public static IReadOnlyList Finalists(TournamentPlan plan, IReadOnlyList contenders) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(contenders); + var order = plan.Contenders.Select((c, i) => (c.Label, i)).ToDictionary(x => x.Label, x => x.i, StringComparer.Ordinal); + return + [ + .. contenders + .Where(c => c.Trial.Status == TrialStatuses.Done && c.WalkForwardSharpe is not null) + .GroupBy(c => (c.Contender.Group, c.Contender.Market)) + .Select(g => g.OrderByDescending(c => c.WalkForwardSharpe).ThenBy(c => order[c.Contender.Label]).First()) + .OrderByDescending(c => c.WalkForwardSharpe).ThenBy(c => order[c.Contender.Label]) + .Take(plan.Finalists.Max) + .Select(c => c.Contender.Label), + ]; + } + + /// The report of the tournament from its contenders, its finalists (as stored when the final tract was opened) and their units. + public static TournamentReport Report( + Guid tournamentId, TournamentPlan plan, string planHash, IReadOnlyList contenders, IReadOnlyList finalists, + IReadOnlyList outcomes, int registryVariants, DateTimeOffset now, TimeSpan elapsed) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(contenders); + ArgumentNullException.ThrowIfNull(finalists); + ArgumentNullException.ThrowIfNull(outcomes); + var watch = System.Diagnostics.Stopwatch.StartNew(); + var done = contenders.Where(c => c.Report is not null).ToList(); + + // N: every planned variant of every contender, failed or not, the combinations of the finalists, the register and what was tried outside it. + var count = new TournamentTrialsCount( + contenders.Sum(c => c.Trial.Variants), + TournamentStatistics.Combinations(finalists.Count, plan.Combinations.WeightSchemes.Count), + registryVariants, + plan.PriorCounted.Sum(p => p.Variants), + 0); + count = count with { Total = TournamentStatistics.CommonTrials(count.Field, count.Combinations, count.Registry, count.Prior) }; + + var field = TournamentStatistics.FieldVariance([.. done.Select(c => new FieldSharpes(c.Report!.PeriodsPerYear, [.. c.Report.Variants.Where(v => !v.OutsideGrid).Select(v => v.Sharpe)]))]); + var all = TournamentStatistics.Align([.. done.SelectMany(c => c.Variants).Select(v => (v.Days, (IReadOnlyList)v.Returns))]); + var pbo = TournamentStatistics.CommonOverfitting(all, plan.Validation.OverfittingGroups); + var overfitting = pbo is null ? null : new ReportOverfitting(pbo.Groups, pbo.Combinations, pbo.Variants, pbo.Probability); + + var byLabel = contenders.ToDictionary(c => c.Contender.Label, StringComparer.Ordinal); + var chosen = finalists.Select(f => byLabel[f].Chosen).ToList(); + double? bets = chosen.Count == 0 ? null + : TournamentStatistics.EffectiveBets(TournamentStatistics.Align([.. chosen.Select(v => (v.Days, (IReadOnlyList)v.Returns))]).Returns); + + var outcomeOf = outcomes.ToDictionary(o => o.Label, StringComparer.Ordinal); + var results = finalists.Select(f => Finalist(plan, byLabel[f], outcomeOf[f], count.Total, field, pbo)).ToList(); + var passed = results.Count(r => r.Passed); + + List limitations = + [ + "La varianza del campo conta solo le varianti dei concorrenti di questo campionato: le prove fatte prima entrano nel numero delle prove, non nella varianza.", + "I mercati con calendari diversi (crypto tutti i giorni, valute e azioni nei giorni feriali) sono messi su un solo calendario: un giorno senza seduta vale un rendimento zero.", + Surrogates.CorporateActionsRefused, + "Le combinazioni dei finalisti e le prove di stress arrivano nella Fase 16: le combinazioni contano già nel numero delle prove.", + ]; + limitations.AddRange(contenders.Where(c => c.Trial.Status == TrialStatuses.Failed) + .Select(c => $"La prova del concorrente «{c.Contender.Label}» non è arrivata in fondo: non può essere finalista, ma le sue varianti contano lo stesso.")); + + return new TournamentReport( + tournamentId, + plan.Name, + planHash, + count, + TournamentStatistics.Bar(count.Total), + field, + overfitting, + bets, + [.. contenders.Select(c => new TournamentContenderResult(c.Contender.Label, c.Contender.Strategy, c.Contender.Group, c.Contender.Market, c.Trial.Id, c.Trial.Status, + c.Trial.Variants, c.Report?.Judged ?? c.Report?.Chosen, c.WalkForwardSharpe, finalists.Contains(c.Contender.Label, StringComparer.Ordinal)) { Error = c.Trial.Error })], + results, + passed, + passed > 0, + limitations, + now, + (elapsed + watch.Elapsed).TotalSeconds); + } + + private static TournamentFinalistResult Finalist(TournamentPlan plan, ContenderOutcome contender, FinalistOutcome outcome, int trials, double field, OverfittingResult? pbo) + { + var report = contender.Report!; + var series = contender.Chosen; + var year = report.PeriodsPerYear; + var moments = Moments.Of(series.Returns); + var dsr = TournamentStatistics.CommonDeflated(series.Returns, year, trials, field); + var (low, high) = TournamentStatistics.Interval(series.Returns, s => Moments.Of(s).Sharpe, PathBootstrap.Block, IntervalRounds, IntervalConfidence, plan.Control.Seed); + + var sorted = outcome.Replicas.Order().ToArray(); + var control = outcome.ControlUnavailable is not null || sorted.Length == 0 + ? new TournamentControlResult(plan.Control.Repetitions, plan.Control.Seed, outcome.Centred, moments.Sharpe, null, null, null) { Unavailable = outcome.ControlUnavailable } + : new TournamentControlResult(plan.Control.Repetitions, plan.Control.Seed, outcome.Centred, moments.Sharpe, TournamentStatistics.ControlShare(moments.Sharpe, sorted), + Percentile(sorted, 0.5), Percentile(sorted, 0.95)); + + var plain = outcome.Holdout[1m]; + var doubledRun = outcome.Holdout[2m]; + var metrics = BacktestMetrics.Of(plain, year); + var holdout = new TournamentHoldoutResult(plan.HoldoutFrom, contender.Contender.Data.To, plain.NetResult, doubledRun.NetResult, metrics.TotalReturn, metrics.Sharpe, + metrics.MaxDrawdown); + + var t = plan.Thresholds; + var doubled = report.Costs.FirstOrDefault(c => c.Multiplier == 2m); + List checks = + [ + new(ReportCheckKeys.DoubleCosts, "Risultato netto con costi doppi", doubled is null ? null : (double)doubled.NetResult, ">", (double)t.MinNetAtDoubleCosts, "money", + doubled is not null && doubled.NetResult > t.MinNetAtDoubleCosts), + new(ReportCheckKeys.DeflatedSharpe, "Deflated Sharpe Ratio sul numero comune di prove", dsr.Value, "≥", t.MinDeflatedSharpe, "ratio", dsr.Value >= t.MinDeflatedSharpe), + new(ReportCheckKeys.Overfitting, "Probabilità di sovra-adattamento di tutto il campo (PBO)", pbo?.Probability, "≤", t.MaxOverfitting, "ratio", + pbo is not null && pbo.Probability <= t.MaxOverfitting), + new(ReportCheckKeys.Drawdown, "Calo massimo", report.Metrics.MaxDrawdown, "≤", t.MaxDrawdown, "percent", report.Metrics.MaxDrawdown <= t.MaxDrawdown), + new(ReportCheckKeys.LookAhead, "Decisioni cambiate aggiungendo dati successivi", report.LookAhead.Changed, "=", 0, "count", report.LookAhead.Passed), + new(TournamentCheckKeys.Control, "Controllo contro il caso: quota di copie pari o migliori", control.Share, "≤", t.MaxControlShare, "ratio", + control.Share is { } share && share <= t.MaxControlShare), + new(TournamentCheckKeys.Holdout, "Risultato netto sul tratto finale con costi doppi", (double)holdout.NetAtDoubleCosts, "≥", (double)t.MinNetAtDoubleCosts, "money", + holdout.NetAtDoubleCosts >= t.MinNetAtDoubleCosts), + ]; + + return new TournamentFinalistResult(contender.Contender.Label, contender.Contender.Strategy, contender.Contender.Group, contender.Contender.Market, series.Parameters, year, + moments.Sharpe, dsr, new ReportInterval(low, high), doubled?.NetResult ?? 0m, report.Metrics.MaxDrawdown, report.LookAhead.Passed, control, holdout, checks, + checks.All(c => c.Passed == true)); + } + + // The value at a share of a sorted list, by the nearest rank below. + private static double Percentile(double[] sorted, double share) => sorted[(int)Math.Floor(share * (sorted.Length - 1))]; +} diff --git a/src/Anubis/Backtest/Tournaments.cs b/src/Anubis/Backtest/Tournaments.cs new file mode 100644 index 0000000..0a9f31e --- /dev/null +++ b/src/Anubis/Backtest/Tournaments.cs @@ -0,0 +1,473 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Db; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The thresholds of a tournament, fixed in its plan: those of a trial (SPEC 12.2) and the control against chance (ADR 0026 +/// point 4). Changing them after seeing the results needs an ADR. +/// +public sealed record TournamentThresholds(decimal MinNetAtDoubleCosts, double MinDeflatedSharpe, double MaxOverfitting, double MaxDrawdown, double MaxControlShare) +{ + public static TournamentThresholds Default { get; } = new( + TrialThresholds.Default.MinNetAtDoubleCosts, TrialThresholds.Default.MinDeflatedSharpe, TrialThresholds.Default.MaxOverfitting, TrialThresholds.Default.MaxDrawdown, 0.05); +} + +/// Words of the rules a plan writes down. +public static class TournamentRules +{ + /// At most one finalist for every pair of group and market. + public const string GroupAndMarket = "group_and_market"; + + /// Finalists are ranked by the Sharpe ratio of their walk-forward windows. + public const string WalkForwardSharpe = "walk_forward_sharpe"; + + public const string Pairs = "pairs"; + + public const string Whole = "whole"; + + public const string EqualWeights = "equal"; + + public const string InverseVolatility = "inverse_volatility"; + + public const string RiskParity = "risk_parity"; + + public const string Quarterly = "quarterly"; +} + +/// Who goes on to the final stage: at most , one per group and market, the best by walk-forward Sharpe. +public sealed record TournamentFinalists(int Max, string OnePer, string RankedBy) +{ + public static TournamentFinalists Default { get; } = new(8, TournamentRules.GroupAndMarket, TournamentRules.WalkForwardSharpe); +} + +/// The control against chance of every finalist: how many surrogate series and the seed of their signs. +public sealed record TournamentControl(int Repetitions, int Seed) +{ + public static TournamentControl Default { get; } = new(200, 20_261_202); +} + +/// +/// The combinations of finalists (ADR 0026 point 8), written in the plan now and run in Phase 16: every pair and the whole set, +/// with each weighting scheme, reading only the before and rebalanced every quarter. They count in +/// the number of trials from now on. +/// +public sealed record TournamentCombinations(IReadOnlyList Sets, IReadOnlyList WeightSchemes, int LookbackDays, string Rebalance) +{ + public static TournamentCombinations Default { get; } = new( + [TournamentRules.Pairs, TournamentRules.Whole], + [TournamentRules.EqualWeights, TournamentRules.InverseVolatility, TournamentRules.RiskParity], + 180, + TournamentRules.Quarterly); +} + +/// A named period of stress, recorded in the plan now; the stress tests run in Phase 16. +public sealed record StressWindow(string Name, DateOnly From, DateOnly To) +{ + public static IReadOnlyList Defaults { get; } = + [ + new("Crollo di marzo 2020", new DateOnly(2020, 2, 19), new DateOnly(2020, 3, 23)), + new("Inverno delle crypto 2022", new DateOnly(2022, 5, 5), new DateOnly(2022, 12, 31)), + ]; +} + +/// Variants tried before, outside the register (the protocols of docs/backtests): they count in N. +public sealed record PriorCount(string Source, string Strategy, int Variants) +{ + public static IReadOnlyList Defaults { get; } = + [ + new("docs/backtests", StrategyNames.CryptoTrend, 18), + new("docs/backtests", StrategyNames.CryptoRelativeMomentum, 9), + ]; +} + +/// +/// A contender of the plan: a fixed rule (its version) with the numbers of its grid, a group and a market, and its data over +/// the whole period, the final tract included. Its trial reads only up to the day before . +/// +public sealed record TournamentContender( + string Label, + string Strategy, + string StrategyVersion, + string Group, + string Market, + IReadOnlyDictionary> Grid, + TrialData Data, + int Variants); + +/// +/// The plan of a tournament (ADR 0026 point 2): contenders, data, costs, thresholds, the rule of the finalists, the control, +/// the combinations, the stress windows and the variants already counted, written before any result and never changed. Its +/// fingerprint is the SHA-256 of the text as stored, as for a trial (). +/// and are what the plan shows before the start: the number of trials it expects and the Sharpe ratio, in +/// standard deviations of the field, that chance alone would reach with so many. +/// +public sealed record TournamentPlan( + string Name, + IReadOnlyList Contenders, + DateOnly HoldoutFrom, + decimal InitialCapital, + IReadOnlyList CostMultipliers, + TournamentThresholds Thresholds, + TournamentFinalists Finalists, + TournamentControl Control, + TournamentCombinations Combinations, + IReadOnlyList StressWindows, + IReadOnlyList PriorCounted, + int RegistryVariantsAtPlanning, + int PlannedTrials, + double Bar, + TrialValidation Validation, + string Engine, + DateTimeOffset WrittenAt) +{ + /// The slippage in force when the plan was written (SPEC 11.6); null for the standard one. + public SlippageTable? Slippage { get; init; } + + /// The last day of the search: the trials of the contenders end here. + public DateOnly SearchTo => HoldoutFrom.AddDays(-1); + + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); + + public static TournamentPlan FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty tournament plan"); +} + +/// A contender as the user asks for it: the plan fills in the version, the grid and the count of variants. +public sealed record ContenderRequest( + string Label, + string Strategy, + string Group, + string Market, + string Source, + string Venue, + IReadOnlyList Symbols, + DateOnly From, + DateOnly To, + IReadOnlyDictionary>? Grid = null); + +/// What a new tournament is: its contenders, the first day of the final tract and the capital of every trial. +public sealed record TournamentRequest(string Name, IReadOnlyList Contenders, DateOnly HoldoutFrom, decimal InitialCapital) +{ + /// The control of the plan; null for 200 repetitions and the default seed. + public TournamentControl? Control { get; init; } + + /// The variants tried outside the register; null for those of docs/backtests. + public IReadOnlyList? PriorCounted { get; init; } + + /// The stress windows; null for the default ones. + public IReadOnlyList? StressWindows { get; init; } +} + +/// A tournament plan that cannot be written, with the reason in Italian. Nothing is written. +public sealed class TournamentPlanException(string message) : Exception(message); + +/// Builds and checks the plan of a tournament: pure, nothing is read or written. +public static class TournamentPlans +{ + public const int MaxContenders = 100; + + public const int MaxRepetitions = 10_000; + + /// The shortest final tract, in calendar days. + public const int MinHoldoutDays = 30; + + /// + /// The plan of and the plans of the trials of its contenders, which read the search window only + /// (to the day before the final tract). Every check fails with an Italian message before anything is built. + /// + public static (TournamentPlan Plan, IReadOnlyList<(TrialPlan Plan, int Variants)> Trials) BuildPlan( + TournamentRequest request, DateTimeOffset now, int registryVariants, Func families, SlippageTable? slippage = null) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(families); + ArgumentOutOfRangeException.ThrowIfNegative(registryVariants); + var it = CultureInfo.GetCultureInfo("it-IT"); + if (string.IsNullOrWhiteSpace(request.Name)) + { + throw new TournamentPlanException("Dai un nome al campionato."); + } + + if (request.Contenders is not { Count: > 0 }) + { + throw new TournamentPlanException("Serve almeno un concorrente."); + } + + if (request.Contenders.Count > MaxContenders) + { + throw new TournamentPlanException($"Al massimo {MaxContenders} concorrenti per campionato."); + } + + var thresholds = TournamentThresholds.Default; + var control = request.Control ?? TournamentControl.Default; + var fewest = (int)Math.Ceiling(Math.Round(1 / thresholds.MaxControlShare, 9)); // 1 / 0.05 is 20, not a hair more + if (control.Repetitions < fewest || control.Repetitions > MaxRepetitions) + { + throw new TournamentPlanException($"Le ripetizioni del controllo contro il caso vanno da {fewest} a {MaxRepetitions}."); + } + + var prior = request.PriorCounted ?? PriorCount.Defaults; + if (prior.Any(p => p is null || p.Variants < 0 || string.IsNullOrWhiteSpace(p.Strategy))) + { + throw new TournamentPlanException("Le prove già contate hanno bisogno di una strategia e di un numero non negativo di varianti."); + } + + var stress = request.StressWindows ?? StressWindow.Defaults; + if (stress.FirstOrDefault(w => w is null || string.IsNullOrWhiteSpace(w.Name) || w.From > w.To) is { } wrong) + { + throw new TournamentPlanException($"La finestra di stress «{wrong?.Name}» non ha un nome o finisce prima di cominciare."); + } + + var contenders = new List(); + var trials = new List<(TrialPlan Plan, int Variants)>(); + var labels = new HashSet(StringComparer.Ordinal); + foreach (var c in request.Contenders) + { + var label = c?.Label?.Trim() ?? ""; + if (c is null || label.Length == 0) + { + throw new TournamentPlanException("Ogni concorrente ha bisogno di un'etichetta."); + } + + if (!labels.Add(label)) + { + throw new TournamentPlanException($"L'etichetta «{label}» è usata due volte."); + } + + if (string.IsNullOrWhiteSpace(c.Group) || string.IsNullOrWhiteSpace(c.Market)) + { + throw new TournamentPlanException($"Il concorrente «{label}» ha bisogno di un gruppo e di un mercato."); + } + + if (request.HoldoutFrom.AddDays(-1) <= c.From) + { + throw new TournamentPlanException(string.Create(it, $"Il tratto finale deve cominciare dopo l'inizio di «{label}», che comincia il {c.From:dd/MM/yyyy}.")); + } + + if (c.To.DayNumber - request.HoldoutFrom.DayNumber + 1 < MinHoldoutDays) + { + throw new TournamentPlanException(string.Create(it, $"Il tratto finale di «{label}» deve durare almeno {MinHoldoutDays} giorni: i suoi dati finiscono il {c.To:dd/MM/yyyy}.")); + } + + var family = families(c.Strategy) ?? throw new TournamentPlanException($"Concorrente «{label}»: strategia sconosciuta."); + (TrialPlan Plan, int Variants) trial; + try + { + trial = Laboratory.BuildPlan(new TrialRequest(c.Strategy, c.Source, c.Venue, c.Symbols, c.From, request.HoldoutFrom.AddDays(-1), request.InitialCapital, c.Grid), + now, slippage, families); + } + catch (TrialRequestException ex) + { + throw new TournamentPlanException($"Concorrente «{label}»: {ex.Message}"); + } + + trials.Add(trial); + contenders.Add(new TournamentContender(label, family.Id, family.Version, c.Group.Trim(), c.Market.Trim(), trial.Plan.Grid, + trial.Plan.Data with { To = c.To }, trial.Variants)); + } + + var combinations = TournamentCombinations.Default; + var finalists = TournamentFinalists.Default; + var places = Math.Min(finalists.Max, contenders.Select(c => (c.Group, c.Market)).Distinct().Count()); + var planned = TournamentStatistics.CommonTrials(contenders.Sum(c => c.Variants), TournamentStatistics.Combinations(places, combinations.WeightSchemes.Count), + registryVariants, prior.Sum(p => p.Variants)); + var plan = new TournamentPlan( + request.Name.Trim(), + contenders, + request.HoldoutFrom, + request.InitialCapital, + [1m, 2m, 3m], + thresholds, + finalists, + control, + combinations, + stress, + prior, + registryVariants, + planned, + TournamentStatistics.Bar(planned), + TrialValidation.Default, + BacktestEngine.Version, + now) + { + Slippage = slippage == SlippageTable.Standard ? null : slippage, + }; + return (plan, trials); + } +} + +public static class TournamentStatuses +{ + public const string Planned = "planned"; + public const string Running = "running"; + public const string Judging = "judging"; + public const string Done = "done"; + public const string Failed = "failed"; +} + +/// A row of the register of the tournaments. +public sealed record Tournament( + Guid Id, + string Name, + TournamentPlan Plan, + string PlanHash, + string Status, + string? Verdict, + IReadOnlyList? Finalists, + string? Error, + DateTimeOffset? HoldoutOpenedAt, + DateTimeOffset CreatedAt, + DateTimeOffset? StartedAt, + DateTimeOffset? FinishedAt) +{ + public bool IsFinished => Status is TournamentStatuses.Done or TournamentStatuses.Failed; + + /// The stored plan text still gives the stored hash: nobody changed it after it was written. + public bool PlanIntact { get; init; } = true; +} + +/// +/// The register of the tournaments (ADR 0026). The plan and the trials of the contenders are written in one transaction before +/// any result, and the plan is never updated. The final tract is opened once: the finalists are written with the moment it +/// was opened, and a second opening gets back the first finalists. +/// +public sealed class TournamentStore(Database db, IClock clock) +{ + private const string Columns = "id, name, plan, plan_hash, status, verdict, finalists, error, holdout_opened_at, created_at, started_at, finished_at"; + + /// The plan and the trials of its contenders, in the order of the plan, all planned. + public async Task PlanAsync(TournamentPlan plan, IReadOnlyList<(TrialPlan Plan, int Variants)> trials, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(trials); + if (trials.Count != plan.Contenders.Count) + { + throw new ArgumentException("One trial for every contender.", nameof(trials)); + } + + var id = await db.WriteAsync(async s => + { + var id = Ids.NewId(clock); + var json = plan.ToJson(); + await s.ExecuteAsync( + "INSERT INTO tournaments (id, name, plan, plan_hash, status, created_at) VALUES (@id, @n, @p, @h, @st, @now)", + cancellationToken, ("id", id), ("n", plan.Name), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("st", TournamentStatuses.Planned), + ("now", clock.UtcNow)).ConfigureAwait(false); + foreach (var (trial, variants) in trials) + { + await TrialStore.PlanAsync(s, clock, trial, variants, null, id, cancellationToken).ConfigureAwait(false); + } + + return id; + }, cancellationToken).ConfigureAwait(false); + return (await GetAsync(id, cancellationToken).ConfigureAwait(false))!; + } + + public Task GetAsync(Guid id, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM tournaments WHERE id = @id", Read, ("id", id)), cancellationToken); + + public Task ReportJsonAsync(Guid id, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT report FROM tournaments WHERE id = @id AND report IS NOT NULL", r => r.Json("report").Text, ("id", id)), + cancellationToken); + + /// The first trial of a contender started. + public Task StartAsync(Guid id, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @r, started_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("r", TournamentStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned)), cancellationToken); + + /// The tournament goes to its judge; true when it is being judged (now, or since before a restart). + public async Task JudgeAsync(Guid id, CancellationToken cancellationToken) => + await db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE tournaments SET status = @j, started_at = COALESCE(started_at, @now) WHERE id = @id AND status IN (@p, @r)", cancellationToken, + ("j", TournamentStatuses.Judging), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running)).ConfigureAwait(false); + return await s.FirstOrDefaultAsync("SELECT status FROM tournaments WHERE id = @id", r => r.Text("status"), ("id", id)).ConfigureAwait(false) == TournamentStatuses.Judging; + }, cancellationToken).ConfigureAwait(false); + + /// + /// Opens the final tract for , once: the first call writes them with the moment, every later + /// one gets back what the first wrote. The finalists never change after the tract is opened. + /// + public async Task<(IReadOnlyList Finalists, DateTimeOffset OpenedAt)> OpenHoldoutAsync(Guid id, IReadOnlyList finalists, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(finalists); + var stored = await db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE tournaments SET finalists = @f, holdout_opened_at = @now WHERE id = @id AND holdout_opened_at IS NULL", cancellationToken, + ("f", new DbJson(JsonSerializer.Serialize(finalists, TrialPlan.Json))), ("now", clock.UtcNow), ("id", id)).ConfigureAwait(false); + return await s.FirstOrDefaultAsync("SELECT finalists, holdout_opened_at FROM tournaments WHERE id = @id", + r => (Finalists: r.Json("finalists").Text, OpenedAt: r.Moment("holdout_opened_at")), ("id", id)).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + return (JsonSerializer.Deserialize(stored.Finalists, TrialPlan.Json) ?? [], stored.OpenedAt); + } + + /// The tournament judged, with its report; the outcomes of its units are dropped, the rows stay as a record. + public Task FinishAsync(Guid id, bool passed, string reportJson, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE tournaments SET status = @d, verdict = @v, report = @rep, finished_at = @now WHERE id = @id AND status = @j", cancellationToken, + ("d", TournamentStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), + ("id", id), ("j", TournamentStatuses.Judging)).ConfigureAwait(false); + await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + /// The tournament failed, with the reason; the outcomes of its units are dropped as when it is done. + public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE tournaments SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r, @j)", cancellationToken, + ("f", TournamentStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running), + ("j", TournamentStatuses.Judging)).ConfigureAwait(false); + await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + /// After a restart: the tournaments not finished whose trials are all finished, oldest first, to judge again. + public async Task> ResumableAsync(CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT t.id FROM tournaments t WHERE t.status IN (@p, @r, @j) AND NOT EXISTS " + + "(SELECT 1 FROM backtest_trials b WHERE b.tournament_id = t.id AND b.status IN (@tp, @tr)) ORDER BY t.created_at, t.id", + r => r.Id("id"), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running), ("j", TournamentStatuses.Judging), ("tp", TrialStatuses.Planned), + ("tr", TrialStatuses.Running)), cancellationToken).ConfigureAwait(false); + + /// + /// The variants of the register outside tournament : every finished trial of every strategy, up to + /// when given (the moment the final tract was opened, so a resumed judge counts the same). + /// + public async Task RegistryVariantsAsync(Guid? except, DateTimeOffset? until, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT variants, finished_at, tournament_id FROM backtest_trials WHERE status = @d", + r => (Variants: (int)r.Number("variants"), FinishedAt: r.MomentOrNull("finished_at"), Tournament: r.IdOrNull("tournament_id")), + ("d", TrialStatuses.Done)), cancellationToken).ConfigureAwait(false); + return rows.Where(r => except is null || r.Tournament != except) + .Where(r => until is null || (r.FinishedAt is { } at && at <= until)) + .Sum(r => r.Variants); + } + + private static Task ReleaseUnitsAsync(DbSession s, Guid id, CancellationToken cancellationToken) => + s.ExecuteAsync("UPDATE tournament_units SET outcome = NULL WHERE tournament_id = @id AND outcome IS NOT NULL", cancellationToken, ("id", id)); + + private static Tournament Read(DbRow r) + { + var plan = r.Json("plan").Text; + return new Tournament( + r.Id("id"), + r.Text("name"), + TournamentPlan.FromJson(plan), + r.Text("plan_hash"), + r.Text("status"), + r.TextOrNull("verdict"), + r.IsNull("finalists") ? null : JsonSerializer.Deserialize(r.Json("finalists").Text, TrialPlan.Json), + r.TextOrNull("error"), + r.MomentOrNull("holdout_opened_at"), + r.Moment("created_at"), + r.MomentOrNull("started_at"), + r.MomentOrNull("finished_at")) + { + PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"), + }; + } +} diff --git a/src/Anubis/Backtest/TrialEngines.cs b/src/Anubis/Backtest/TrialEngines.cs index 16a6368..598fff2 100644 --- a/src/Anubis/Backtest/TrialEngines.cs +++ b/src/Anubis/Backtest/TrialEngines.cs @@ -50,6 +50,19 @@ public interface ITrialEngine /// What the judged variant should give once it trades, from its run and its returns. TrialExpectations Expected(BacktestRun run, double[] returns); + + /// + /// True when the engine only buys: its control against chance turns the signs around the mean return, so the drift alone + /// beats nothing (ADR 0026 point 4). An engine that does not say so is taken as one that only buys. + /// + bool LongOnly => true; + + /// + /// The same engine on the surrogate of its data (): every day of every instrument takes the sign of + /// , around the mean when . An engine without surrogates, or data that + /// cannot have them (corporate actions), throws with the reason for the user. + /// + ITrialEngine Surrogate(DaySigns signs, bool centred) => throw new NotSupportedException("Questo motore non prevede ancora il controllo contro il caso."); } /// @@ -101,6 +114,11 @@ public sealed class DailyTrialEngine : ITrialEngine public IReadOnlyList Limitations() => TrialRunner.Limitations(_plan, _family, _data); + /// The daily engine buys and sells what it holds: it never goes short. + public bool LongOnly => true; + + public ITrialEngine Surrogate(DaySigns signs, bool centred) => new DailyTrialEngine(_plan, _family, Surrogates.Of(_data, signs, centred)); + public TrialExpectations Expected(BacktestRun run, double[] returns) { ArgumentNullException.ThrowIfNull(run); diff --git a/src/Anubis/Backtest/TrialUnits.cs b/src/Anubis/Backtest/TrialUnits.cs index 368dbe0..f58f2f5 100644 --- a/src/Anubis/Backtest/TrialUnits.cs +++ b/src/Anubis/Backtest/TrialUnits.cs @@ -25,6 +25,15 @@ public enum TrialUnitKind /// The look-ahead check of the judged variant. LookAhead, + + /// + /// A repetition of the control against chance of a finalist of a tournament (its ): the + /// chosen variant on surrogate data. Only its daily Sharpe ratio is kept. + /// + Control, + + /// The chosen variant of a finalist of a tournament on the final tract, read once, at the cost multiplier of its key. + Holdout, } /// @@ -41,8 +50,12 @@ public sealed record TrialUnitKey(TrialUnitKind Kind, int Index, string Paramete $"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}"); } -/// The outcome of one unit: a run, or the result of the look-ahead check. -public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead); +/// The outcome of one unit: a run, the result of the look-ahead check, or the daily Sharpe ratio of a control. +public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead) +{ + /// The daily Sharpe ratio of a repetition of the control (); null for the other units. + public double? Sharpe { get; init; } +} /// /// Every engine execution a trial needs, done: what reads. is in the order @@ -283,12 +296,18 @@ internal static class TrialUnitOutcomes decimal WrittenOff, IReadOnlyList Baskets); + private sealed record StoredControl(double Sharpe); + public static byte[] Encode(TrialUnitResult result) { ArgumentNullException.ThrowIfNull(result); - var json = result.Key.Kind == TrialUnitKind.LookAhead - ? JsonSerializer.SerializeToUtf8Bytes(result.LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."), TrialPlan.Json) - : JsonSerializer.SerializeToUtf8Bytes(Stored(result.Run ?? throw new InvalidOperationException("The unit " + result.Key.Text + " has no run.")), TrialPlan.Json); + var json = result.Key.Kind switch + { + TrialUnitKind.LookAhead => JsonSerializer.SerializeToUtf8Bytes(result.LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."), TrialPlan.Json), + TrialUnitKind.Control => JsonSerializer.SerializeToUtf8Bytes(new StoredControl(result.Sharpe ?? throw new InvalidOperationException("The control unit has no Sharpe ratio.")), + TrialPlan.Json), + _ => JsonSerializer.SerializeToUtf8Bytes(Stored(result.Run ?? throw new InvalidOperationException("The unit " + result.Key.Text + " has no run.")), TrialPlan.Json), + }; using var buffer = new MemoryStream(); using (var zip = new GZipStream(buffer, CompressionLevel.Optimal, leaveOpen: true)) { @@ -308,6 +327,12 @@ internal static class TrialUnitOutcomes return new TrialUnitResult(key, null, JsonSerializer.Deserialize(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome")); } + if (key.Kind == TrialUnitKind.Control) + { + var control = JsonSerializer.Deserialize(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome"); + return new TrialUnitResult(key, null, null) { Sharpe = control.Sharpe }; + } + var run = JsonSerializer.Deserialize(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome"); return new TrialUnitResult(key, new BacktestRun(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, [], run.Notes) { @@ -382,6 +407,14 @@ public sealed class TrialUnitStore(Database db, IClock clock) ("r", TrialUnitStatuses.Running)), cancellationToken); } + /// The outcomes of the units of a finished trial that still have one (those of a tournament until it ends), by key. + public async Task> OutcomesAsync(Guid trialId, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync("SELECT unit_key, outcome FROM tournament_units WHERE trial_id = @t AND status = @d AND outcome IS NOT NULL", + r => (Key: r.Text("unit_key"), Outcome: r.Bytes("outcome")), ("t", trialId), ("d", TrialUnitStatuses.Done)), cancellationToken).ConfigureAwait(false); + return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal); + } + /// The units of a trial, in the order they were claimed. public async Task> ListAsync(Guid trialId, CancellationToken cancellationToken) => await db.ReadAsync(s => s.QueryAsync( diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 48794ad..568fd7f 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -168,6 +168,9 @@ public sealed record Trial( /// The quarterly review that registered it; null for the user's. public Guid? ReviewId { get; init; } + + /// The tournament it is the trial of a contender of; null outside a tournament. + public Guid? TournamentId { get; init; } } /// The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios. @@ -182,7 +185,7 @@ public sealed record PriorTrials(int Trials, int Variants, IReadOnlyList /// public sealed class TrialStore(Database db, IClock clock) { - private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at, review_id"; + private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at, review_id, tournament_id"; public async Task PlanAsync(TrialPlan plan, int variants, CancellationToken cancellationToken) { @@ -191,7 +194,11 @@ public sealed class TrialStore(Database db, IClock clock) } /// The same as part of a transaction: the plans of a quarterly review are written together. - public static async Task PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, CancellationToken cancellationToken) + public static Task PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, CancellationToken cancellationToken) => + PlanAsync(s, clock, plan, variants, review, null, cancellationToken); + + /// The same for the trial of a contender, written with the plan of its tournament. + public static async Task PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, Guid? tournament, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(clock); @@ -199,10 +206,10 @@ public sealed class TrialStore(Database db, IClock clock) var id = Ids.NewId(clock); var json = plan.ToJson(); await s.ExecuteAsync( - "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, review_id) " + - "VALUES (@id, @s, @v, @p, @h, @n, @st, @now, @rev)", + "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, review_id, tournament_id) " + + "VALUES (@id, @s, @v, @p, @h, @n, @st, @now, @rev, @tour)", cancellationToken, ("id", id), ("s", plan.Strategy), ("v", plan.StrategyVersion), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), - ("n", variants), ("st", TrialStatuses.Planned), ("now", clock.UtcNow), ("rev", review)).ConfigureAwait(false); + ("n", variants), ("st", TrialStatuses.Planned), ("now", clock.UtcNow), ("rev", review), ("tour", tournament)).ConfigureAwait(false); return id; } @@ -210,6 +217,11 @@ public sealed class TrialStore(Database db, IClock clock) public async Task> OfReviewAsync(Guid review, CancellationToken cancellationToken) => await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE review_id = @r ORDER BY created_at, id", Read, ("r", review)), cancellationToken).ConfigureAwait(false); + /// The trials of the contenders of a tournament, in the order of its plan. + public async Task> OfTournamentAsync(Guid tournament, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE tournament_id = @t ORDER BY created_at, id", Read, ("t", tournament)), + cancellationToken).ConfigureAwait(false); + public Task GetAsync(Guid id, CancellationToken cancellationToken) => db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM backtest_trials WHERE id = @id", Read, ("id", id)), cancellationToken); @@ -316,6 +328,7 @@ public sealed class TrialStore(Database db, IClock clock) { PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"), ReviewId = r.IdOrNull("review_id"), + TournamentId = r.IdOrNull("tournament_id"), }; } } diff --git a/tests/Anubis.Tests/TournamentTests.cs b/tests/Anubis.Tests/TournamentTests.cs new file mode 100644 index 0000000..906b9d2 --- /dev/null +++ b/tests/Anubis.Tests/TournamentTests.cs @@ -0,0 +1,631 @@ +using System.Globalization; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// 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. +/// +[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); + + /// Warm-up of 450 days before the search, as every trial reads. + private static readonly DateOnly SearchFrom = Synthetic.Start.AddDays(TrialData.WarmupDays); + + private static readonly Dictionary> OneGrid = new() { ["lookback"] = [20m], ["entry"] = [1m] }; + + private static readonly Dictionary> EdgeGrid = new() { ["lookback"] = [20m], ["entry"] = [1.5m] }; + + private static readonly Dictionary> 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> { ["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(() => 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()); + } + + /// + /// 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. + /// + [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(); + 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(() => 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(); + 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(() => 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(); + var outcomes = new List(); + 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(() => TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportOfATournamentRoundTrips() + { + var checks = new List + { + 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); + } + + /// The figures a resumed judge must give again: everything but the identities and the seconds. + 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}"); + + /// A short field: 1100 days a series, a final tract of 100 days. + 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> 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> 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, + }; + + /// Runs the trials of a tournament in the order of its plan: the last one brings it to its judge. + 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 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> 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> 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))); + + /// The signs of a surrogate as text, to tell which repetition an engine was given. + private static string SignsOf(DaySigns signs) => + string.Concat(Enumerable.Range(0, Math.Min(signs.Count, 256)).Select(i => signs[signs.First.AddDays(i)] > 0 ? '+' : '-')); + + /// Synthetic series by symbol, read as the laboratory reads data (from the warm-up to the last day asked), with every read recorded. + private sealed class SyntheticField + { + private readonly Dictionary> _bars = new(StringComparer.Ordinal); + private readonly List _reads = []; + + public IReadOnlyList Reads + { + get + { + lock (_reads) + { + return [.. _reads]; + } + } + } + + public void Add(string symbol, IReadOnlyList bars) => _bars[symbol] = bars; + + public Task 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")); + } + } + + /// An engine in between: it records the runs on surrogates (with the repetition their signs belong to) and on the final tract. + private sealed class CountingEngine(ITrialEngine inner, List calls, IReadOnlyDictionary replicas, string name, string? tag, Action? 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 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 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); + } +}