Add the backtest baskets command and the basket family's report

`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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 18:40:49 +01:00
1 parent d1ae650043
commit 3bee136c74
8 files changed
+830 -34

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
using System.IO.Compression;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Server;
namespace Anubis.Tests;
/// <summary>
/// "anubis backtest baskets" (Phase 14, issue #131): from the command line, on the database of this run (SQLite here,
/// PostgreSQL in CI), with the ECB history of the research document already in the research folder and no network. The
/// plan is written before the trial, read back and run only when it is still the one written; every run counts the earlier
/// ones; the report is written whatever the verdict.
/// </summary>
[TestClass]
public sealed class BasketCommandTests
{
private const string EcbFile = "free/ecb-hist-1999-2026-12-02.csv";
private static readonly DateOnly To = new(2001, 12, 31);
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ABasketTrialRunsFromTheCommandLineWithItsPlanIntact()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
await using var engine = postgres;
var data = TempFolder.Create("baskets");
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
try
{
var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
await using var db = Database.Open(config.Db!);
await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
Directory.CreateDirectory(config.Data.Research);
await File.WriteAllBytesAsync(Ecb.HistoryPath(config.Data.Research), EcbZip()).ConfigureAwait(false);
var outDir = Path.Combine(data, "out");
var report = Path.Combine(outDir, BasketReport.Strategy + ".md");
var store = new TrialStore(db, clock);
var network = new FakeHttp();
string[] args = ["baskets", "--offline", "--to", "2001-12-31", "--control", "5", "--out", outDir, "--platform", "docker", "--data-dir", data];
async Task<(int Code, string Text)> RunAsync()
{
using var output = new StringWriter();
var code = await BasketCommand.RunAsync([.. args.Skip(1)], output, env, network, clock).ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(1));
return (code, output.ToString());
}
// The first run: replica, control and trial, the plan written and judged as it was written.
var written = BasketProtocol.Plan(To, clock.UtcNow).Plan;
var (code, text) = await RunAsync().ConfigureAwait(false);
Assert.AreEqual(0, code, text);
StringAssert.Contains(text, "13 su 13 righe vincolanti dentro la tolleranza");
StringAssert.Contains(text, "Esito: ");
StringAssert.Contains(text, "Rapporto scritto in " + report);
var markdown = await File.ReadAllTextAsync(report).ConfigureAwait(false);
StringAssert.Contains(markdown, "**Esito: ");
StringAssert.Contains(markdown, "13 righe vincolanti su 13 dentro la tolleranza.");
StringAssert.Contains(markdown, "`anubis backtest baskets --to 2001-12-31 --control 5`");
StringAssert.Contains(markdown, "| 5 | 20261202 |");
Assert.AreEqual(0, network.Requests.Count, "offline with the cached history: no request");
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".outcome.json")), "no outcome file for the basket family");
var first = (await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
Assert.AreEqual(TrialStatuses.Done, first.Status, first.Error);
Assert.IsTrue(first.PlanIntact);
Assert.AreEqual(TrialPlan.Hash(written.ToJson()), first.PlanHash);
Assert.AreEqual(written.ToJson(), first.Plan.ToJson());
Assert.AreEqual(BasketModes.AsLive, first.Plan.Mode);
Assert.AreEqual(VenueCosts.Etoro.Fingerprint(), first.Plan.Costs!.Fingerprint());
Assert.AreEqual(BasketEngine.Version, first.Plan.Engine);
Assert.AreEqual(BasketProtocol.Capital, first.Plan.InitialCapital);
Assert.AreEqual(4, first.Variants);
var judged = BacktestReport.FromJson((await store.ReportJsonAsync(first.Id, CancellationToken.None).ConfigureAwait(false))!);
Assert.AreEqual(first.PlanHash, judged.PlanHash);
Assert.AreEqual(4, judged.TrialsCounted);
StringAssert.Contains(markdown, "`" + first.PlanHash[..12] + "`");
// The same plan again: accepted, a trial of its own, and the first one counts in its deflated Sharpe.
(code, text) = await RunAsync().ConfigureAwait(false);
Assert.AreEqual(0, code, text);
StringAssert.Contains(text, "prove precedenti contate: 1");
var trials = await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false);
Assert.HasCount(2, trials);
Assert.IsTrue(trials.All(t => t.Status == TrialStatuses.Done && t.PlanIntact));
Assert.AreEqual(8, BacktestReport.FromJson((await store.ReportJsonAsync(trials[0].Id, CancellationToken.None).ConfigureAwait(false))!).TrialsCounted);
var kept = await File.ReadAllTextAsync(report).ConfigureAwait(false);
// A plan changed in the register after it was written: refused, recorded as failed, the report left as it was. First
// its hash no longer matches; then the grid is changed and the hash written again to match.
string WiderGrid()
{
var grid = new SortedDictionary<string, IReadOnlyList<decimal>>(BasketProtocol.Grid.ToDictionary(), StringComparer.Ordinal) { ["distance"] = [4m, 12m] };
var json = (BasketProtocol.Plan(To, clock.UtcNow).Plan with { Grid = grid }).ToJson();
return $"SET plan = '{json.Replace("'", "''", StringComparison.Ordinal)}', plan_hash = '{TrialPlan.Hash(json)}'";
}
(Func<string> Sql, string Error)[] tampers =
[
(() => "SET plan_hash = '0'", "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."),
(WiderGrid, "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."),
];
foreach (var (sql, error) in tampers)
{
await TamperAsync(db, sql()).ConfigureAwait(false);
(code, text) = await RunAsync().ConfigureAwait(false);
await UntamperAsync(db).ConfigureAwait(false);
Assert.AreEqual(1, code, text);
StringAssert.Contains(text, "Non riuscito: " + error);
var refused = (await store.ListAsync(1, CancellationToken.None).ConfigureAwait(false))[0];
Assert.AreEqual(TrialStatuses.Failed, refused.Status);
Assert.AreEqual(error, refused.Error);
Assert.AreEqual(kept, await File.ReadAllTextAsync(report).ConfigureAwait(false), "a refused trial writes no report");
}
Assert.AreEqual(2, (await store.PriorAsync(BasketReport.Strategy, Guid.Empty, CancellationToken.None).ConfigureAwait(false)).Trials, "refused trials are not counted");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task OfflineWithoutTheEcbHistoryTheCommandStopsInItalian()
{
var data = TempFolder.Create("baskets-offline");
try
{
var env = ServerHarness.DockerSqlite();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
await using (var db = Database.Open(config.Db!))
{
await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
}
var network = new FakeHttp();
using var output = new StringWriter();
Assert.AreEqual(1, await BasketCommand.RunAsync(["--offline", "--platform", "docker", "--data-dir", data], output, env, network, clock).ConfigureAwait(false));
StringAssert.Contains(output.ToString(), "Non riuscito: Manca lo storico dei cambi BCE già scaricato");
Assert.AreEqual(0, network.Requests.Count);
using var usage = new StringWriter();
Assert.AreEqual(2, await BacktestCommand.RunAsync(["baskets", "--control", "zero", "--platform", "docker", "--data-dir", data], usage, env).ConfigureAwait(false));
StringAssert.Contains(usage.ToString(), "base|candidates|baskets");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
/// <summary>A trigger that changes every plan as soon as it is written: someone touching the register behind the command.</summary>
private static async Task TamperAsync(Database db, string set)
{
if (db.Engine == Anubis.Platform.DbEngine.Postgres)
{
await db.WriteAsync(s => s.ExecuteAsync(
$"CREATE FUNCTION tamper_plan() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; RETURN NULL; END $$",
CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
await db.WriteAsync(s => s.ExecuteAsync("CREATE TRIGGER tamper AFTER INSERT ON backtest_trials FOR EACH ROW EXECUTE FUNCTION tamper_plan()", CancellationToken.None),
CancellationToken.None).ConfigureAwait(false);
return;
}
await db.WriteAsync(s => s.ExecuteAsync($"CREATE TRIGGER tamper AFTER INSERT ON backtest_trials BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; END",
CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
}
private static async Task UntamperAsync(Database db)
{
if (db.Engine == Anubis.Platform.DbEngine.Postgres)
{
await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper ON backtest_trials", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
await db.WriteAsync(s => s.ExecuteAsync("DROP FUNCTION tamper_plan()", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
return;
}
await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
}
/// <summary>The fixture of the research document's ECB history, zipped as the ECB serves it and as the cache keeps it.</summary>
private static byte[] EcbZip()
{
using var zip = new MemoryStream();
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open()))
{
writer.Write(Fixture.Text(EcbFile));
}
return zip.ToArray();
}
}