Files
Anubis/tests/Anubis.Tests/BasketTrialEngineTests.cs
T
Alby96andClaude Opus 5.5 a8defde572 Fix the review findings of the basket engine, command and report
The independent review of Phase 14 found rules the engine applied
differently from the decisions, numbers the report labelled wrongly and
a command that left a trial "running" when interrupted.

Engine:
- The pause after the 9% account stop is read at the decision moment
  (the bar's close), like every other gate: on daily bars it no longer
  blocks one day past the server date change.
- In a one-pair basket, a level closed by the venue's mandatory stop
  closes the other levels at the next execution with their own reason,
  closed_with_stop (counted and labelled in the report); the basket's
  exit stays mandatory_stop, and a two-leg basket keeps orphan_leg.
- The cap of two entries per currency applies to new baskets only,
  never to the averagings of an open basket, and every leg is valued
  at the current mid: a Prudente long basket "come dal vivo" now makes
  its three averagings and Fedele writes no note on them.
- The surrogate of the control chains on the mid when the source has
  an ask, so each mid change keeps its size and the spread stays
  around the mid instead of moving the mid by a spread at each change
  of sign.
- The financing already charged on positions still open at the end is
  part of the run's fees (BacktestRun.AccruedFees, zero for the daily
  engine, kept in stored unit outcomes).

Report: the fee row says what it holds (commission and financing, the
spread is in the prices) and the cost-stress text matches what the
multiplier scales; baskets still open at the end are labelled as such
and left out of the share closed at the target; refusal labels say
what the engine checks; the ECB-price and cost limitations are no
longer printed twice; every count has the Italian thousands separator.

Command: Ctrl+C or SIGTERM cancels the run; the trial is recorded as
failed with "Prova interrotta prima della fine: rilancia «anubis
backtest baskets»." and the command exits 1; a trial that cannot start
is failed instead of thrown, and an unexpected error ends with an
Italian line, never a stack trace. The laboratory fails a leftover
basket trial with an accurate message instead of "Strategia non più
disponibile".

The Table 6.5 test comment no longer claims each price is the only one
that fits the row. The real report is regenerated on the same data and
database as the first run, which now counts as a prior trial.

refs #127 #129 #131

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

326 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// 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.
/// </summary>
[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<string, double[]> { ["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<string, (QuoteSide, QuoteSide)[]>
{
["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<string, IReadOnlyList<decimal>>(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 WithBidAndAskTheSurrogateKeepsTheSizeOfEveryMidChange()
{
// 15-minute EURUSD quotes two pips wide around a walking mid, from Tuesday 13 January 2026 20:00 UTC over four server
// days whose signs alternate. The engine reads the mid: in the surrogate every change of the mid keeps its size and
// the spread stays around it. Chained on the bid, the mid would jump by a whole spread at each change of sign.
var first = new DateTimeOffset(2026, 1, 13, 20, 0, 0, TimeSpan.Zero);
var walk = BasketSynthetic.Walk(200, 7, 0, 0.0004);
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
{
["EURUSD"] = [.. walk.Select(x => BasketSynthetic.Mid(Math.Round(1.1m * (decimal)Math.Exp(x), 5), 0.0002m))],
});
var market = BasketMarket.Of(data);
var days = market.Day(market.Count - 1).DayNumber - market.Day(0).DayNumber + 1;
Assert.IsTrue(days >= 3, $"{days} server days");
var signs = new DaySigns(market.Day(0), [.. Enumerable.Range(0, days).Select(i => i % 2 == 0 ? 1 : -1)]);
var surrogate = market.Surrogate(signs, centred: false);
var before = market.Reference("EURUSD");
var after = surrogate.Reference("EURUSD");
var (bid, ask) = (surrogate.Bid("EURUSD").Close, surrogate.Ask("EURUSD")!.Close);
var (bid0, ask0) = (market.Bid("EURUSD").Close, market.Ask("EURUSD")!.Close);
var turned = 0;
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-7, $"bar {t}");
Assert.IsTrue(bid[t] < ask[t], $"bar {t}");
Assert.AreEqual((ask0[t] - bid0[t]) / before[t], (ask[t] - bid[t]) / after[t], 1e-6, $"bar {t}: the spread stays around the mid");
turned += market.Day(t) != market.Day(t - 1) ? 1 : 0;
}
Assert.IsTrue(turned >= 2, $"{turned} changes of sign");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFamilyHasOneIdForEverySubVariant()
{
var family = BasketReversionFamily.Instance;
Assert.AreEqual("basket_reversion", family.Id);
Assert.IsNotInstanceOfType<IStrategyFamily>(family, "research only: never a strategy the bot could run");
Assert.IsFalse(StrategyCatalog.All.Any(f => f.Id == family.Id));
var grid = new Dictionary<string, IReadOnlyList<decimal>>(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<string>(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);
/// <summary>A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.</summary>
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<string, IReadOnlyList<decimal>>(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,
};
}