diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index 99c3fd0..f01cc4f 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -53,6 +53,13 @@ public sealed record BacktestTrade(string Symbol, DateOnly Opened, DateOnly? Clo public bool IsClosed => Closed is not null; } +/// +/// A basket from its first level to its exit: the relation it trades (a pair of symbols or one), the units of each order, +/// how many levels it reached, its legs, why it closed (null while open) and its result net of every cost, in the dataset +/// currency. Only the basket engine writes them. +/// +public sealed record BacktestBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList Legs, string? ExitReason, decimal Result); + /// What the strategy proposed on a day, and what was left after correctives and risk. public sealed record DecisionRecord(DateOnly Day, IReadOnlyList Proposed, IReadOnlyList Final); @@ -80,6 +87,9 @@ public sealed record BacktestRun( /// Value of the leftovers below the minimum written off after an exit (SPEC 7.2). public decimal WrittenOff { get; init; } + /// The baskets of an engine that trades them, in the order they opened; empty for the daily engine. + public IReadOnlyList Baskets { get; init; } = []; + /// Daily returns of the equity, one per session after the first. public double[] DailyReturns() { diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 60e4e1d..c0e1b95 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -10,6 +10,9 @@ namespace Anubis.Backtest; /// An instrument of the report: where its bars come from and what period they cover. public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? First, DateOnly? Last, int Bars, int Actions, string Source); +/// A basket of the judged variant (), as the report shows it. +public sealed record ReportBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList Legs, string? ExitReason, decimal Result); + /// A point of the equity curve of the chosen variant and of buy and hold, on the same day. public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark); @@ -95,6 +98,9 @@ public sealed record BacktestReport( /// The variant in use, when the figures, the checks and the curve are its own (); null when they are those of the chosen one. public string? Judged { get; init; } + /// The last baskets of the judged variant, at most ; null (left out) for an engine without baskets. + public IReadOnlyList? Baskets { get; init; } + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty report"); @@ -105,7 +111,8 @@ public sealed record BacktestReport( /// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily /// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan /// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice, -/// the overfitting and the number of tries. +/// the overfitting and the number of tries. The engine that runs the variants is an : the daily one +/// () unless the caller gives another. /// public static class TrialRunner { @@ -113,6 +120,7 @@ public static class TrialRunner public const int MaxTrades = 300; + /// A trial of a daily family on daily data: the judge with the . public static (BacktestReport Report, TrialSummary Summary) Run( Guid trialId, TrialPlan plan, string planHash, IStrategyFamily family, BacktestDataset data, PriorTrials prior, DateTimeOffset now, Action? progress = null, CancellationToken cancellationToken = default) @@ -121,8 +129,20 @@ public static class TrialRunner ArgumentNullException.ThrowIfNull(family); ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(prior); + return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken); + } + + /// A trial of any family on any engine: the same validations, checks and report whatever the engine. + public static (BacktestReport Report, TrialSummary Summary) Run( + Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now, + Action? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(family); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(prior); var watch = Stopwatch.StartNew(); - var sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + var sessions = engine.Sessions; if (sessions < 30) { throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30."); @@ -134,15 +154,12 @@ public static class TrialRunner throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri."); } - // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. - var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } }; - var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); progress?.Invoke($"variante {i + 1} di {variants.Count}"); - runs[i] = BacktestEngine.Run(family.Create(variants[i].Parameters), data, options); + runs[i] = engine.Run(variants[i].Parameters); } var returns = runs.Select(r => r.DailyReturns()).ToArray(); @@ -157,21 +174,22 @@ public static class TrialRunner progress?.Invoke("variante in uso"); } - var run = judgedIndex < 0 ? BacktestEngine.Run(family.Create(judged), data, options) : runs[judgedIndex]; + var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex]; var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex]; - var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear); + var year = engine.PeriodsPerYear; + var metrics = BacktestMetrics.Of(run, year); progress?.Invoke("costi doppi e tripli, comprare e tenere"); var costs = new List(); foreach (var multiplier in plan.CostMultipliers.Distinct().Order()) { - var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(judged), data, options with { Costs = options.Costs with { Multiplier = multiplier } }); - var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear); + var costed = multiplier == 1m ? run : engine.Run(judged, multiplier); + var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year); costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } - var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, plain); - var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); + var benchmarkRun = engine.Benchmark(); + var benchmark = BacktestMetrics.Of(benchmarkRun, year); cancellationToken.ThrowIfCancellationRequested(); progress?.Invoke("convalide"); @@ -195,7 +213,7 @@ public static class TrialRunner var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread); progress?.Invoke("test anti sguardo in avanti"); - var look = LookAheadCheck.Run(_ => family.Create(judged), data, options, v.LookAheadCuts); + var look = engine.LookAhead(judged, v.LookAheadCuts); var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count, [.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]); @@ -226,18 +244,17 @@ public static class TrialRunner family.Name, family.Version, planHash, - data.Fingerprint(), - data.Currency, - data.PeriodsPerYear, + engine.Fingerprint(), + engine.Currency, + year, sessions, - [.. data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, - i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))], + engine.Instruments(), chosen.ToString(), metrics, benchmark, costs, [.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult, - Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)), + BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)), .. judgedIndex >= 0 ? Array.Empty() : [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]], walkForward, @@ -248,36 +265,28 @@ public static class TrialRunner lookAhead, checks, passed, - judgedIndex >= 0 ? Limitations(plan, family, data) - : [.. Limitations(plan, family, data), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."], + judgedIndex >= 0 ? engine.Limitations() + : [.. engine.Limitations(), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."], curve, [.. run.Trades.TakeLast(MaxTrades)], run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal), now, watch.Elapsed.TotalSeconds) - { Judged = plan.Judged is null ? null : judged.ToString() }; - if (StrategyPipeline.ResearchShare(family.Id) is not null) { - var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); - var table = plan.Slippage ?? SlippageTable.Standard; - var traded = run.Trades.Sum(x => x.Invested); - report = report with - { - ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null), - ExpectedPathP5 = [.. PathBootstrap.Percentile(judgedReturns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) - .Select(x => Math.Round(x, 4))], - }; - } + Judged = plan.Judged is null ? null : judged.ToString(), + Baskets = run.Baskets.Count == 0 ? null + : [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))], + }; + var expected = engine.Expected(run, judgedReturns); + report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 }; - var summary = new TrialSummary(data.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, + var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, dsr.Value, pbo?.Probability, sharpes); return (report, summary); } - private static BacktestMetrics Metrics(BacktestRun run, BacktestDataset data) => BacktestMetrics.Of(run, data.PeriodsPerYear); - /// What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it). - public static IReadOnlyList Limitations(TrialPlan plan, IStrategyFamily family, BacktestDataset data) + public static IReadOnlyList Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data) { ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(family); diff --git a/src/Anubis/Backtest/TrialEngines.cs b/src/Anubis/Backtest/TrialEngines.cs new file mode 100644 index 0000000..fbc1313 --- /dev/null +++ b/src/Anubis/Backtest/TrialEngines.cs @@ -0,0 +1,118 @@ +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// What an engine expects of the judged variant once it trades for real: the mean slippage in basis points and the 5th +/// percentile of the expected path (SPEC 12.3). Null where the engine has nothing to expect (the examples). +/// +public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList? PathP5) +{ + public static TrialExpectations None { get; } = new(null, null); +} + +/// +/// What the trial judge () asks of an engine, so the same judge, with the same validations and the +/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in +/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check. +/// +public interface ITrialEngine +{ + /// The currency of the money in the runs and in the report. + string Currency { get; } + + /// Periods in a year, to annualise the returns of the runs. + int PeriodsPerYear { get; } + + /// The sessions of the plan's window, both ends included: fewer than 30 and there is no trial. + int Sessions { get; } + + /// A hash of the data the runs read, for the report. + string Fingerprint(); + + /// The instruments of the data, with the period they cover. + IReadOnlyList Instruments(); + + /// One variant over the whole window, with costs multiplied by . + BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m); + + /// The term of comparison of the report: buy and hold for the daily engine, its own for an engine that is not. + BacktestRun Benchmark(); + + /// The check of SPEC 12.2 point 2: a decision must not change when data after it is added. + LookAheadResult LookAhead(StrategyParameters parameters, int cuts); + + /// What this engine does not model, in plain Italian (SPEC 12.1). + IReadOnlyList Limitations(); + + /// What the judged variant should give once it trades, from its run and its returns. + TrialExpectations Expected(BacktestRun run, double[] returns); +} + +/// +/// The daily engine of the trial judge: on daily closes, the strategy through its correctives and +/// the risk engine, buy and hold as the comparison. The options are built once, so every run shares the same risk state as it +/// always did. +/// +public sealed class DailyTrialEngine : ITrialEngine +{ + private readonly TrialPlan _plan; + private readonly IStrategyFamily _family; + private readonly BacktestDataset _data; + private readonly BacktestOptions _plain; + private readonly BacktestOptions _options; + + public DailyTrialEngine(TrialPlan plan, IStrategyFamily family, BacktestDataset data) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(family); + ArgumentNullException.ThrowIfNull(data); + _plan = plan; + _family = family; + _data = data; + + // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. + _plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } }; + _options = StrategyPipeline.For(family.Id, data, _plain, plan.ReferenceShare); + Sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + } + + public string Currency => _data.Currency; + + public int PeriodsPerYear => _data.PeriodsPerYear; + + public int Sessions { get; } + + public string Fingerprint() => _data.Fingerprint(); + + public IReadOnlyList Instruments() => + [.. _data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, + i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))]; + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) => + BacktestEngine.Run(_family.Create(parameters), _data, costMultiplier == 1m ? _options : _options with { Costs = _options.Costs with { Multiplier = costMultiplier } }); + + public BacktestRun Benchmark() => BacktestEngine.Run(new BuyAndHold(_data.Tradable.Count()), _data, _plain); + + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => LookAheadCheck.Run(_ => _family.Create(parameters), _data, _options, cuts); + + public IReadOnlyList Limitations() => TrialRunner.Limitations(_plan, _family, _data); + + public TrialExpectations Expected(BacktestRun run, double[] returns) + { + ArgumentNullException.ThrowIfNull(run); + ArgumentNullException.ThrowIfNull(returns); + if (StrategyPipeline.ResearchShare(_family.Id) is null) + { + return TrialExpectations.None; + } + + var specs = _data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var table = _plan.Slippage ?? SlippageTable.Standard; + var traded = run.Trades.Sum(x => x.Invested); + return new TrialExpectations( + traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null), + [.. PathBootstrap.Percentile(returns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed).Select(x => Math.Round(x, 4))]); + } +} diff --git a/src/Anubis/Backtest/Validation.cs b/src/Anubis/Backtest/Validation.cs index 840bbaf..2c5fd2e 100644 --- a/src/Anubis/Backtest/Validation.cs +++ b/src/Anubis/Backtest/Validation.cs @@ -5,6 +5,12 @@ namespace Anubis.Backtest; /// One point of a parameter grid: its parameters and its place on each parameter's grid (for neighbours). public sealed record Variant(int Index, StrategyParameters Parameters, IReadOnlyList Position) { + /// + /// For each axis, in the order of , whether it is a choice axis (); + /// null when none is. + /// + public IReadOnlyList? Choices { get; init; } + public override string ToString() => Parameters.ToString(); } @@ -15,12 +21,14 @@ public static class ParameterGrid /// The Cartesian product of the grids (the family's own, or where given), without the /// points the family rejects. A family without parameters has one variant. /// - public static IReadOnlyList Of(IStrategyFamily family, IReadOnlyDictionary>? grids = null) + public static IReadOnlyList Of(IResearchFamily family, IReadOnlyDictionary>? grids = null) { ArgumentNullException.ThrowIfNull(family); var axes = family.Parameters .Select(p => (p.Name, Values: (IReadOnlyList)[.. (grids?.GetValueOrDefault(p.Name) ?? p.Grid).Distinct().Order()])) .ToList(); + bool[] marks = [.. family.Parameters.Select(p => p.Choices)]; + var choices = marks.Any(c => c) ? marks : null; if (axes.Any(a => a.Values.Count == 0)) { throw new ArgumentException("Every parameter needs at least one value on its grid", nameof(grids)); @@ -33,7 +41,7 @@ public static class ParameterGrid var parameters = new StrategyParameters(axes.Select((a, i) => KeyValuePair.Create(a.Name, a.Values[position[i]]))); if (family.Accepts(parameters)) { - result.Add(new Variant(result.Count, parameters, [.. position])); + result.Add(new Variant(result.Count, parameters, [.. position]) { Choices = choices }); } // Next point: the last parameter moves fastest. @@ -116,7 +124,8 @@ public sealed record OverfittingResult(int Groups, int Combinations, int Variant public static class Validation { /// - /// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every axis. + /// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every numeric axis + /// with the same value on every choice axis (). /// public static double[] PlateauScores(IReadOnlyList variants, IReadOnlyList values) { @@ -129,7 +138,7 @@ public static class Validation var count = 0; for (var j = 0; j < variants.Count; j++) { - if (Neighbours(variants[i].Position, variants[j].Position)) + if (Neighbours(variants[i].Position, variants[j].Position, variants[i].Choices)) { sum += values[j]; count++; @@ -436,11 +445,13 @@ public static class Validation return sums; } - private static bool Neighbours(IReadOnlyList a, IReadOnlyList b) + /// One step at most on every numeric axis; on a choice axis only the same value. + private static bool Neighbours(IReadOnlyList a, IReadOnlyList b, IReadOnlyList? choices) { for (var k = 0; k < a.Count; k++) { - if (Math.Abs(a[k] - b[k]) > 1) + var limit = choices is not null && choices[k] ? 0 : 1; + if (Math.Abs(a[k] - b[k]) > limit) { return false; } diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index 3623a9a..5addd05 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -212,7 +212,7 @@ public sealed class StrategyParameters public static StrategyParameters None { get; } = new([]); /// The parameters a text such as fast=20;slow=100 gives to a family: its defaults where the text says nothing, or nothing it accepts. - public static StrategyParameters Of(IStrategyFamily family, string? text) + public static StrategyParameters Of(IResearchFamily family, string? text) { ArgumentNullException.ThrowIfNull(family); var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal); @@ -328,10 +328,21 @@ public interface IStrategy /// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results). /// parameters take only whole numbers, such as a number of days. /// -public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max, bool Whole = false); +public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max, bool Whole = false) +{ + /// + /// True for a choice axis: its values name different rules (a signal, a relation, a style), not points on a scale. The + /// plateau rule never averages two variants that differ on a choice axis. + /// + public bool Choices { get; init; } +} -/// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. -public interface IStrategyFamily +/// +/// What the laboratory needs to judge a family of rules: its name, its version and its parameters. A family judged by an +/// engine of its own (baskets) stops here; adds the strategies the daily engine and the live +/// bot run. +/// +public interface IResearchFamily { string Id { get; } @@ -350,7 +361,11 @@ public interface IStrategyFamily /// False for a point of the grid that makes no sense (a short average longer than the long one). bool Accepts(StrategyParameters parameters) => true; +} +/// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. +public interface IStrategyFamily : IResearchFamily +{ IStrategy Create(StrategyParameters parameters); } diff --git a/tests/Anubis.Tests/TrialEngineTests.cs b/tests/Anubis.Tests/TrialEngineTests.cs new file mode 100644 index 0000000..068bf0e --- /dev/null +++ b/tests/Anubis.Tests/TrialEngineTests.cs @@ -0,0 +1,361 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The seam between the trial judge and the engines (Phase 12, issue #118): the judge takes any +/// and any , the report gains an optional basket section, the plateau rule knows choice axes, +/// and nothing of what exists moves (the golden reports are in ). +/// +[TestClass] +public sealed class TrialEngineTests +{ + private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero); + private static readonly Guid Id = new("0b7e2c1d-5a3f-4e8b-9c6d-2f1a0e9d8c7b"); + private static readonly DateOnly First = new(2024, 1, 1); + + [TestMethod] + [TestCategory(Category.Unit)] + public void AnEngineThatIsNotDailyIsJudgedWithItsOwnSessionsYearFingerprintInstrumentsBenchmarkAndLimits() + { + var engine = new StubEngine(); + var (report, summary) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + + Assert.AreEqual(StubFamily.FamilyId, report.Strategy); + Assert.AreEqual("Famiglia finta", report.StrategyName); + Assert.AreEqual("USD", report.Currency); + Assert.AreEqual("USD", summary.Currency); + Assert.AreEqual(StubEngine.Year, report.PeriodsPerYear); + Assert.AreEqual(StubEngine.SessionCount, report.Sessions); + Assert.AreEqual("stub-data", report.DataFingerprint); + CollectionAssert.AreEqual(engine.Instruments().ToList(), report.Instruments.ToList()); + CollectionAssert.AreEqual(new[] { "Motore finto della prova." }, report.Limitations.ToList()); + + // The benchmark is the engine's own (here: stay flat), not buy and hold. + Assert.AreEqual(0d, report.Benchmark.TotalReturn); + Assert.IsTrue(report.Curve.All(p => p.Benchmark == StubEngine.Capital)); + + // Figures are annualised with the engine's periods per year. + var chosen = report.Variants.Single(v => v.Chosen).Parameters; + var expected = BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), StubEngine.Year); + Assert.AreEqual(expected.Sharpe, report.Metrics.Sharpe); + Assert.AreEqual(expected.AnnualReturn, report.Metrics.AnnualReturn); + Assert.AreNotEqual(BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), 365).Sharpe, report.Metrics.Sharpe); + + // What the engine expects and its look-ahead check reach the report as they are. + Assert.AreEqual(7.5m, report.ExpectedSlippageBp); + CollectionAssert.AreEqual(new[] { -0.01, -0.02 }, report.ExpectedPathP5!.ToList()); + Assert.AreEqual(42, report.LookAhead.Decisions); + Assert.IsTrue(report.LookAhead.Passed); + Assert.AreEqual(6, report.Variants.Count); + Assert.IsNull(report.Baskets); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheJudgeCallsTheEngineInTheOrderOfToday() + { + var engine = new StubEngine(); + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + var chosen = report.Variants.Single(v => v.Chosen).Parameters; + string[] expected = + [ + "run a=1;kind=0 x1", "run a=1;kind=1 x1", "run a=2;kind=0 x1", "run a=2;kind=1 x1", "run a=3;kind=0 x1", "run a=3;kind=1 x1", + $"run {chosen} x2", $"run {chosen} x3", "benchmark", $"look_ahead {chosen} 6", + ]; + CollectionAssert.AreEqual(expected, engine.Calls); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AJudgedVariantOutsideTheGridRunsOnceMoreOnTheEngine() + { + var engine = new StubEngine(); + var (report, _) = TrialRunner.Run(Id, StubPlan() with { Judged = "a=4;kind=1" }, "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + Assert.AreEqual("a=4;kind=1", report.Judged); + Assert.AreEqual("run a=4;kind=1 x1", engine.Calls[6]); + Assert.IsTrue(report.Variants[^1].OutsideGrid); + Assert.AreEqual(2, report.Limitations.Count); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportHasNoBasketsKeyWhenTheRunHasNone() + { + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine(), PriorTrials.None, Now); + Assert.IsNull(report.Baskets); + Assert.IsFalse(report.ToJson().Contains("\"baskets\"", StringComparison.Ordinal)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportCarriesTheBasketsOfTheRunWithUnitsLevelsLegsAndExitReasonAsItsLastSection() + { + var opened = new DateTimeOffset(2024, 3, 4, 14, 15, 0, TimeSpan.Zero); + BacktestBasket[] baskets = + [ + new("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, ["EURUSD", "USDCHF"], "target", 12.5m), + new("AUDUSD", opened.AddDays(1), null, 2_000m, 1, ["AUDUSD"], null, -3.25m), + ]; + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now); + + Assert.IsNotNull(report.Baskets); + Assert.AreEqual(2, report.Baskets.Count); + var first = report.Baskets[0]; + Assert.AreEqual(new ReportBasket("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, first.Legs, "target", 12.5m), first); + CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, first.Legs.ToList()); + Assert.IsNull(report.Baskets[1].Closed); + Assert.IsNull(report.Baskets[1].ExitReason); + + var json = report.ToJson(); + StringAssert.Contains(json, "\"units\":1000"); + StringAssert.Contains(json, "\"levels\":3"); + StringAssert.Contains(json, "\"legs\":[\"EURUSD\",\"USDCHF\"]"); + StringAssert.Contains(json, "\"exit_reason\":\"target\""); + Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"seconds\":", StringComparison.Ordinal), "The baskets come after every other field."); + Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"expected_slippage_bp\":", StringComparison.Ordinal)); + Assert.IsTrue(json.EndsWith("]}", StringComparison.Ordinal)); + + var back = BacktestReport.FromJson(json); + Assert.AreEqual(2, back.Baskets!.Count); + CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, back.Baskets[0].Legs.ToList()); + Assert.AreEqual(json, back.ToJson()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportKeepsOnlyTheLastBasketsUpToTheLimitOfTheTrades() + { + var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero); + var baskets = Enumerable.Range(0, TrialRunner.MaxTrades + 5) + .Select(i => new BacktestBasket("EURUSD", opened.AddHours(i), opened.AddHours(i + 1), 1_000m, 1, ["EURUSD"], "target", i)) + .ToArray(); + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now); + Assert.AreEqual(TrialRunner.MaxTrades, report.Baskets!.Count); + Assert.AreEqual(5m, report.Baskets[0].Result); + Assert.AreEqual(TrialRunner.MaxTrades + 4m, report.Baskets[^1].Result); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheDailyEngineThroughTheNewOverloadGivesTheReportOfTheOldOne() + { + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: First)); + var grid = new Dictionary> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] }; + var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"], + First.AddDays(60), First.AddDays(399), 10_000m, grid), Now).Plan; + var hash = TrialPlan.Hash(plan.ToJson()); + var family = MovingAverageCrossFamily.Instance; + + var engine = new DailyTrialEngine(plan, family, data); + Assert.AreEqual(data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To), engine.Sessions); + Assert.AreEqual(data.PeriodsPerYear, engine.PeriodsPerYear); + Assert.AreEqual(data.Currency, engine.Currency); + Assert.AreEqual(data.Fingerprint(), engine.Fingerprint()); + CollectionAssert.AreEqual(TrialRunner.Limitations(plan, family, data).ToList(), engine.Limitations().ToList()); + + var old = TrialRunner.Run(Id, plan, hash, family, data, PriorTrials.None, Now); + var seam = TrialRunner.Run(Id, plan, hash, family, engine, PriorTrials.None, Now); + Assert.AreEqual((old.Report with { Seconds = 0 }).ToJson(), (seam.Report with { Seconds = 0 }).ToJson()); + Assert.AreEqual(old.Summary.Chosen, seam.Summary.Chosen); + Assert.AreEqual(old.Summary.NetResult, seam.Summary.NetResult); + } + + /// + /// The hashes of plans built the way the laboratory and the protocols build them, recorded on commit 88b2883 before the + /// seam: a plan written today has the same hash, so the trial ids derived from it and the recorded outcomes do not move. + /// + [TestMethod] + [TestCategory(Category.Golden)] + public void APlanBuiltTodayHasTheHashItHadBeforeTheSeam() + { + var expected = new Dictionary + { + [StrategyNames.CryptoTrend] = "2a30b537ecf0d6a0d94794c5d9fe97695cc912d5a1ada6ca9c10382853d7b3cb", + ["equity_momentum"] = "9555ef93f3d90ae54ede9068f4db7dc38697f283ac586de6dff324c3475f4cd7", + ["equity_meanrev"] = "5b64b09419ba153703909c81b13b9934938d6f8ba1b984fc00330980ff0e082c", + [StrategyNames.StockAthBreakout] = "5bf77e99a0d2e4372002e9cc306cec84a98acee3804ace5dda8ab24ca90fb378", + [StrategyNames.CryptoRelativeMomentum] = "99a85eb937c80bbe14a5113973271fc73ca3f5f7ac966321bca3a9e44204985e", + [MovingAverageCrossFamily.FamilyId] = "952279ca4cd6193b08da61b96ecd12cac86c925a10c946099798dccb0c3326ca", + [BuyAndHoldFamily.FamilyId] = "8266b414ea78d9ad1317ce578f23e3def2bb37bcb28a6103fae1bab6bc082a06", + }; + var written = new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero); + Assert.AreEqual(expected.Count, StrategyCatalog.All.Count); + foreach (var family in StrategyCatalog.All) + { + var plan = Laboratory.BuildPlan(new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, ["BTCEUR", "ETHEUR"], + CryptoTrendProtocol.From, new DateOnly(2026, 10, 31), CryptoTrendProtocol.Capital), written).Plan; + Assert.AreEqual(expected[family.Id], TrialPlan.Hash(plan.ToJson()), family.Id); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePlateauRuleNeverTreatsTwoValuesOfAChoiceAxisAsNeighbours() + { + var variants = ParameterGrid.Of(StubFamily.Instance); + Assert.AreEqual(6, variants.Count); + Assert.IsTrue(variants.All(v => v.Choices is [false, true])); + + // Grid order: a = 1, 2, 3 outside, kind = 0, 1 inside. Kind 0 is a valley on the numeric axis, kind 1 a flat hill. + double[] values = [3, 5, 0, 5, 3, 5]; + var scores = Validation.PlateauScores(variants, values); + + // Kind 1 is averaged only with kind 1: no score is dragged down by the other choice. + Assert.AreEqual(5d, scores[1]); + Assert.AreEqual(5d, scores[3]); + Assert.AreEqual(5d, scores[5]); + + // The numeric axis still averages one step either side: (3 + 0) / 2 at the ends, min(0, 2) in the middle. + Assert.AreEqual(1.5, scores[0]); + Assert.AreEqual(0d, scores[2]); + Assert.AreEqual(1.5, scores[4]); + Assert.AreEqual(1, Validation.ChoosePlateau(variants, values)); + + // Without the choice mark the same grid mixes the two kinds, as the numeric rule always did. + var plain = variants.Select(v => v with { Choices = null }).ToList(); + Assert.AreEqual(3.25, Validation.PlateauScores(plain, values)[1]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AGridWithoutChoiceAxesMarksNoVariant() + { + Assert.IsTrue(ParameterGrid.Of(MovingAverageCrossFamily.Instance).All(v => v.Choices is null)); + Assert.IsTrue(StrategyCatalog.All.SelectMany(f => f.Parameters).All(p => !p.Choices)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EveryStrategyFamilyIsAResearchFamilyAndTheCatalogStillKnowsWhoNeedsTheWholeHistory() + { + Assert.IsTrue(typeof(IResearchFamily).IsAssignableFrom(typeof(IStrategyFamily))); + foreach (var family in StrategyCatalog.All) + { + Assert.IsInstanceOfType(family, family.Id); + } + + Assert.IsTrue(StrategyCatalog.Find(StrategyNames.StockAthBreakout) is { NeedsFullHistory: true }); + Assert.IsFalse(StrategyCatalog.Find(StrategyNames.CryptoTrend) is { NeedsFullHistory: true }); + IResearchFamily research = StockAthBreakoutFamily.Instance; + Assert.IsTrue(research.NeedsFullHistory); + IResearchFamily cross = MovingAverageCrossFamily.Instance; + Assert.IsFalse(cross.Accepts(new StrategyParameters([KeyValuePair.Create("fast", 50m), KeyValuePair.Create("slow", 20m)]))); + Assert.AreEqual("fast=20;slow=100", StrategyParameters.Of(cross, "fast=50;slow=20").ToString()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AResearchFamilyWithoutStrategiesHasItsGridAndItsParameters() + { + Assert.AreEqual("a=2;kind=1", StrategyParameters.Of(StubFamily.Instance, "a=2;kind=1").ToString()); + Assert.AreEqual("a=2;kind=0", StrategyParameters.Of(StubFamily.Instance, null).ToString()); + Assert.AreEqual(6, ParameterGrid.Of(StubFamily.Instance).Count); + Assert.IsFalse(typeof(IStrategyFamily).IsAssignableFrom(typeof(StubFamily))); + } + + private static TrialPlan StubPlan() => new( + StubFamily.FamilyId, + StubFamily.Instance.Version, + new SortedDictionary>(StringComparer.Ordinal) { ["a"] = [1m, 2m, 3m], ["kind"] = [0m, 1m] }, + new TrialData(TrialSources.Research, "dukascopy", ["EURUSD"], First, First.AddDays(StubEngine.Days - 1)), + StubEngine.Capital, + [1m, 2m, 3m], + TrialValidation.Default, + TrialThresholds.Default, + "stub", + Now); + + /// A research family that cannot build a strategy: a numeric axis and a choice axis. + private sealed class StubFamily : IResearchFamily + { + public const string FamilyId = "stub_baskets"; + + public static StubFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => "1"; + + public string Name => "Famiglia finta"; + + public string Description => "Famiglia finta per provare il giunto del giudice."; + + public IReadOnlyList Parameters => + [ + new("a", "Numero", 2m, [1m, 2m, 3m], 1m, 9m, Whole: true), + new("kind", "Tipo", 0m, [0m, 1m], 0m, 1m, Whole: true) { Choices = true }, + ]; + } + + /// An engine that is not daily: it builds its runs by hand, records every call and has its own figures. + private sealed class StubEngine : ITrialEngine + { + public const int Days = 320; + public const int SessionCount = 7_680; + public const int Year = 6_048; + public const decimal Capital = 10_000m; + + public List Calls { get; } = []; + + public IReadOnlyList Baskets { get; init; } = []; + + public string Currency => "USD"; + + public int PeriodsPerYear => Year; + + public int Sessions => SessionCount; + + public string Fingerprint() => "stub-data"; + + public IReadOnlyList Instruments() => [new("EURUSD", "dukascopy", First, First.AddDays(Days - 1), SessionCount, 0, "file")]; + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) + { + Calls.Add(FormattableString.Invariant($"run {parameters} x{costMultiplier}")); + return Build(parameters, costMultiplier, Baskets); + } + + public BacktestRun Benchmark() + { + Calls.Add("benchmark"); + return new BacktestRun(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []); + } + + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) + { + Calls.Add(FormattableString.Invariant($"look_ahead {parameters} {cuts}")); + return new LookAheadResult([First.AddDays(100)], 42, []); + } + + public IReadOnlyList Limitations() => ["Motore finto della prova."]; + + public TrialExpectations Expected(BacktestRun run, double[] returns) => new(7.5m, [-0.01, -0.02]); + + /// A noisy equity whose drift depends on the parameters; costs lower it a little each day. + public static BacktestRun Build(StrategyParameters parameters, decimal costMultiplier, IReadOnlyList baskets) + { + var a = parameters.Whole("a"); + var kind = parameters.Whole("kind"); + var gen = new Gen((a * 10) + kind); + var drift = (0.0004 * a) - (0.0006 * kind); + var equity = new List(); + var value = Capital; + for (var i = 0; i < Days; i++) + { + if (i > 0) + { + value *= 1m + (decimal)(drift + (0.01 * gen.Normal())) - (0.0001m * (costMultiplier - 1m)); + value = Math.Round(value, 6); + } + + equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m)); + } + + return new BacktestRun("USD", Capital, equity, [], [], [], []) { Baskets = baskets }; + } + } +}