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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 19:26:24 +01:00
1 parent 3bee136c74
commit a8defde572
15 files changed
+488 -143

No files matched your search

+86 -39
View File
@@ -1,5 +1,6 @@
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Brokers;
@@ -22,7 +23,7 @@ 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)
HttpMessageHandler? handler = null, IClock? clock = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(output);
@@ -82,14 +83,23 @@ internal static class BasketCommand
return 1;
}
// Ctrl+C, or the stop of the container (SIGTERM), cancels the run: the trial is closed as failed with a reason the user
// can act on, instead of staying «running» for the laboratory to find at the next start.
using var interrupted = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Interrupt);
using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Interrupt);
var token = interrupted.Token;
TrialStore? trials = null;
Guid? owned = null; // The trial this command planned and has not closed yet.
Database? db = null; // Disposed in finally: a failure closes the trial on it first.
try
{
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
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 rates = await RatesAsync(config.Data.Research, offline, handler, clock, output, token).ConfigureAwait(false);
var crosses = EcbCrosses.Build(rates);
var notes = BasketProtocol.Notes(crosses);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
@@ -97,11 +107,13 @@ internal static class BasketCommand
var series = StylisedReplica.EcbSeries(crosses, BasketProtocol.ReplicaThrough);
var replica = BasketProtocol.Replica(series);
token.ThrowIfCancellationRequested();
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);
token.ThrowIfCancellationRequested();
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}%)"))}."))
@@ -109,14 +121,15 @@ internal static class BasketCommand
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))
trials = new TrialStore(db, clock);
var planned = await trials.PlanAsync(plan, variants, token).ConfigureAwait(false);
owned = planned.Id;
if (!await trials.StartAsync(planned.Id, token).ConfigureAwait(false))
{
throw new InvalidOperationException("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.");
return await RefuseAsync("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.").ConfigureAwait(false);
}
var trial = (await trials.GetAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))!;
var trial = (await trials.GetAsync(planned.Id, token).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())
@@ -124,59 +137,93 @@ internal static class BasketCommand
: 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;
return await RefuseAsync(refusal).ConfigureAwait(false);
}
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 prior = await trials.PriorAsync(trial.Strategy, trial.Id, token).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 (report, 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)), token);
// Judged: the trial is recorded whatever comes now, an interruption included.
await trials.FinishAsync(trial.Id, report.DataFingerprint, summary, report.ToJson(), report.Passed, CancellationToken.None).ConfigureAwait(false);
owned = null;
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Prova calcolata in {watch.Elapsed.TotalSeconds:0} secondi.")).ConfigureAwait(false);
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)))
await File.WriteAllTextAsync(file, BasketReport.Markdown(new BasketReportInput(command, now, notes, trial.Plan.Costs ?? VenueCosts.Etoro, replica, control, section, null)), CancellationToken.None)
.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)
catch (OperationCanceledException) when (interrupted.IsCancellationRequested)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return await RefuseAsync(owned is null ? "interrotto prima che la prova fosse pianificata: nessuna prova registrata." : Interrupted).ConfigureAwait(false);
}
catch (Exception ex)
{
// Any failure, expected or not, ends with an Italian line and exit 1, never a stack trace; the trial it leaves is closed.
var message = 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
? Redactor.Redact(ex.Message)
: $"errore inatteso ({ex.GetType().Name}): {Redactor.Redact(ex.Message)}";
return await RefuseAsync(message).ConfigureAwait(false);
}
finally
{
if (db is not null)
{
await db.DisposeAsync().ConfigureAwait(false);
}
}
// Closes the trial this command still holds, if any, with the reason, and says it: exit 1.
async Task<int> RefuseAsync(string reason)
{
if (trials is not null && owned is { } id)
{
owned = null;
try
{
await trials.FailAsync(id, reason, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or InvalidOperationException or TimeoutException)
{
await output.WriteLineAsync("La prova non si è potuta segnare come non riuscita: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
}
}
await output.WriteLineAsync("Non riuscito: " + reason).ConfigureAwait(false);
return 1;
}
void Interrupt(PosixSignalContext context)
{
context.Cancel = true;
interrupted.Cancel();
}
}
/// <summary>What an interrupted trial says, in the register and on the console.</summary>
internal const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
/// <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)
private static async Task<IReadOnlyList<FxRate>> RatesAsync(string research, bool offline, HttpMessageHandler? handler, IClock clock, TextWriter output, CancellationToken cancellationToken)
{
if (offline && !File.Exists(Ecb.HistoryPath(research)))
{
@@ -186,7 +233,7 @@ internal static class BasketCommand
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);
var rates = await Ecb.LoadHistoryAsync(new ApiHttp(http, clock, Ecb.Source), research, offline, EcbCrosses.Rates, cancellationToken).ConfigureAwait(false);
if (rates.Count == 0)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");