From acc9efe39d455d45966fdd172a0ec53f1b9f413b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 18:10:17 +0100 Subject: [PATCH] Add the basket_reversion family and its trial engine The trial machinery of Phase 13 judges a family through an ITrialEngine; the baskets need one so their variants go through the same judge, cost stress, control and look-ahead check as the daily families. BasketReversionFamily ("Rientro tra strumenti") has one identifier for every sub-variant: generation A (the five documented spreads) or B (ten single symbols), signal, target, distance, growth, averagings, window, entry threshold, exit rule, profile, open baskets and lot. The choice axes are decimal codes marked as choices, so the plan never treats them as a range to explore. Rules() turns parameters into BasketRules and refuses a combination the family does not accept. BasketTrialEngine runs the basket engine on the plan's data with the plan's mode (come_dal_vivo by default) and venue costs (eToro by default): one equity point a day on the same days for every variant, 260 points a year, zero as the comparison (the account is not long anything), a surrogate that flips each day's changes for the control, and a look-ahead check that compares the decisions taken before each cut with those taken on the cut data. Its fingerprint carries the market, the engine version, the costs and the mode. refs #129 Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/BasketTrialEngine.cs | 180 ++++++++++++ src/Anubis/Strategies/BasketReversion.cs | 98 +++++++ tests/Anubis.Tests/BasketTrialEngineTests.cs | 289 +++++++++++++++++++ 3 files changed, 567 insertions(+) create mode 100644 src/Anubis/Backtest/BasketTrialEngine.cs create mode 100644 src/Anubis/Strategies/BasketReversion.cs create mode 100644 tests/Anubis.Tests/BasketTrialEngineTests.cs diff --git a/src/Anubis/Backtest/BasketTrialEngine.cs b/src/Anubis/Backtest/BasketTrialEngine.cs new file mode 100644 index 0000000..f98819a --- /dev/null +++ b/src/Anubis/Backtest/BasketTrialEngine.cs @@ -0,0 +1,180 @@ +using System.Globalization; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Backtest; + +/// +/// The trial judge's engine for the basket family (Phase 14, ADR 0026): the on currency bars, in +/// the plan's mode and with the plan's venue costs («come dal vivo» and eToro when the plan names none). One equity point per +/// day of the window, 260 a year; the comparison is zero, capital that does not move, never buy and hold; the control +/// against chance turns each day's changes of every pair with the day's sign, both ways (the engine sells as well as it +/// buys). It holds no state between runs. +/// +public sealed class BasketTrialEngine : ITrialEngine +{ + /// Equity points in a year: the weekdays of the currency calendar. + public const int PointsPerYear = 260; + + private readonly TrialPlan _plan; + private readonly BasketReversionFamily _family; + private readonly BasketMode _mode; + private readonly VenueCosts _costs; + private readonly BasketEngine _engine; + private readonly Lazy _fingerprint; + private readonly DateOnly[] _days; + + public BasketTrialEngine(TrialPlan plan, BasketReversionFamily family, BarDataset data) + : this(plan, family, BasketMarket.Of(data ?? throw new ArgumentNullException(nameof(data)))) + { + } + + private BasketTrialEngine(TrialPlan plan, BasketReversionFamily family, BasketMarket market) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(family); + _plan = plan; + _family = family; + _mode = BasketModes.Parse(plan.Mode ?? BasketModes.AsLive); + _costs = plan.Costs ?? VenueCosts.Etoro; + Market = market; + _engine = new BasketEngine(market, _costs, plan.InitialCapital); + _fingerprint = new Lazy(() => + $"{market.Fingerprint}|basket:{BasketEngine.Version}|costs:{_costs.Fingerprint()}|mode:{BasketModes.Name(_mode)}"); + _days = [.. Enumerable.Range(0, market.Count).Select(market.Day).Distinct().Where(d => d >= plan.Data.From && d <= plan.Data.To)]; + } + + /// The prices the runs read. + public BasketMarket Market { get; } + + /// A test hook: changes the rules of every run (narrower units, a filter off, a rule that cheats). + internal Func? Customize { get; init; } + + public string Currency => "USD"; + + public int PeriodsPerYear => PointsPerYear; + + /// The days of the window with at least one bar: one equity point each. + public int Sessions => _days.Length; + + public string Fingerprint() => _fingerprint.Value; + + public IReadOnlyList Instruments() => + [.. Market.Symbols.Select(symbol => + { + var bars = Enumerable.Range(0, Market.Count).Where(t => Market.Has(symbol, t)).ToList(); + return new ReportInstrument(symbol, _plan.Data.Venue, bars.Count > 0 ? Market.Day(bars[0]) : null, bars.Count > 0 ? Market.Day(bars[^1]) : null, + bars.Count, 0, _plan.Data.Source); + })]; + + /// The rules of a variant in the plan's mode. + public BasketRules Rules(StrategyParameters parameters) + { + var rules = _family.Rules(parameters, _mode, Market.Timeframe); + return Customize is null ? rules : Customize(rules); + } + + /// A run with its traces and decisions, not only what the judge reads. + public BasketRunResult RunBaskets(StrategyParameters parameters, decimal costMultiplier = 1m) => + _engine.Run(Rules(parameters), costMultiplier, _plan.Data.From, _plan.Data.To); + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) => RunBaskets(parameters, costMultiplier).Run; + + /// Zero: the capital that does not trade, on the same days (ADR 0026 point 5). + public BacktestRun Benchmark() => new( + Currency, _plan.InitialCapital, [.. _days.Select(d => new EquityPoint(d, _plan.InitialCapital, _plan.InitialCapital, 0m))], [], [], [], []); + + /// + /// The check of SPEC 12.2 point 2 for baskets: the whole data and the data cut after a few days of the window (only the + /// bars closed by the end of that day), every decision up to the cut compared, moment by moment. A basket still open at + /// the cut, valued at the end, is not a decision. + /// + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) + { + var rules = Rules(parameters); + var cutoffs = Enumerable.Range(1, cuts) + .Select(k => (int)((long)(_days.Length - 1) * k / (cuts + 1))) + .Where(i => i > 0) + .Distinct() + .Select(i => _days[i]) + .ToList(); + var full = _engine.Run(rules, 1m, _plan.Data.From, _plan.Data.To); + var mismatches = new List(); + var compared = 0; + foreach (var cutoff in cutoffs) + { + var lastBar = Enumerable.Range(0, Market.Count).Last(t => Market.Day(t) <= cutoff); + var moment = Market.ClosesAt(lastBar); + var cut = new BasketEngine(Market.Through(moment), _costs, _plan.InitialCapital).Run(rules, 1m, _plan.Data.From, _plan.Data.To); + var before = Decisions(full.Events, moment); + var after = Decisions(cut.Events, moment); + foreach (var at in before.Keys.Union(after.Keys).Order()) + { + compared++; + var inFull = before.TryGetValue(at, out var x); + var inCut = after.TryGetValue(at, out var y); + var a = inFull ? x.Text : "-"; + var b = inCut ? y.Text : "-"; + if (a != b) + { + mismatches.Add(new LookAheadMismatch(cutoff, inFull ? x.Day : y.Day, a, b)); + } + } + } + + return new LookAheadResult(cutoffs, compared, mismatches); + } + + public IReadOnlyList Limitations() + { + var italian = CultureInfo.GetCultureInfo("it-IT"); + var result = new List(); + if (Market.Symbols.Any(s => !Market.HasAsk(s))) + { + result.Add("I prezzi della BCE sono cambi di riferimento, non prezzi a cui si compra o si vende: denaro e lettera sono ricostruiti " + + "attorno al cambio con il differenziale della tabella dei costi."); + } + + result.Add(string.Create(italian, $"Costi di {_costs.Venue} al {_costs.AsOf:d MMMM yyyy}: {_costs.Source}.")); + if (_costs.Pairs.Any(p => p.FinancingEstimated)) + { + result.Add("Il finanziamento notturno delle coppie che il documento non dà è stimato con prudenza: il costo più alto fra quelli noti, sui due lati."); + } + + result.Add(Market.Daily + ? "Si decide sul cambio di chiusura di un giorno e si esegue su quello del giorno dopo; le finestre orarie (fine settimana, sessione, pausa giornaliera) su barre giornaliere non valgono." + : "Si decide sulla chiusura della barra e si esegue all'apertura della barra dopo; lo stop sul conto usa i prezzi medi durante la pausa giornaliera."); + result.Add("Il conto non viene letto: margine, stop obbligatorio della piattaforma, chiusura d'ufficio sotto metà del margine e finanziamento con il mercoledì triplo sono simulati con le regole della sede."); + result.Add(_mode == BasketMode.AsLive + ? "Modalità «come dal vivo»: regole del documento più i limiti di rischio (perdita del giorno, della settimana, calo dal massimo) e del margine; se scatta l'interruttore supponiamo che tu riparta dopo sette giorni." + : "Modalità «alla lettera»: solo le regole del documento. Il giudizio vale solo per la modalità «come dal vivo»."); + result.Add("Nessuna notizia e nessun calendario economico: il filtro delle notizie è spento."); + result.Add("Il confronto è con zero, cioè il capitale fermo, non con comprare e tenere."); + result.Add("Sharpe e volatilità sono calcolati senza tasso privo di rischio."); + return result; + } + + public TrialExpectations Expected(BacktestRun run, double[] returns) + { + ArgumentNullException.ThrowIfNull(run); + ArgumentNullException.ThrowIfNull(returns); + return new TrialExpectations(null, + [.. PathBootstrap.Percentile(returns, PointsPerYear, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed).Select(x => Math.Round(x, 4))]); + } + + /// Baskets buy and sell: the control flips the signs without centring them (ADR 0026 point 4). + public bool LongOnly => false; + + /// The same engine on the surrogate market: every day of every pair takes the sign of . + public ITrialEngine Surrogate(DaySigns signs, bool centred) => + new BasketTrialEngine(_plan, _family, Market.Surrogate(signs, centred)) { Customize = Customize }; + + private static Dictionary Decisions(IReadOnlyList events, DateTimeOffset through) => + events + .Where(e => e.At <= through && e.Reason != BasketReasons.End) + .GroupBy(e => e.At) + .ToDictionary( + g => g.Key, + g => (g.First().Day, string.Join(" | ", g.Select(e => string.Create(CultureInfo.InvariantCulture, + $"{e.At.UtcDateTime:yyyy-MM-dd HH:mm} {e.Unit} {e.Kind} {e.Reason} {e.Direction}"))))); +} diff --git a/src/Anubis/Strategies/BasketReversion.cs b/src/Anubis/Strategies/BasketReversion.cs new file mode 100644 index 0000000..ec14404 --- /dev/null +++ b/src/Anubis/Strategies/BasketReversion.cs @@ -0,0 +1,98 @@ +using Anubis.Backtest; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Strategies; + +/// +/// The family «Rientro tra strumenti» of the research document of 2 December 2026 (Phase 14, issue #129): baskets that bet on +/// the return of a currency relation to its mean. One identifier for every sub-variant (generation, signal, units, exit, +/// profile), so every attempt counts in the deflated Sharpe of the next ones (). A research +/// family only, judged by the : never an , never in the +/// catalogue the bot trades from. Choice axes are codes: generation 1 = A (two legs), 2 = B (one pair); signal 1 = z of the +/// pip sum, 2 = z of the log index; units 1 = pips, 2 = σ; exit 1 = pip sum (section 4.5), 2 = mean of the entries (G.3); +/// profile 1 = Fedele, 2 = Prudente. +/// +public sealed class BasketReversionFamily : IResearchFamily +{ + public const string FamilyId = "basket_reversion"; + + public static BasketReversionFamily Instance { get; } = new(); + + /// Generation A: the five spreads of the five-spread edition (section 3.3), all chains. + public static IReadOnlyList GenerationA { get; } = [.. Relations.DocumentedSpreads.Take(5).Select(s => BasketUnit.Of(s.A, s.B))]; + + /// Generation B: the ten symbols of the ten-symbol edition (section 4.8), each on its own. + public static IReadOnlyList GenerationB { get; } = + [.. new[] { "EURUSD", "USDCHF", "AUDUSD", "USDCAD", "GBPUSD", "EURGBP", "NZDUSD", "AUDCHF", "EURCHF", "AUDCAD" }.Select(p => BasketUnit.OnePair(FxPairs.Get(p)))]; + + public string Id => FamilyId; + + public string Version => "1"; + + public string Name => "Rientro tra strumenti"; + + public string Description => + "Dal documento di ricerca del 2 dicembre 2026: quando l'indice di due cambi legati, o di un cambio solo, si allontana di due " + + "deviazioni dalla sua media recente, apre un paniere contro lo scostamento; se il prezzo va ancora contro, aggiunge livelli " + + "uguali al primo, mai più grandi; chiude tutto all'obiettivo. Solo ricerca: nessun ordine, nemmeno finto."; + + public IReadOnlyList Parameters { get; } = + [ + new("generation", "Generazione (1 = due gambe, 2 = un cambio)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true }, + new("signal", "Segnale (1 = somma dei pip, 2 = logaritmi)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true }, + new("units", "Unità (1 = pip, 2 = σ)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true }, + new("target", "Obiettivo (pip o σ)", 10m, [10m], 0.1m, 200m), + new("distance", "Distanza di mediazione (pip o σ)", 40m, [40m], 0m, 2_000m), + new("growth", "Crescita della distanza", 1m, [1m], 1m, 2m), + new("averagings", "Mediazioni al massimo", 3m, [3m], 0m, 4m, Whole: true), + new("window", "Finestra (barre)", 100m, [100m], 10m, 1_000m, Whole: true), + new("entry_z", "Soglia di ingresso (z)", 2m, [2m], 0.5m, 5m), + new("exit", "Uscita (1 = somma dei pip, 2 = media degli ingressi)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true }, + new("profile", "Profilo (1 = Fedele, 2 = Prudente)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true }, + new("max_open", "Panieri aperti insieme", 2m, [2m], 1m, 10m, Whole: true), + new("lot", "Lotti per 10.000 di capitale", 0.01m, [0.01m], 0.001m, 1m), + ]; + + /// Codes outside their choices, and four averagings without growth (the document allows four only with 1.3), make no sense. + public bool Accepts(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + bool Code(string name) => parameters[name] is 1m or 2m; + return Code("generation") && Code("signal") && Code("units") && Code("exit") && Code("profile") + && (parameters.Whole("averagings") <= 3 || parameters["growth"] > 1m); + } + + /// + /// The rules of a variant for the engine: the document's filters on (Rvol 2, correlation 0.6 on the expected sign, three + /// costs, open baskets), leverage 5, decision on the close and execution at the next open. The hourly window is on for + /// generation B, as in the document; on bars of a day or longer no window of the day applies. + /// + public BasketRules Rules(StrategyParameters parameters, BasketMode mode, string timeframe) + { + ArgumentNullException.ThrowIfNull(parameters); + if (!Accepts(parameters)) + { + throw new ArgumentException($"Variante non valida per {Name}: {parameters}.", nameof(parameters)); + } + + var generationB = parameters.Whole("generation") == 2; + return new BasketRules(generationB ? GenerationB : GenerationA) + { + Signal = parameters.Whole("signal") == 2 ? BasketSignal.ZScoreLog : BasketSignal.ZScorePipSum, + Measure = parameters.Whole("units") == 2 ? BasketMeasure.Sigma : BasketMeasure.Pips, + Target = parameters["target"], + Distance = parameters["distance"], + Growth = parameters["growth"], + MaxAveragings = parameters.Whole("averagings"), + Window = parameters.Whole("window"), + EntryZ = (double)parameters["entry_z"], + Exit = parameters.Whole("exit") == 2 ? BasketExitRule.MeanOfEntries : BasketExitRule.PipSum, + Profile = parameters.Whole("profile") == 2 ? BasketProfiles.Prudente : BasketProfiles.Fedele, + MaxOpenBaskets = parameters.Whole("max_open"), + LotPer10k = parameters["lot"], + Mode = mode, + Session = generationB && Timeframes.IsIntraday(timeframe), + }; + } +} diff --git a/tests/Anubis.Tests/BasketTrialEngineTests.cs b/tests/Anubis.Tests/BasketTrialEngineTests.cs new file mode 100644 index 0000000..89ba58c --- /dev/null +++ b/tests/Anubis.Tests/BasketTrialEngineTests.cs @@ -0,0 +1,289 @@ +using Anubis.Backtest; +using Anubis.Baskets; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// The basket family and its trial engine (Phase 14, issue #129): one identifier for every sub-variant, the choice axes, the +/// plan that carries mode and costs, the judge on a basket trial (orphan legs counted in the report, one equity point a day +/// for every variant, zero as the comparison, the surrogate of the control), the look-ahead check that catches a rule +/// reading the bars ahead, and the lot that never grows inside a basket. +/// +[TestClass] +public sealed class BasketTrialEngineTests +{ + private static readonly FxPair EurUsd = FxPairs.Get("EURUSD"); + private static readonly FxPair UsdChf = FxPairs.Get("USDCHF"); + + [TestMethod] + [TestCategory(Category.Integration)] + public void AMandatoryStopThatLeavesAnOrphanLegIsCountedInTheReport() + { + // The chain EURUSD + USDCHF is bought on bar 40 (filled on bar 41 at the asks 1.099005 and 0.799505: 0.1 pip of + // spread). On bar 45 USDCHF opens 15% lower: the mandatory stop of the long USDCHF at leverage 5 sits 10% under the + // entry (0.7195545), so it is gapped and filled at the open's bid, 0.679995. The EURUSD leg is left alone: it closes + // at the next execution as an orphan. + double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 40), .. Enumerable.Repeat(1.0990, 30)]; + double[] c = [.. BasketSynthetic.Alternate(0.8000, 0.8002, 40), .. Enumerable.Repeat(0.7995, 5), .. Enumerable.Repeat(0.68, 25)]; + var data = BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e, ["USDCHF"] = c }); + var days = BasketSynthetic.Weekdays(BasketSynthetic.Monday, 70); + var plan = Plan(days[0], days[^1], BasketModes.AsDocument); + var engine = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data) + { + Customize = r => r with { Units = [BasketUnit.Of(EurUsd, UsdChf)], Window = 10, MaxRvol = null, MinCorrelation = null }, + }; + + var run = engine.RunBaskets(StrategyParameters.Of(BasketReversionFamily.Instance, null)); + var basket = run.Run.Baskets[0]; + Assert.AreEqual(BasketReasons.OrphanLeg, basket.ExitReason); + var trace = run.Traces[0]; + var chf = trace.Positions.Single(p => p.Pair == "USDCHF"); + var eur = trace.Positions.Single(p => p.Pair == "EURUSD"); + Assert.AreEqual(BasketReasons.MandatoryStop, chf.ExitReason); + Assert.AreEqual(45, chf.ExitBar); + Assert.AreEqual(0.679995m, chf.ExitPrice); + Assert.AreEqual(BasketReasons.OrphanLeg, eur.ExitReason); + Assert.AreEqual(46, eur.ExitBar); + Assert.AreEqual(1, run.Run.Notes.Count(n => n.Reason == BasketReasons.OrphanLeg)); + + var (report, _) = TrialRunner.Run(Guid.NewGuid(), plan, "plan", BasketReversionFamily.Instance, engine, PriorTrials.None, plan.WrittenAt); + Assert.AreEqual(1, report.Notes[BasketReasons.OrphanLeg]); + Assert.AreEqual(1, report.Notes[BasketReasons.MandatoryStop]); + Assert.AreEqual(BasketReasons.OrphanLeg, report.Baskets![0].ExitReason); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheLotNeverGrowsInsideABasket() + { + // Property: on reverting and walking crosses, both modes, both profiles, pips and σ, no level is larger than the first. + var levels = 0; + for (var seed = 1; seed <= 12; seed++) + { + var data = BasketSynthetic.Crosses(320, seed, halfLife: 10 + (seed * 7), volatility: 0.004 + (seed * 0.0007)); + var market = BasketMarket.Of(data); + var mode = seed % 2 == 0 ? BasketModes.AsLive : BasketModes.AsDocument; + var parameters = StrategyParameters.Of(BasketReversionFamily.Instance, + $"generation={1 + (seed % 2)};units={1 + (seed / 2 % 2)};target={(seed / 2 % 2 == 0 ? 10 : 2)};distance={(seed / 2 % 2 == 0 ? 15 : 1)};profile={1 + (seed / 4 % 2)};growth={(seed % 3 == 0 ? "1.3" : "1")};averagings={(seed % 3 == 0 ? 4 : 3)};window=20"); + var rules = BasketReversionFamily.Instance.Rules(parameters, BasketModes.Parse(mode), data.Timeframe) with { MaxRvol = null, MinCorrelation = null }; + var result = new BasketEngine(market, VenueCosts.Etoro, 10_000m).Run(rules); + foreach (var trace in result.Traces) + { + foreach (var leg in trace.Positions.GroupBy(p => p.Pair)) + { + var first = leg.First(p => p.Level == 0).Units; + Assert.IsTrue(leg.All(p => p.Units <= first), $"seed {seed}, {trace.Unit}: {string.Join(", ", leg.Select(p => p.Units))}"); + levels += leg.Count(p => p.Level > 0); + } + } + } + + Assert.IsTrue(levels > 20, $"{levels} averagings: the property must be exercised"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEngineFindsARuleThatReadsTheNextBar() + { + var data = BasketSynthetic.Crosses(520, 7, halfLife: 30); + var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 520); + var plan = Plan(days[120], days[^1], BasketModes.AsDocument); + var parameters = StrategyParameters.Of(BasketReversionFamily.Instance, "generation=2;signal=2;units=2;target=2.5;distance=4;exit=2"); + + var honest = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data).LookAhead(parameters, 6); + Assert.AreEqual(0, honest.Mismatches.Count, string.Join("\n", honest.Mismatches.Take(3).Select(m => $"{m.Day}: {m.Full} / {m.Cut}"))); + Assert.IsTrue(honest.Decisions > 20, $"{honest.Decisions} decisions compared"); + + // A signal that reads the bars ahead: the same z, fifty bars later (as good as a centred window). + var cheat = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data) { Customize = r => r with { SignalShift = 50 } }.LookAhead(parameters, 6); + Assert.IsTrue(cheat.Mismatches.Count > 0); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EveryVariantHasOneEquityPointPerDayOnTheSameDays() + { + // Daily fixings: every variant, both modes, one point per weekday of the window. + var data = BasketSynthetic.Crosses(260, 11, halfLife: 25); + var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 260); + foreach (var mode in new[] { BasketModes.AsDocument, BasketModes.AsLive }) + { + var engine = new BasketTrialEngine(Plan(days[110], days[^1], mode), BasketReversionFamily.Instance, data); + Assert.AreEqual(150, engine.Sessions); + foreach (var p in new[] { "generation=1", "generation=2", "generation=2;units=2;target=2.5;distance=4;profile=2", "generation=1;signal=2;units=2;target=2.5;distance=10;exit=2" }) + { + var run = engine.Run(StrategyParameters.Of(BasketReversionFamily.Instance, p)); + CollectionAssert.AreEqual(days.Skip(110).ToArray(), run.Equity.Select(x => x.Day).ToArray(), $"{mode} {p}"); + } + + CollectionAssert.AreEqual(days.Skip(110).ToArray(), engine.Benchmark().Equity.Select(x => x.Day).ToArray()); + Assert.IsTrue(engine.Benchmark().Equity.All(x => x.Equity == 10_000m), "the comparison is zero: capital that does not move"); + } + + // 15-minute bars: one point per server day, the day that ends at 17:00 New York. + var first = new DateTimeOffset(2026, 1, 13, 0, 0, 0, TimeSpan.Zero); + var walk = BasketSynthetic.Walk(288, 5, 0, 0.0004); + var quarters = BasketSynthetic.Quarters(first, new Dictionary + { + ["EURUSD"] = [.. walk.Select(x => BasketSynthetic.Mid(Math.Round((decimal)(1.1 * Math.Exp(x)), 5), 0.0001m))], + }); + var serverDays = Enumerable.Range(0, 288).Select(t => ServerClock.Day(first.AddMinutes((15 * t) + 15).AddTicks(-1))).Distinct().ToArray(); + Assert.AreEqual(4, serverDays.Length); + foreach (var rules in new[] { SingleRules(EurUsd, BasketMode.AsDocument), SingleRules(EurUsd, BasketMode.AsLive) with { Window = 20, Target = 3m } }) + { + CollectionAssert.AreEqual(serverDays, Run(quarters, rules, VenueCosts.Etoro).Run.Equity.Select(x => x.Day).ToArray()); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public void TheTrialEngineJudgesABasketTrial() + { + var data = BasketSynthetic.Crosses(420, 3, halfLife: 30); + var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 420); + var plan = Plan(days[120], days[^1], BasketModes.AsLive) with + { + Grid = new SortedDictionary>(StringComparer.Ordinal) + { + ["generation"] = [2m], + ["signal"] = [2m], + ["units"] = [2m], + ["target"] = [2m, 2.5m], + ["distance"] = [4m], + ["exit"] = [2m], + }, + }; + var engine = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data); + Assert.IsFalse(((ITrialEngine)engine).LongOnly, "a basket sells as well as buys: its control is not centred"); + Assert.AreEqual(260, engine.PeriodsPerYear); + StringAssert.Contains(engine.Fingerprint(), "|basket:" + BasketEngine.Version + "|costs:" + VenueCosts.Etoro.Fingerprint() + "|mode:come_dal_vivo"); + Assert.AreEqual(28, engine.Instruments().Count); + + var (report, summary) = TrialRunner.Run(Guid.NewGuid(), plan, "plan", BasketReversionFamily.Instance, engine, PriorTrials.None, plan.WrittenAt); + Assert.AreEqual(BasketReversionFamily.FamilyId, report.Strategy); + Assert.AreEqual(2, report.Variants.Count); + Assert.AreEqual(5, report.Checks.Count); + Assert.IsNotNull(report.Baskets); + Assert.IsTrue(report.Baskets.Count > 0); + Assert.AreEqual(0d, report.Benchmark.TotalReturn, "the comparison is zero, never buy and hold"); + Assert.AreEqual(300, report.Sessions, "the plan's window"); + Assert.IsTrue(report.Limitations.Any(l => l.Contains("BCE", StringComparison.Ordinal))); + Assert.IsNotNull(report.ExpectedPathP5); + Assert.AreEqual("USD", summary.Currency); + + // The control against chance flips each day's log returns of every pair with the day's sign: their size stays. + var signs = DaySigns.Draw(days[0], days[^1], 42); + var surrogate = (BasketTrialEngine)engine.Surrogate(signs, centred: false); + foreach (var pair in new[] { "EURUSD", "USDJPY", "GBPCHF" }) + { + var before = engine.Market.Reference(pair); + var after = surrogate.Market.Reference(pair); + for (var t = 1; t < before.Count; t++) + { + Assert.AreEqual(Math.Abs(Math.Log(before[t] / before[t - 1])), Math.Abs(Math.Log(after[t] / after[t - 1])), 1e-12, $"{pair} {t}"); + } + } + + Assert.AreEqual(engine.Sessions, surrogate.Run(StrategyParameters.Of(BasketReversionFamily.Instance, "generation=2;signal=2;units=2;target=2.5;distance=4;exit=2")).Equity.Count); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFamilyHasOneIdForEverySubVariant() + { + var family = BasketReversionFamily.Instance; + Assert.AreEqual("basket_reversion", family.Id); + Assert.IsNotInstanceOfType(family, "research only: never a strategy the bot could run"); + Assert.IsFalse(StrategyCatalog.All.Any(f => f.Id == family.Id)); + + var grid = new Dictionary>(StringComparer.Ordinal) + { + ["generation"] = [1m, 2m], + ["signal"] = [1m, 2m], + ["units"] = [1m, 2m], + ["exit"] = [1m, 2m], + ["profile"] = [1m, 2m], + ["growth"] = [1m, 1.3m], + ["averagings"] = [3m, 4m], + }; + var variants = ParameterGrid.Of(family, grid); + Assert.AreEqual(32 * 3, variants.Count, "four averagings only with growth"); + var units = new HashSet(StringComparer.Ordinal); + foreach (var v in variants) + { + var rules = family.Rules(v.Parameters, BasketMode.AsLive, Timeframes.Day); + units.UnionWith(rules.Units.Select(u => u.Name)); + Assert.AreEqual(v.Parameters["generation"] == 1m ? 5 : 10, rules.Units.Count); + } + + Assert.AreEqual(15, units.Count, "five documented spreads and ten symbols"); + + // The defaults: Moderato, generation A, z of the pip sum, 10 and 40 pips, Fedele. + var defaults = family.Rules(StrategyParameters.Of(family, null), BasketMode.AsLive, Timeframes.Day); + Assert.AreEqual(BasketSignal.ZScorePipSum, defaults.Signal); + Assert.AreEqual(BasketMeasure.Pips, defaults.Measure); + Assert.AreEqual((10m, 40m, 3, 2, 2.0), (defaults.Target, defaults.Distance, defaults.MaxAveragings, defaults.MaxOpenBaskets, defaults.EntryZ)); + Assert.AreEqual(BasketProfiles.Fedele, defaults.Profile); + Assert.AreEqual("EURUSD/USDCHF", defaults.Units[0].Name); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ChoiceAxesAreMarkedAsChoices() + { + var choices = BasketReversionFamily.Instance.Parameters.Where(p => p.Choices).Select(p => p.Name).Order(StringComparer.Ordinal).ToArray(); + CollectionAssert.AreEqual(new[] { "exit", "generation", "profile", "signal", "units" }, choices); + Assert.IsTrue(BasketReversionFamily.Instance.Parameters.Where(p => p.Choices).All(p => p.Whole)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ABasketPlanCarriesItsModeAndItsCosts() + { + var plan = Plan(new DateOnly(2000, 1, 3), new DateOnly(2026, 11, 30), BasketModes.AsLive); + var json = plan.ToJson(); + StringAssert.Contains(json, "\"mode\":\"come_dal_vivo\""); + StringAssert.Contains(json, "\"costs\":{\"venue\":\"etoro\""); + var back = TrialPlan.FromJson(json); + Assert.AreEqual(BasketModes.AsLive, back.Mode); + Assert.AreEqual(VenueCosts.Etoro, back.Costs); + Assert.AreEqual(json, back.ToJson(), "the stored text gives back the same plan and the same hash"); + + // A daily plan has neither: its text, and so its hash, is the one it always had. + var daily = plan with { Mode = null, Costs = null }; + Assert.IsFalse(daily.ToJson().Contains("\"mode\"", StringComparison.Ordinal) || daily.ToJson().Contains("\"costs\"", StringComparison.Ordinal)); + } + + // ----- data of the tests ----- + + private static BasketRunResult Run(BarDataset data, BasketRules rules, VenueCosts costs, decimal capital = 10_000m) => + new BasketEngine(BasketMarket.Of(data), costs, capital).Run(rules); + + /// A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen. + private static BasketRules SingleRules(FxPair pair, BasketMode mode) => new([BasketUnit.OnePair(pair)]) + { + Window = 10, + Target = 10m, + Distance = 1_000m, + Mode = mode, + MaxRvol = null, + }; + + private static TrialPlan Plan(DateOnly from, DateOnly to, string mode) => new( + BasketReversionFamily.FamilyId, + BasketReversionFamily.Instance.Version, + new SortedDictionary>(StringComparer.Ordinal), + new TrialData(TrialSources.Research, EcbCrosses.Venue, [.. FxPairs.All.Select(p => p.Name)], from, to), + 10_000m, + [1m, 2m, 3m], + TrialValidation.Default, + TrialThresholds.Default, + BasketEngine.Version, + new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero)) + { + Mode = mode, + Costs = VenueCosts.Etoro, + }; +}