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

+11 -3
View File
@@ -15,17 +15,25 @@ namespace Anubis.Server;
/// them to euro, runs the protocol of <c>crypto_trend</c> on both universes and writes reports and outcome files.
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
/// "anubis backtest candidates" does the same for the candidates of SPEC 8.4 and leaves the other files alone.
/// "anubis backtest baskets" is the basket family's: <see cref="BasketCommand"/>.
/// </summary>
internal static class BacktestCommand
{
private const string Usage =
"Uso: anubis backtest base|candidates [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
internal const string Usage =
"Uso: anubis backtest base|candidates|baskets [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]\n" +
" baskets [--control 150] [--seed 20261202]: replica dell'appendice G, controllo contro il caso e prova del motore a panieri sui cambi BCE,\n" +
" registrata nel database (avvia prima il server una volta). Con --offline usa solo lo storico BCE già scaricato e si ferma se manca.";
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
HttpMessageHandler? handler = null)
{
output ??= Console.Out;
if (args.Length >= 1 && args[0] == "baskets")
{
return await BasketCommand.RunAsync(args[1..], output, environment, handler).ConfigureAwait(false);
}
if (args.Length < 1 || args[0] is not ("base" or "candidates"))
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
+207
View File
@@ -0,0 +1,207 @@
using System.Collections;
using System.Globalization;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Strategies;
namespace Anubis.Server;
/// <summary>
/// "anubis backtest baskets" (Phase 14, issue #131): the replica of appendix G of the research document on the 28 ECB
/// crosses, the control against chance of G.5 and the trial of the basket engine «come dal vivo» with the eToro costs
/// (<see cref="BasketProtocol"/>). The trial is planned in the configured database before it runs, read back and run only if
/// its stored plan is the one just written, judged with every earlier trial of the family counted, and recorded. The report
/// <c>basket_reversion.md</c> is written whatever the verdict; there is no outcome file for the family.
/// </summary>
internal static class BasketCommand
{
private const string Progress = "costi doppi e tripli, comprare e tenere";
public static async Task<int> RunAsync(string[] args, TextWriter output, IReadOnlyDictionary<string, string?>? environment = null,
HttpMessageHandler? handler = null, IClock? clock = null)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(output);
clock ??= new SystemClock();
var rest = args.ToList();
var offline = rest.Remove("--offline");
var own = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var name in new[] { "--to", "--out", "--control", "--seed" })
{
var index = rest.IndexOf(name);
if (index < 0)
{
continue;
}
if (index == rest.Count - 1)
{
return await UsageAsync(output, $"Manca il valore di {name}.").ConfigureAwait(false);
}
own[name] = rest[index + 1];
rest.RemoveRange(index, 2);
}
var now = clock.UtcNow;
DateOnly to;
if (own.TryGetValue("--to", out var t))
{
if (!DateOnly.TryParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out to))
{
return await UsageAsync(output, "--to vuole una data AAAA-MM-GG.").ConfigureAwait(false);
}
}
else
{
to = new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last day of the previous month.
}
var repetitions = BasketProtocol.ControlRepetitions;
if (own.TryGetValue("--control", out var c) && (!int.TryParse(c, NumberStyles.None, CultureInfo.InvariantCulture, out repetitions) || repetitions < 1))
{
return await UsageAsync(output, "--control vuole un numero intero di ripetizioni, almeno 1.").ConfigureAwait(false);
}
var seed = BasketProtocol.ControlSeed;
if (own.TryGetValue("--seed", out var s) && !int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out seed))
{
return await UsageAsync(output, "--seed vuole un numero intero.").ConfigureAwait(false);
}
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
var outDir = Path.GetFullPath(own.GetValueOrDefault("--out") ?? Path.Combine("docs", "backtests"));
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
return 1;
}
try
{
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
config.Data.Ensure();
Directory.CreateDirectory(outDir);
var rates = await RatesAsync(config.Data.Research, offline, handler, clock, output).ConfigureAwait(false);
var crosses = EcbCrosses.Build(rates);
var notes = BasketProtocol.Notes(crosses);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Cambi BCE: {EcbCrosses.Rates.Count} valute, {notes.Pairs} coppie, {notes.Days} giorni, dal {notes.First:yyyy-MM-dd} al {notes.Last:yyyy-MM-dd}.")).ConfigureAwait(false);
var series = StylisedReplica.EcbSeries(crosses, BasketProtocol.ReplicaThrough);
var replica = BasketProtocol.Replica(series);
var binding = replica.Where(r => r.Case.Binding).ToList();
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Replica dell'appendice G fino al {Earlier(notes.Last, BasketProtocol.ReplicaThrough):yyyy-MM-dd}: {binding.Count(r => r.Case.Passes(r.Result.Total))} su {binding.Count} righe vincolanti dentro la tolleranza.")).ConfigureAwait(false);
var control = BasketProtocol.Control(series, repetitions, seed);
var it = CultureInfo.GetCultureInfo("it-IT");
await output.WriteLineAsync(string.Create(it,
$"Controllo contro il caso: {repetitions} ripetizioni, seme {seed.ToString(CultureInfo.InvariantCulture)}. Pari o migliori: {string.Join("; ", control.Select(r => $"{r.Case.Label} {r.Case.StopLabel} {r.Control.Share * 100:0.0}% (documento {r.DocumentShare * 100:0}%)"))}."))
.ConfigureAwait(false);
var (plan, variants) = BasketProtocol.Plan(to, now);
var data = BasketProtocol.Dataset(crosses, to);
var trials = new TrialStore(db, clock);
var planned = await trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
if (!await trials.StartAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))
{
throw new InvalidOperationException("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.");
}
var trial = (await trials.GetAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))!;
var refusal = !trial.PlanIntact
? "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."
: trial.PlanHash != TrialPlan.Hash(plan.ToJson())
? "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."
: null;
if (refusal is not null)
{
await trials.FailAsync(trial.Id, refusal, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync("Non riuscito: " + refusal).ConfigureAwait(false);
return 1;
}
BacktestReport report;
try
{
var prior = await trials.PriorAsync(trial.Strategy, trial.Id, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Prova {trial.Id} pianificata con il piano {trial.PlanHash[..12]}: {variants} varianti dal {plan.Data.From:yyyy-MM-dd} al {plan.Data.To:yyyy-MM-dd}, prove precedenti contate: {prior.Trials}."))
.ConfigureAwait(false);
var engine = new BasketTrialEngine(trial.Plan, BasketReversionFamily.Instance, data);
var watch = System.Diagnostics.Stopwatch.StartNew();
var (judged, summary) = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, BasketReversionFamily.Instance, engine, prior, now,
text => output.WriteLine("Prova: " + (text == Progress ? "costi doppi e tripli, confronto con zero" : text)));
await trials.FinishAsync(trial.Id, judged.DataFingerprint, summary, judged.ToJson(), judged.Passed, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Prova calcolata in {watch.Elapsed.TotalSeconds:0} secondi.")).ConfigureAwait(false);
report = judged;
}
catch (Exception ex)
{
// A trial left running would be picked up by the laboratory at the next start: it is closed as failed.
await trials.FailAsync(trial.Id, Redactor.Redact(ex.Message), CancellationToken.None).ConfigureAwait(false);
throw;
}
var section = new BasketTrialSection(BasketProtocol.TrialName, trial.Plan, trial.PlanHash, report, trial.Plan.Mode ?? BasketModes.AsLive);
var command = "anubis backtest baskets --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
+ (repetitions == BasketProtocol.ControlRepetitions ? "" : " --control " + repetitions.ToString(CultureInfo.InvariantCulture))
+ (seed == BasketProtocol.ControlSeed ? "" : " --seed " + seed.ToString(CultureInfo.InvariantCulture));
var file = Path.Combine(outDir, BasketReport.Strategy + ".md");
await File.WriteAllTextAsync(file, BasketReport.Markdown(new BasketReportInput(command, now, notes, trial.Plan.Costs ?? VenueCosts.Etoro, replica, control, section, null)))
.ConfigureAwait(false);
await output.WriteLineAsync((report.Passed ? "Esito: superato. " : "Esito: non superato. ") + BasketReport.Verdict(section)).ConfigureAwait(false);
await output.WriteLineAsync("Rapporto scritto in " + file).ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
or ArgumentException or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException or System.Text.Json.JsonException
or SchemaException or System.Data.Common.DbException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
/// <summary>
/// The ECB rates of the seven currencies from the zip shared with <c>anubis data ecb</c>: downloaded again on every run;
/// with <paramref name="offline"/> only the copy already in the research folder, and an error when there is none.
/// </summary>
private static async Task<IReadOnlyList<FxRate>> RatesAsync(string research, bool offline, HttpMessageHandler? handler, IClock clock, TextWriter output)
{
if (offline && !File.Exists(Ecb.HistoryPath(research)))
{
throw new InvalidOperationException($"Manca lo storico dei cambi BCE già scaricato ({Ecb.HistoryPath(research)}): togli --offline o esegui prima «anubis data ecb».");
}
using var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
http.Timeout = TimeSpan.FromMinutes(5);
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
var rates = await Ecb.LoadHistoryAsync(new ApiHttp(http, clock, Ecb.Source), research, offline, EcbCrosses.Rates, CancellationToken.None).ConfigureAwait(false);
if (rates.Count == 0)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
}
await output.WriteLineAsync(offline ? "Storico BCE letto dalla copia già scaricata." : "Storico BCE scaricato di nuovo.").ConfigureAwait(false);
return rates;
}
private static DateOnly Earlier(DateOnly a, DateOnly b) => a < b ? a : b;
private static async Task<int> UsageAsync(TextWriter output, string problem)
{
await output.WriteLineAsync(problem).ConfigureAwait(false);
await output.WriteLineAsync(BacktestCommand.Usage).ConfigureAwait(false);
return 2;
}
}