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>
281 lines
15 KiB
C#
281 lines
15 KiB
C#
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);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task AnInterruptedBasketTrialIsRecordedAsFailedWithAnItalianReason()
|
|
{
|
|
// Ctrl+C or the stop of the container while the trial runs: the command's token is cancelled as soon as it says the
|
|
// trial is planned. The trial is recorded as failed with a reason the user can act on, no report is written, exit 1.
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
|
|
await using var engine = postgres;
|
|
var data = TempFolder.Create("baskets-stop");
|
|
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");
|
|
|
|
using var stop = new CancellationTokenSource();
|
|
using var output = new StopOnLine(stop, "Prova ");
|
|
var code = await BasketCommand.RunAsync(
|
|
["--offline", "--to", "2001-12-31", "--control", "1", "--out", outDir, "--platform", "docker", "--data-dir", data], output, env, new FakeHttp(), clock,
|
|
stop.Token).ConfigureAwait(false);
|
|
|
|
const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
|
|
Assert.AreEqual(1, code, output.ToString());
|
|
StringAssert.Contains(output.ToString(), "Non riuscito: " + Interrupted);
|
|
Assert.IsFalse(output.ToString().Contains(" at ", StringComparison.Ordinal), "no stack trace");
|
|
var trial = (await new TrialStore(db, clock).ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
|
|
Assert.AreEqual(TrialStatuses.Failed, trial.Status);
|
|
Assert.AreEqual(Interrupted, trial.Error);
|
|
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".md")), "an interrupted trial writes no report");
|
|
}
|
|
finally
|
|
{
|
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
|
TempFolder.Delete(data);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheLaboratoryFailsALeftoverBasketTrialWithAnAccurateReason()
|
|
{
|
|
// A basket trial left planned or running by a command that died is picked up by the laboratory at the next start. The
|
|
// family only runs from the command line: the trial fails with a reason that says so, not «no longer available».
|
|
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
|
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
|
|
var (plan, variants) = BasketProtocol.Plan(To, clock.UtcNow);
|
|
var left = await lab.Trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
|
|
|
|
await lab.ProcessAsync(left.Id, CancellationToken.None).ConfigureAwait(false);
|
|
|
|
var failed = (await lab.Trials.GetAsync(left.Id, CancellationToken.None).ConfigureAwait(false))!;
|
|
Assert.AreEqual(TrialStatuses.Failed, failed.Status);
|
|
Assert.AreEqual("Prova a panieri interrotta: si rilancia da riga di comando con «anubis backtest baskets».", failed.Error);
|
|
}
|
|
|
|
/// <summary>Console output that cancels the command's token at the first line starting with <c>start</c>.</summary>
|
|
private sealed class StopOnLine(CancellationTokenSource stop, string start) : StringWriter(System.Globalization.CultureInfo.InvariantCulture)
|
|
{
|
|
public override void WriteLine(string? value)
|
|
{
|
|
base.WriteLine(value);
|
|
if (value is not null && value.StartsWith(start, StringComparison.Ordinal))
|
|
{
|
|
stop.Cancel();
|
|
}
|
|
}
|
|
|
|
public override Task WriteLineAsync(string? value)
|
|
{
|
|
WriteLine(value);
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
/// <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();
|
|
}
|
|
}
|