`anubis backtest baskets` reruns the replica of appendix G on the 28 ECB crosses up to the research document's end, the G.5 control against chance, and a trial of the basket engine "come dal vivo" with the eToro costs on 20,000 USD, from 1999 to the chosen day on a grid fixed in BasketProtocol (generation A/B x distance 4/10 sigma). The plan is written to the trial register before the run, read back and run only if it is still the plan just written (a changed or re-hashed plan fails the trial), judged with every earlier basket_reversion trial counted, and recorded. --offline reads only the cached ECB zip and stops in Italian when it is missing. The report is written whatever the verdict; there is no outcome file. The report now labels max_positions and clock_window, reads its codes from BasketReasons and BasketModes, counts positions closed by the mandatory stop instead of listing them among refused entries, and no longer repeats the engine's own limitations. The generated report is committed: 13 of 13 binding replica rows inside the band, verdict not passed (net at double costs and DSR). refs #131 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
364 lines
18 KiB
C#
364 lines
18 KiB
C#
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using Anubis.Backtest;
|
||
using Anubis.Baskets;
|
||
using Anubis.Core;
|
||
using Anubis.Strategies;
|
||
|
||
namespace Anubis.Tests;
|
||
|
||
/// <summary>
|
||
/// The report of the basket family (Phase 14, issue #131): <c>docs/backtests/basket_reversion.md</c> is written whatever
|
||
/// the verdict, shows the 15 rows of the replica of appendix G with the binding ones counted, the control against chance,
|
||
/// the trial of the basket engine with its orphan legs counted, compares with zero and never with buy and hold, writes
|
||
/// numbers the Italian way and never names the product the research document describes.
|
||
/// </summary>
|
||
[TestClass]
|
||
public sealed class BasketReportTests
|
||
{
|
||
private const string Command = "anubis backtest baskets --to 2026-11-30";
|
||
|
||
/// <summary>SHA-256 of the lower-case name of the product the research document describes: the test never writes it.</summary>
|
||
private const string ProductNameSha256 = "9f00a2f4b75ffa8777d52da7e1a4a5a7c99929f0709b13cb0bc727003bbf9607";
|
||
|
||
private const int ProductNameLength = 6;
|
||
|
||
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 30, 0, TimeSpan.Zero);
|
||
|
||
private static readonly DateOnly First = new(2024, 1, 1);
|
||
|
||
/// <summary>The prototype's totals, positions and baskets of the 15 rows of G.4: what the replica gives on the ECB file.</summary>
|
||
private static readonly (double Total, int Positions, int Baskets)[] Ours =
|
||
[
|
||
(535.5, 1675, 1259), (543.7, 2047, 1543), (257.2, 2390, 1788),
|
||
(753.6, 1953, 1467), (1029.1, 2583, 1929), (-100.8, 2937, 2186),
|
||
(340.1, 1424, 1066), (536.3, 1641, 1223), (138.4, 1936, 1447),
|
||
(647.1, 1977, 1167), (439.5, 2702, 1590), (-47.4, 3650, 2166),
|
||
(531.3, 2133, 1273), (757.4, 3010, 1796), (169.9, 3455, 2109),
|
||
];
|
||
|
||
private static readonly Lazy<BasketTrialSection> _trial = new(BuildTrial);
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheReportIsWrittenWhateverTheVerdict()
|
||
{
|
||
var trial = _trial.Value;
|
||
var passed = BasketReport.Markdown(Input(trial with { Report = trial.Report with { Passed = true } }));
|
||
var failedReport = trial.Report with
|
||
{
|
||
Passed = false,
|
||
Checks = [.. trial.Report.Checks.Select(c => c.Key == ReportCheckKeys.Drawdown ? c with { Value = 0.38, Passed = false } : c)],
|
||
};
|
||
var failed = BasketReport.Markdown(Input(trial with { Report = failedReport }));
|
||
var waiting = BasketReport.Markdown(Input(null, "Mancano i cambi della BCE: la prova del motore non è partita."));
|
||
|
||
foreach (var text in new[] { passed, failed, waiting })
|
||
{
|
||
Assert.IsTrue(text.StartsWith("# Backtest di `basket_reversion` (Rientro tra strumenti)" + Environment.NewLine, StringComparison.Ordinal), text[..80]);
|
||
StringAssert.Contains(text, "Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).");
|
||
StringAssert.Contains(text, "Per rifarlo: `" + Command + "`");
|
||
StringAssert.Contains(text, "## Dati");
|
||
StringAssert.Contains(text, "## Replica dell'appendice G");
|
||
StringAssert.Contains(text, "## Controllo contro il caso (G.5)");
|
||
StringAssert.Contains(text, "## Cosa il backtest non rappresenta");
|
||
Assert.IsFalse(text.Contains("outcome.json", StringComparison.Ordinal), "No outcome file for baskets in this phase.");
|
||
Assert.IsFalse(text.Contains("letto dal bot", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Dati", StringComparison.Ordinal) < text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal) < text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal) < text.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
|
||
}
|
||
|
||
StringAssert.Contains(passed, "**Esito: superato.**");
|
||
StringAssert.Contains(passed, "## Prova del motore a panieri");
|
||
StringAssert.Contains(passed, "versione basket-1 del motore a panieri");
|
||
StringAssert.Contains(passed, "«come dal vivo»");
|
||
StringAssert.Contains(passed, "Motore finto della prova.");
|
||
Assert.IsTrue(passed.IndexOf("## Prova del motore a panieri", StringComparison.Ordinal) < passed.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
|
||
|
||
StringAssert.Contains(failed, "**Esito: non superato.**");
|
||
StringAssert.Contains(failed, "calo massimo 38,0%");
|
||
StringAssert.Contains(failed, "**non superato**");
|
||
|
||
StringAssert.Contains(waiting, "**Esito: in attesa.** Mancano i cambi della BCE: la prova del motore non è partita.");
|
||
Assert.IsFalse(waiting.Contains("## Prova del motore a panieri", StringComparison.Ordinal));
|
||
StringAssert.Contains(waiting, "file a 1 minuto");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheReplicaTableShowsEveryRowAndCountsTheBindingOnes()
|
||
{
|
||
var text = BasketReport.Markdown(Input(null, "Nessuna prova."));
|
||
var replica = Section(text, "## Replica dell'appendice G");
|
||
|
||
StringAssert.Contains(replica, "| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |");
|
||
foreach (var c in ReplicaSettings.DocumentCases)
|
||
{
|
||
var row = "| " + c.Label + " | " + c.StopLabel + " |";
|
||
Assert.AreEqual(2, Count(replica, row), row + " in the totals and in the break-even table.");
|
||
}
|
||
|
||
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 535,5 | +1,5 | ±26,7 | sì | dentro |");
|
||
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 90 obiettivi | 1.032 | 1.029,1 | −2,9 | ±51,6 | sì | dentro |");
|
||
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 30 obiettivi | −98 | −100,8 | −2,8 | ±25 | no | solo riportata |");
|
||
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | +0,32 | +0,32 | 1.675 | 1.259 | ");
|
||
StringAssert.Contains(replica, "13 righe vincolanti su 13 dentro la tolleranza.");
|
||
StringAssert.Contains(replica, "2 σ · 8 σ · 3 con stop di 30 obiettivi");
|
||
StringAssert.Contains(replica, "2,5 σ · 4 σ · 3 con stop di 30 obiettivi");
|
||
StringAssert.Contains(replica, "mai giudicata");
|
||
|
||
var rows = ReplicaRows();
|
||
rows[0] = rows[0] with { Result = rows[0].Result with { Total = 400 } };
|
||
var off = Section(BasketReport.Markdown(Input(null, "Nessuna prova.") with { Replica = rows }), "## Replica dell'appendice G");
|
||
StringAssert.Contains(off, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 400 | −134 | ±26,7 | sì | **fuori** |");
|
||
StringAssert.Contains(off, "12 righe vincolanti su 13 dentro la tolleranza.");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void OrphanLegsAreCountedInTheReport()
|
||
{
|
||
var trial = _trial.Value;
|
||
var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero);
|
||
ReportBasket[] baskets =
|
||
[
|
||
new("EURUSD-USDCHF", opened, opened.AddDays(3), 1_000m, 2, ["EURUSD", "USDCHF"], "mandatory_stop", -40m),
|
||
new("EURUSD-USDCHF", opened.AddDays(3), opened.AddDays(4), 1_000m, 2, ["EURUSD", "USDCHF"], "orphan_leg", -12m),
|
||
new("AUDNZD", opened.AddDays(5), opened.AddDays(9), 1_000m, 1, ["AUDNZD"], "target", 9m),
|
||
new("AUDNZD", opened.AddDays(10), opened.AddDays(12), 1_000m, 1, ["AUDNZD"], "target", 8m),
|
||
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], null, -3m),
|
||
];
|
||
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
|
||
{
|
||
["orphan_leg"] = 2,
|
||
["gate_open_loss"] = 5,
|
||
["weird_code"] = 1,
|
||
};
|
||
var two = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes, Baskets = baskets } })), "## Prova del motore a panieri");
|
||
StringAssert.Contains(two, "Gambe rimaste sole: 2");
|
||
StringAssert.Contains(two, "| stop obbligatorio della piattaforma | 1 |");
|
||
StringAssert.Contains(two, "| gamba rimasta sola dopo uno stop obbligatorio | 1 |");
|
||
StringAssert.Contains(two, "| obiettivo raggiunto | 2 |");
|
||
StringAssert.Contains(two, "| ancora aperto alla fine | 1 |");
|
||
StringAssert.Contains(two, "Panieri della variante giudicata: 5.");
|
||
StringAssert.Contains(two, "perdita aperta oltre il 2%");
|
||
StringAssert.Contains(two, "| `weird_code` | 1 |");
|
||
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0%");
|
||
|
||
var none = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = new Dictionary<string, int>(), Baskets = [] } })), "## Prova del motore a panieri");
|
||
StringAssert.Contains(none, "Gambe rimaste sole: 0");
|
||
StringAssert.Contains(none, "Chiusure d'ufficio per margine insufficiente: 0");
|
||
StringAssert.Contains(none, "Stop sul valore del conto: 0");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void EveryCodeOfTheEngineHasAnItalianLabel()
|
||
{
|
||
var trial = _trial.Value;
|
||
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
|
||
{
|
||
[BasketReasons.PositionLimit] = 3,
|
||
[BasketReasons.ClockWindow] = 4,
|
||
[BasketReasons.MandatoryStop] = 6,
|
||
[BasketReasons.GateOpenLoss] = 1,
|
||
[BasketReasons.PausedUntilNextDay] = 1,
|
||
[BasketReasons.DailyLossBlock] = 1,
|
||
[BasketReasons.HalfSize] = 1,
|
||
[BasketReasons.BelowVenueMinimum] = 1,
|
||
[BasketReasons.MarginLimit] = 1,
|
||
[BasketReasons.OppositePosition] = 1,
|
||
[BasketReasons.CurrencyExposure] = 1,
|
||
[BasketReasons.CostRule] = 1,
|
||
[BasketReasons.RvolFilter] = 1,
|
||
[BasketReasons.CorrelationLow] = 1,
|
||
[BasketReasons.SwitchTripped] = 1,
|
||
[BasketReasons.MaxOpenBaskets] = 1,
|
||
};
|
||
var text = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes } })), "## Prova del motore a panieri");
|
||
StringAssert.Contains(text, "| troppe posizioni aperte per la piattaforma | 3 |");
|
||
StringAssert.Contains(text, "| fuori dalla finestra oraria | 4 |");
|
||
StringAssert.Contains(text, "Posizioni chiuse dallo stop obbligatorio della piattaforma: 6.");
|
||
var refusals = text[text.IndexOf("**Ingressi e mediazioni fermati o annotati**", StringComparison.Ordinal)..];
|
||
Assert.IsFalse(refusals.Contains('`', StringComparison.Ordinal), "a code without a label: " + refusals);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheComparisonIsZeroNeverBuyAndHold()
|
||
{
|
||
var text = BasketReport.Markdown(Input(_trial.Value));
|
||
StringAssert.Contains(text, "| | Strategia | Zero (nessuna operazione) |");
|
||
StringAssert.Contains(text, "zero (nessuna operazione)");
|
||
Assert.IsFalse(text.Contains("comprare e tenere", StringComparison.OrdinalIgnoreCase));
|
||
Assert.IsFalse(text.Contains("buy and hold", StringComparison.OrdinalIgnoreCase));
|
||
StringAssert.Contains(text, "**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)");
|
||
StringAssert.Contains(text, "| ×2 |");
|
||
StringAssert.Contains(text, "| ×3 |");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void NumbersAreItalianAndTheProductIsNeverNamed()
|
||
{
|
||
var texts = new[]
|
||
{
|
||
BasketReport.Markdown(Input(_trial.Value)),
|
||
BasketReport.Markdown(Input(null, "Nessuna prova.")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketReport.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketProtocol.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "BasketCommand.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "backtests", "basket_reversion.md")),
|
||
};
|
||
var text = texts[0];
|
||
StringAssert.Contains(text, "535,5");
|
||
StringAssert.Contains(text, "−100,8");
|
||
Assert.IsFalse(text.Contains("535.5", StringComparison.Ordinal));
|
||
Assert.IsFalse(text.Contains("-100,8", StringComparison.Ordinal), "The minus is U+2212, as in the other reports.");
|
||
StringAssert.Contains(text, "1.000 USD");
|
||
StringAssert.Contains(text, "0,005%");
|
||
StringAssert.Contains(text, "dal 04/01/1999 al 02/12/2026");
|
||
StringAssert.Contains(text, "`f298c1dcc4be`");
|
||
StringAssert.Contains(text, "| 2,5 σ · 10 σ · 3 | nessuno | 150 | 20261202 | +0,32 | ");
|
||
StringAssert.Contains(text, " | 35,0% | 37% |");
|
||
|
||
foreach (var t in texts)
|
||
{
|
||
var lower = t.ToLowerInvariant();
|
||
for (var i = 0; i + ProductNameLength <= lower.Length; i++)
|
||
{
|
||
var window = lower.AsSpan(i, ProductNameLength);
|
||
if (!char.IsLetter(window[0]))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(window.ToString())));
|
||
Assert.AreNotEqual(ProductNameSha256, hash, "The report names the product the research document describes, at " + i + ".");
|
||
}
|
||
}
|
||
}
|
||
|
||
private static BasketReportInput Input(BasketTrialSection? trial, string? missing = null) => new(
|
||
Command,
|
||
Now,
|
||
new BasketDataNotes("Banca centrale europea, cambi di riferimento (eurofxref-hist)", "f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8",
|
||
new DateOnly(1999, 1, 4), new DateOnly(2026, 12, 2), 7_149, 28, new DateOnly(2026, 12, 2)),
|
||
VenueCosts.Etoro,
|
||
ReplicaRows(),
|
||
ControlRows(),
|
||
trial,
|
||
missing);
|
||
|
||
private static List<BasketReplicaRow> ReplicaRows() =>
|
||
[.. ReplicaSettings.DocumentCases.Select((c, i) => new BasketReplicaRow(c, new ReplicaResult(Ours[i].Total, Ours[i].Positions, Ours[i].Baskets, (int)(Ours[i].Baskets * 0.97), 0, [])))];
|
||
|
||
private static List<BasketControlRow> ControlRows()
|
||
{
|
||
var replicas = Enumerable.Range(0, 150).Select(i => -1.8 + (2.7 * i / 149.0)).ToArray();
|
||
return [.. BasketReport.DocumentControl.Select(d => new BasketControlRow(d.Case, new ReplicaControl(0.32, replicas, 0.35), 150, 20_261_202, d.Share))];
|
||
}
|
||
|
||
private static string Section(string text, string heading)
|
||
{
|
||
var start = text.IndexOf(heading, StringComparison.Ordinal);
|
||
Assert.IsTrue(start >= 0, heading);
|
||
var end = text.IndexOf("\n## ", start + heading.Length, StringComparison.Ordinal);
|
||
return end < 0 ? text[start..] : text[start..end];
|
||
}
|
||
|
||
private static int Count(string text, string part)
|
||
{
|
||
var count = 0;
|
||
for (var i = text.IndexOf(part, StringComparison.Ordinal); i >= 0; i = text.IndexOf(part, i + part.Length, StringComparison.Ordinal))
|
||
{
|
||
count++;
|
||
}
|
||
|
||
return count;
|
||
}
|
||
|
||
private static BasketTrialSection BuildTrial()
|
||
{
|
||
var plan = new TrialPlan(
|
||
"basket_reversion",
|
||
"1",
|
||
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal) { ["target"] = [2m, 2.5m, 3m] },
|
||
new TrialData(TrialSources.Research, "ecb", ["EURUSD", "USDCHF", "AUDNZD"], First, First.AddDays(StubEngine.Days - 1)),
|
||
StubEngine.Capital,
|
||
[1m, 2m, 3m],
|
||
TrialValidation.Default,
|
||
TrialThresholds.Default,
|
||
"basket-1",
|
||
Now);
|
||
var hash = TrialPlan.Hash(plan.ToJson());
|
||
var (report, _) = TrialRunner.Run(new Guid("6a1f0c3e-2b7d-4e59-8c1a-9d3e5f7a0b2c"), plan, hash, StubFamily.Instance, new StubEngine(), PriorTrials.None, Now);
|
||
return new BasketTrialSection("Le 28 coppie della BCE, generazione B in σ", plan, hash, report, BasketReport.LikeLive);
|
||
}
|
||
|
||
/// <summary>A research family with one numeric axis, under the basket family's id.</summary>
|
||
private sealed class StubFamily : IResearchFamily
|
||
{
|
||
public static StubFamily Instance { get; } = new();
|
||
|
||
public string Id => "basket_reversion";
|
||
|
||
public string Version => "1";
|
||
|
||
public string Name => "Rientro tra strumenti";
|
||
|
||
public string Description => "Famiglia finta per provare il rapporto dei panieri.";
|
||
|
||
public IReadOnlyList<ParameterSpec> Parameters => [new("target", "Obiettivo", 2.5m, [2m, 2.5m, 3m], 1m, 5m)];
|
||
}
|
||
|
||
/// <summary>An engine with a flat benchmark (zero) and a noisy equity that depends on the target.</summary>
|
||
private sealed class StubEngine : ITrialEngine
|
||
{
|
||
public const int Days = 320;
|
||
public const decimal Capital = 20_000m;
|
||
|
||
public string Currency => "USD";
|
||
|
||
public bool LongOnly => false;
|
||
|
||
public int PeriodsPerYear => 260;
|
||
|
||
public int Sessions => Days;
|
||
|
||
public string Fingerprint() => "f298c1dcc4be41a4|basket:basket-1";
|
||
|
||
public IReadOnlyList<ReportInstrument> Instruments() => [new("EURUSD", "ecb", First, First.AddDays(Days - 1), Days, 0, "file")];
|
||
|
||
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
|
||
{
|
||
var target = (double)parameters["target"];
|
||
var random = new SeededRandom((int)(target * 10));
|
||
var equity = new List<EquityPoint>();
|
||
var value = Capital;
|
||
for (var i = 0; i < Days; i++)
|
||
{
|
||
if (i > 0)
|
||
{
|
||
value *= 1m + (decimal)((0.0002 * target) + (0.006 * random.Normal())) - (0.0001m * (costMultiplier - 1m));
|
||
value = Math.Round(value, 6);
|
||
}
|
||
|
||
equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m));
|
||
}
|
||
|
||
return new BacktestRun(Currency, Capital, equity, [], [], [], []);
|
||
}
|
||
|
||
public BacktestRun Benchmark() =>
|
||
new(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []);
|
||
|
||
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => new([First.AddDays(100)], 12, []);
|
||
|
||
public IReadOnlyList<string> Limitations() => ["Motore finto della prova."];
|
||
|
||
public TrialExpectations Expected(BacktestRun run, double[] returns) => new(null, null);
|
||
}
|
||
}
|