Fase 13 — Campionato: unità di lavoro, piano e statistica #188

Merged
Alby96 merged 6 commits from fase-13 into main 2026-12-04 15:53:44 +01:00
15 changed files with 1233 additions and 115 deletions
Showing only changes of commit b564871391 - Show all commits

No files matched your search

+2
View File
@@ -264,6 +264,8 @@ Per ripartire, togli il file e conferma dalla pagina Rischio.
**Parametri delle strategie.** Non si toccano dall'interfaccia: sono quelli con cui ogni strategia è stata provata. Un cambio è una nuova prova in Laboratorio. Si cambiano invece capitale, ripartizione, limiti di rischio, regole sulle notizie e del modello.
**Operai del Laboratorio.** In Impostazioni → Sistema dici quanti calcoli di una prova del Laboratorio girano insieme: uno all'inizio, al massimo uno in meno dei processori. Alzalo solo dopo averne misurato l'effetto, perché il Laboratorio non deve togliere tempo al trading; vale dalla prossima prova. Se il bot si ferma a metà di una prova, alla ripartenza rifà solo i calcoli che non aveva finito.
**Notizie, calendario e trimestrali: solo misurate o attive.** In Impostazioni → Notizie l'interruttore sopra le cinque regole dice se agiscono. «Solo misurate» è il predefinito: le decisioni guardano solo i prezzi, e ogni regola scrive in ombra che cosa avrebbe fatto. «Attive» è il comportamento delle versioni precedenti: le regole accese possono fermare o rinviare un acquisto. Il bot non le riaccende mai da solo. Prima di farlo guarda nel Laboratorio la tabella delle regole in ombra: una regola merita di agire solo dopo almeno 6 mesi di misura, almeno 30 ingressi cambiati e un effetto tutto sopra lo zero (la riga dice «Criterio raggiunto»). Per riaccenderne una sola, spegni le altre righe e poi scegli «Attive». Passare da «Attive» a «Solo misurate» toglie protezioni: se una strategia usa soldi veri chiede la frase, la password e, se l'hai attivato, il codice a sei cifre, come quando spegni una regola. Ogni cambio lascia una riga nel Diario. Con le regole solo misurate un modello in carica che usa indizi delle notizie, delle trimestrali o di paura e avidità viene messo da parte subito. La domenica ne addestra uno senza, che prende il posto solo dopo aver vinto i confronti con il modello in carica; nel frattempo nessun modello conta.
Chi aggiorna da una versione precedente trova nel Diario una riga sola: da questa versione le regole sono solo misurate. Le decisioni prese prima restano come erano, con le regole attive.
+1 -1
View File
@@ -437,7 +437,7 @@ internal sealed partial class AnubisHost(
}
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger, ct => LaboratorySettings.WorkersAsync(settings, ct));
if (_lab is { } laboratory && _trading is { } running && _market is { } market)
{
async Task<bool> HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet;
@@ -4,6 +4,7 @@
@inject ShellData Shell
@inject SecondFactorDrafts Drafts
@inject Anubis.Core.IClock Clock
@using Anubis.Backtest
@using Anubis.Data
@using Anubis.Trading
@@ -646,6 +647,16 @@
</dl>
<p class="hint">Motore e connessione del database si cambiano solo nella configurazione del container. Per passare a un altro database c'è l'esportazione e l'importazione: il manuale dice come.</p>
<h3>Laboratorio</h3>
<form method="post" action="/azioni/impostazioni/@LaboratorySettings.Workers.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#sistema" />
<label for="lab-workers">@LaboratorySettings.Workers.Label</label>
<input id="lab-workers" name="valore" inputmode="numeric" autocomplete="off" value="@_labWorkers.Value" readonly="@(_labWorkers.ReadOnly || Shell.IsDemo)" />
<button class="btn btn-small" type="submit">Salva</button>
</form>
<p class="hint">Quante prove del Laboratorio girano insieme. Alzalo solo dopo averne misurato l'effetto: il Laboratorio non deve togliere tempo al trading. Vale dalla prossima prova. Su questo computer va da 1 a @LaboratorySettings.MaxWorkers.</p>
<h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
@@ -722,6 +733,7 @@
private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
private SettingValue _labWorkers = new(LaboratorySettings.Workers.Key, LaboratorySettings.Workers.Default, false, null);
private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft;
private string? _draftUri;
@@ -784,6 +796,7 @@
_telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
_heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
_telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
_labWorkers = await services.Settings.GetAsync(LaboratorySettings.Workers.Key, ct);
_queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
@@ -818,6 +831,7 @@
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
"impostazione" => "Questa impostazione non si può cambiare così.",
"operai" => $"Gli operai del Laboratorio sono un numero intero da 1 a {LaboratorySettings.MaxWorkers}.",
"riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».",
"bot" => "Comando non ammesso nello stato attuale del bot.",
"motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.",
+6 -1
View File
@@ -274,7 +274,7 @@ internal static partial class Forms
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
var rules = key == Anubis.News.ExternalRules.Setting.Key;
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key &&
!news && !model && !rules)
key != Anubis.Backtest.LaboratorySettings.Workers.Key && !news && !model && !rules)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
@@ -324,6 +324,11 @@ internal static partial class Forms
return Results.Redirect(With(back, "errore", refusal));
}
if (key == Anubis.Backtest.LaboratorySettings.Workers.Key && Anubis.Backtest.LaboratorySettings.Workers.Check!(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "operai"));
}
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "riunioni"));
+69 -59
View File
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Channels;
using Anubis.Core;
@@ -41,9 +42,11 @@ public static class TrialRequestErrors
}
/// <summary>
/// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time on a
/// dedicated thread with low priority, so trading and the interface never wait for a backtest, and writes the report
/// back. Only the asynchronous side touches the database. After a restart, trials left halfway start again.
/// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time, and writes
/// the report back. The engine executions of a trial (its units) run on a pool of low-priority threads, one by default
/// (<see cref="LaboratorySettings.Workers"/>, read at the start of every trial), so trading and the interface never wait for a
/// backtest. Each unit is recorded in the database when it is done: after a restart a trial left halfway starts again and
/// runs only the units it had not finished. Only the asynchronous side touches the database.
/// </summary>
public sealed partial class Laboratory : IDisposable
{
@@ -60,19 +63,32 @@ public sealed partial class Laboratory : IDisposable
private readonly ILogger _logger;
private readonly Channel<Guid> _queue = Channel.CreateUnbounded<Guid>(new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary<Guid, string> _progress = new();
private readonly LowPriorityWorker _worker = new("anubis-laboratory");
private readonly Func<CancellationToken, Task<int>> _workers;
private readonly Lock _poolGate = new();
private LowPriorityPool _pool = new(PoolName, 1);
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null)
/// <param name="workers">How many threads the next trial gets (<see cref="LaboratorySettings.WorkersAsync"/>); one when null.</param>
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null, Func<CancellationToken, Task<int>>? workers = null)
{
_db = db;
_clock = clock;
_researchRoot = researchRoot;
_logger = logger ?? NullLogger.Instance;
_workers = workers ?? (_ => Task.FromResult(1));
Trials = new TrialStore(db, clock);
Units = new TrialUnitStore(db, clock);
}
private const string PoolName = "anubis-laboratory";
public TrialStore Trials { get; }
/// <summary>The units of the trials: one row per engine execution.</summary>
public TrialUnitStore Units { get; }
/// <summary>The engine of a trial: the daily one. Tests put one in between to count or stop the executions.</summary>
internal Func<TrialPlan, IStrategyFamily, BacktestDataset, ITrialEngine> EngineFor { get; set; } = (plan, family, data) => new DailyTrialEngine(plan, family, data);
/// <summary>Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did.</summary>
public Func<CancellationToken, Task>? ReviewTrialEnded { get; set; }
@@ -86,8 +102,35 @@ public sealed partial class Laboratory : IDisposable
}
}
/// <summary>Heavy work on the thread of the trials.</summary>
public Task<T> ComputeAsync<T>(Func<T> work) => _worker.RunAsync(work);
/// <summary>Heavy work on the threads of the trials.</summary>
public Task<T> ComputeAsync<T>(Func<T> work)
{
lock (_poolGate)
{
return _pool.RunAsync(work);
}
}
/// <summary>The pool with <paramref name="workers"/> threads: the one in use, or a new one when the number changed.</summary>
private LowPriorityPool PoolOf(int workers)
{
LowPriorityPool? old = null;
LowPriorityPool pool;
lock (_poolGate)
{
if (_pool.Workers != workers)
{
old = _pool;
_pool = new LowPriorityPool(PoolName, workers);
}
pool = _pool;
}
// The old threads finish what they were given (heavy work of a review, at most) and stop.
old?.Dispose();
return pool;
}
/// <summary>What the running trial is doing, in words; null when it is not running here.</summary>
public string? Progress(Guid id) => _progress.GetValueOrDefault(id);
@@ -236,7 +279,10 @@ public sealed partial class Laboratory : IDisposable
}
}
/// <summary>One trial: load its data, compute on the worker thread, write the report. A failure is recorded, not thrown.</summary>
/// <summary>
/// One trial: load its data, run its units on the pool (those done before a restart come back from the database), judge on
/// the pool, write the report. A failure is recorded, not thrown.
/// </summary>
public async Task ProcessAsync(Guid id, CancellationToken cancellationToken)
{
if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false))
@@ -263,8 +309,17 @@ public sealed partial class Laboratory : IDisposable
var data = await LoadAsync(_db, _clock, _researchRoot, trial.Plan.Data, cancellationToken).ConfigureAwait(false);
var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false);
var now = _clock.UtcNow;
var (report, summary) = await _worker.RunAsync(
() => TrialRunner.Run(id, trial.Plan, trial.PlanHash, family, data, prior, now, text => _progress[id] = text, cancellationToken)).ConfigureAwait(false);
var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false)));
var done = await Units.ResumeAsync(id, cancellationToken).ConfigureAwait(false);
var engine = EngineFor(trial.Plan, family, data);
var watch = Stopwatch.StartNew();
var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, null, done), text => _progress[id] = text,
cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
_progress[id] = "convalide";
var elapsed = watch.Elapsed;
var (report, summary) = await pool.RunAsync(
() => TrialRunner.Judge(id, trial.Plan, trial.PlanHash, family, engine, runs, prior, now, elapsed)).ConfigureAwait(false);
await Trials.FinishAsync(id, report.DataFingerprint, summary, report.ToJson(), report.Passed, cancellationToken).ConfigureAwait(false);
LogFinished(_logger, id, trial.Strategy, report.Passed);
}
@@ -379,7 +434,10 @@ public sealed partial class Laboratory : IDisposable
public void Dispose()
{
_queue.Writer.TryComplete();
_worker.Dispose();
lock (_poolGate)
{
_pool.Dispose();
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")]
@@ -391,51 +449,3 @@ public sealed partial class Laboratory : IDisposable
[LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")]
private static partial void LogFailed(ILogger logger, Guid id, Exception exception);
}
/// <summary>
/// One thread with low priority that runs heavy work in order. Its callers await the result on their own side: the
/// thread never touches the database.
/// </summary>
internal sealed class LowPriorityWorker : IDisposable
{
private readonly BlockingCollection<Action> _work = [];
private readonly Thread _thread;
public LowPriorityWorker(string name)
{
_thread = new Thread(Loop) { IsBackground = true, Name = name, Priority = ThreadPriority.BelowNormal };
_thread.Start();
}
public Task<T> RunAsync<T>(Func<T> work)
{
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
public void Dispose()
{
_work.CompleteAdding();
_thread.Join(TimeSpan.FromSeconds(10));
_work.Dispose();
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Globalization;
using Anubis.Core;
namespace Anubis.Backtest;
/// <summary>
/// The settings of the laboratory (Phase 13): how many threads run the units of a trial together. One by default; at most
/// one less than the processors, so trading always has one, and never fewer than one (a container with a single processor).
/// </summary>
public static class LaboratorySettings
{
public static readonly SettingDefinition Workers = new("laboratory.workers", "Operai del Laboratorio", "1", Check: Whole);
public static readonly IReadOnlyList<SettingDefinition> All = [Workers];
/// <summary>The most threads this computer allows, read when asked: the processors can change with the container.</summary>
public static int MaxWorkers => Math.Max(1, Environment.ProcessorCount - 1);
/// <summary>The threads for the next trial: the saved value, kept within the bounds of this computer.</summary>
public static async Task<int> WorkersAsync(SettingsStore settings, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(settings);
var value = (await settings.GetAsync(Workers.Key, cancellationToken).ConfigureAwait(false)).Value;
return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var workers) ? Math.Clamp(workers, 1, MaxWorkers) : 1;
}
private static string? Whole(string text)
{
var max = MaxWorkers;
return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= 1 && value <= max
? null
: $"Serve un numero intero tra 1 e {max}.";
}
}
+86
View File
@@ -0,0 +1,86 @@
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Anubis.Backtest;
/// <summary>
/// A few background threads with low priority (<c>name-1</c> … <c>name-N</c>) that take heavy work in the order it arrives:
/// with one thread the work runs in that order. Callers await the result on their own side: the threads never touch the
/// database. On Linux the priority is mostly ignored by the scheduler, so what keeps the laboratory light there is the number
/// of threads.
/// </summary>
internal sealed class LowPriorityPool : IDisposable
{
private static readonly TimeSpan JoinWait = TimeSpan.FromSeconds(10);
private readonly BlockingCollection<Action> _work = [];
private readonly Thread[] _threads;
private int _disposed;
public LowPriorityPool(string name, int workers)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentOutOfRangeException.ThrowIfLessThan(workers, 1);
_threads = new Thread[workers];
for (var i = 0; i < workers; i++)
{
_threads[i] = new Thread(Loop) { IsBackground = true, Name = $"{name}-{i + 1}", Priority = ThreadPriority.BelowNormal };
_threads[i].Start();
}
}
/// <summary>How many threads take work.</summary>
public int Workers => _threads.Length;
public Task<T> RunAsync<T>(Func<T> work)
{
ArgumentNullException.ThrowIfNull(work);
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
/// <summary>
/// Takes no more work and lets the threads finish what was handed over, waiting for them a while. The queue is released only
/// when every thread has left it: a thread still busy with a long piece of work must not find it gone.
/// </summary>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_work.CompleteAdding();
var watch = Stopwatch.StartNew();
var stopped = true;
foreach (var thread in _threads)
{
var left = JoinWait - watch.Elapsed;
stopped &= thread.Join(left > TimeSpan.Zero ? left : TimeSpan.Zero);
}
if (stopped)
{
_work.Dispose();
}
}
}
+135 -41
View File
@@ -107,11 +107,14 @@ public sealed record BacktestReport(
}
/// <summary>
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan
/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice,
/// the overfitting and the number of tries. The engine that runs the variants is an <see cref="ITrialEngine"/>: the daily one
/// Runs a trial from its plan, on data already loaded (pure computation, no database), in two steps. <see cref="Variants"/>
/// does every engine execution, each one a unit with its own key (<see cref="TrialUnitKey"/>): every variant of the grid on
/// the whole period, the variant in use when the grid does not have it, then, once the plateau rule has chosen, the chosen
/// (or judged) variant with doubled and tripled costs, the benchmark and the look-ahead check. <see cref="Judge"/> then
/// computes the validations, the checks and the report from those runs alone, assembled by key: the same report whether the
/// units ran in order on one thread, on several threads (<see cref="VariantsAsync"/>) or came back from the database after
/// a restart. A plan that names the variant to judge has the figures, the checks and the curve of that one: the grid still
/// gives the choice, the overfitting and the number of tries. The engine is an <see cref="ITrialEngine"/>: the daily one
/// (<see cref="DailyTrialEngine"/>) unless the caller gives another.
/// </summary>
public static class TrialRunner
@@ -132,7 +135,7 @@ public static class TrialRunner
return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken);
}
/// <summary>A trial of any family on any engine: the same validations, checks and report whatever the engine.</summary>
/// <summary>A trial of any family on any engine: <see cref="Judge"/> of <see cref="Variants"/>, on the caller's thread.</summary>
public static (BacktestReport Report, TrialSummary Summary) Run(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now,
Action<string>? progress = null, CancellationToken cancellationToken = default)
@@ -142,57 +145,125 @@ public static class TrialRunner
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
}
var runs = Variants(plan, family, engine, progress, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
return Judge(trialId, plan, planHash, family, engine, runs, prior, now, watch.Elapsed);
}
var variants = ParameterGrid.Of(family, plan.Grid);
if (variants.Count == 0)
{
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
var runs = new BacktestRun[variants.Count];
for (var i = 0; i < variants.Count; i++)
/// <summary>
/// Every engine execution of a trial, one after the other on the caller's thread, in the order the engine has always been
/// called: the grid, the variant in use outside it, the costed runs, the benchmark, the look-ahead check.
/// </summary>
public static TrialRuns Variants(TrialPlan plan, IResearchFamily family, ITrialEngine engine, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
var stages = new TrialStages(plan, family, engine);
var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
foreach (var key in stages.First)
{
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke($"variante {i + 1} di {variants.Count}");
runs[i] = engine.Run(variants[i].Parameters);
progress?.Invoke(key.Kind == TrialUnitKind.Variant ? $"variante {key.Index + 1} di {stages.Grid.Count}" : "variante in uso");
results[key.Text] = stages.Execute(key);
}
var returns = runs.Select(r => r.DailyReturns()).ToArray();
var said = false;
foreach (var key in stages.Second(results))
{
cancellationToken.ThrowIfCancellationRequested();
if (key.Kind == TrialUnitKind.LookAhead)
{
progress?.Invoke("test anti sguardo in avanti");
}
else if (!said)
{
progress?.Invoke("costi doppi e tripli, comprare e tenere");
said = true;
}
results[key.Text] = stages.Execute(key);
}
return stages.Assemble(results);
}
/// <summary>
/// The same executions handed to <paramref name="units"/> one stage at a time (a pool of threads, a store of finished
/// units): the grid and the variant in use first, the rest once the plateau rule has chosen. The results are assembled by
/// key, never in the order they finish, so the runs are those of <see cref="Variants"/>.
/// </summary>
public static async Task<TrialRuns> VariantsAsync(
TrialPlan plan, IResearchFamily family, ITrialEngine engine, ITrialUnits units, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(units);
var stages = new TrialStages(plan, family, engine);
var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
var total = stages.First.Count + stages.SecondCount;
var finished = 0;
TrialUnitResult Execute(TrialUnitKey key)
{
cancellationToken.ThrowIfCancellationRequested();
var result = stages.Execute(key);
progress?.Invoke($"passo {Interlocked.Increment(ref finished)} di {total}");
return result;
}
foreach (var result in await units.RunAsync(stages.First, Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
Interlocked.Exchange(ref finished, results.Count);
foreach (var result in await units.RunAsync(stages.Second(results), Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
return stages.Assemble(results);
}
/// <summary>
/// The judge of a trial on runs already done: the plateau choice, the validations, the checks and the report. Pure: the
/// engine gives only its facts (sessions, currency, year, fingerprint, instruments, limitations) and what it expects of
/// the judged run. <paramref name="elapsed"/> is the time the runs took; the report adds the time of the judge.
/// </summary>
public static (BacktestReport Report, TrialSummary Summary) Judge(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, TrialRuns runs, PriorTrials prior, DateTimeOffset now, TimeSpan elapsed)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(runs);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = engine.Sessions;
var variants = runs.Variants;
if (runs.Grid.Count != variants.Count)
{
throw new InvalidOperationException("Every variant of the grid needs its run.");
}
var returns = runs.Grid.Select(r => r.DailyReturns()).ToArray();
var sharpes = returns.Select(r => Moments.Of(r).Sharpe).ToArray();
var scores = Validation.PlateauScores(variants, sharpes);
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var (chosenIndex, judged, judgedIndex) = Choose(plan, family, variants, sharpes);
var chosen = variants[chosenIndex];
var judged = plan.Judged is null ? chosen.Parameters : StrategyParameters.Of(family, plan.Judged);
var judgedIndex = plan.Judged is null ? chosenIndex : variants.ToList().FindIndex(x => x.ToString() == judged.ToString());
if (judgedIndex < 0)
{
progress?.Invoke("variante in uso");
}
var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex];
var run = judgedIndex < 0 ? runs.OutsideGrid ?? throw new InvalidOperationException("The variant in use outside the grid has no run.") : runs.Grid[judgedIndex];
var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var year = engine.PeriodsPerYear;
var metrics = BacktestMetrics.Of(run, year);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List<ReportCosts>();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{
var costed = multiplier == 1m ? run : engine.Run(judged, multiplier);
var costed = multiplier == 1m ? run : runs.Costed[multiplier];
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
}
var benchmarkRun = engine.Benchmark();
var benchmarkRun = runs.Benchmark;
var benchmark = BacktestMetrics.Of(benchmarkRun, year);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
var days = run.Equity.Select(p => p.Day).ToArray();
DateOnly DayOf(int returnIndex) => days[Math.Clamp(returnIndex + 1, 0, days.Length - 1)];
var v = plan.Validation;
@@ -212,8 +283,7 @@ public static class TrialRunner
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti");
var look = engine.LookAhead(judged, v.LookAheadCuts);
var look = runs.LookAhead;
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -253,8 +323,8 @@ public static class TrialRunner
metrics,
benchmark,
costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs.Grid[i].NetResult,
BacktestMetrics.Of(runs.Grid[i], year).MaxDrawdown, runs.Grid[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
.. judgedIndex >= 0 ? Array.Empty<ReportVariant>()
: [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward,
@@ -271,20 +341,44 @@ public static class TrialRunner
[.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now,
watch.Elapsed.TotalSeconds)
0)
{
Judged = plan.Judged is null ? null : judged.ToString(),
Baskets = run.Baskets.Count == 0 ? null
: [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))],
};
var expected = engine.Expected(run, judgedReturns);
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 };
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5, Seconds = (elapsed + watch.Elapsed).TotalSeconds };
var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes);
return (report, summary);
}
/// <summary>
/// The plateau choice and the variant judged: the chosen one, or the one the plan names, with its place in the grid (-1
/// when the grid does not have it). The same rule for both stages of the runs and for the judge.
/// </summary>
internal static (int ChosenIndex, StrategyParameters Judged, int JudgedIndex) Choose(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants, IReadOnlyList<double> sharpes)
{
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var chosen = variants[chosenIndex];
var (named, namedIndex) = Named(plan, family, variants);
return named is null ? (chosenIndex, chosen.Parameters, chosenIndex) : (chosenIndex, named, namedIndex);
}
/// <summary>The variant the plan names, with its place in the grid (-1 when the grid does not have it); null when it names none.</summary>
internal static (StrategyParameters? Judged, int Index) Named(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants)
{
if (plan.Judged is null)
{
return (null, -1);
}
var judged = StrategyParameters.Of(family, plan.Judged);
return (judged, variants.ToList().FindIndex(x => x.ToString() == judged.ToString()));
}
/// <summary>What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it).</summary>
public static IReadOnlyList<string> Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data)
{
+4 -2
View File
@@ -14,8 +14,10 @@ public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList<double
/// <summary>
/// What the trial judge (<see cref="TrialRunner"/>) asks of an engine, so the same judge, with the same validations and the
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in
/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check.
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset. Each execution is a unit
/// (<see cref="TrialUnitKey"/>); on one thread they come in a fixed order: every variant, the judged one outside the grid,
/// the costed runs, the benchmark, the look-ahead check. The laboratory may run several at once on its pool, so an engine
/// must not keep state between runs.
/// </summary>
public interface ITrialEngine
{
+392
View File
@@ -0,0 +1,392 @@
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>What one engine execution of a trial is (<see cref="TrialUnitKey"/>).</summary>
public enum TrialUnitKind
{
/// <summary>A variant of the grid at plain costs.</summary>
Variant,
/// <summary>The variant in use when the grid does not have it (<see cref="TrialPlan.Judged"/>).</summary>
OutsideGrid,
/// <summary>The judged variant with costs multiplied.</summary>
Costed,
/// <summary>The term of comparison of the engine.</summary>
Benchmark,
/// <summary>The look-ahead check of the judged variant.</summary>
LookAhead,
}
/// <summary>
/// The identity of one engine execution of a trial: its kind, its place among the units of that kind (the grid index for a
/// variant, 0 otherwise), its parameters and its cost multiplier. <see cref="Text"/> is the invariant key the database keeps
/// (<c>variant:3:a=1;kind=0:x1</c>).
/// </summary>
public sealed record TrialUnitKey(TrialUnitKind Kind, int Index, string Parameters, decimal CostMultiplier)
{
/// <summary>The kind in snake case, as the database keeps it (<c>outside_grid</c>).</summary>
public string KindText => JsonNamingPolicy.SnakeCaseLower.ConvertName(Kind.ToString());
public string Text => string.Create(CultureInfo.InvariantCulture,
$"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}");
}
/// <summary>The outcome of one unit: a run, or the result of the look-ahead check.</summary>
public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead);
/// <summary>
/// Every engine execution a trial needs, done: what <see cref="TrialRunner.Judge"/> reads. <see cref="Grid"/> is in the order
/// of <see cref="Variants"/>; <see cref="Costed"/> holds the multipliers other than 1.
/// </summary>
public sealed record TrialRuns(
IReadOnlyList<Variant> Variants,
IReadOnlyList<BacktestRun> Grid,
BacktestRun? OutsideGrid,
IReadOnlyDictionary<decimal, BacktestRun> Costed,
BacktestRun Benchmark,
LookAheadResult LookAhead);
/// <summary>
/// Where the units of a stage run: on the caller's thread, on a pool of threads, or on a pool that keeps finished units in the
/// database. The results come back in the order of <paramref name="keys"/>, whatever the order they finished in.
/// </summary>
public interface ITrialUnits
{
Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken);
}
/// <summary>Units one after the other on the caller's thread: the task it returns is already finished.</summary>
public sealed class InlineTrialUnits : ITrialUnits
{
public static InlineTrialUnits Instance { get; } = new();
public Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var results = new List<TrialUnitResult>(keys.Count);
foreach (var key in keys)
{
cancellationToken.ThrowIfCancellationRequested();
results.Add(execute(key));
}
return Task.FromResult<IReadOnlyList<TrialUnitResult>>(results);
}
}
/// <summary>
/// Units on a pool of low-priority threads, handed over in order: with one thread they run in the order of the keys. After a
/// unit fails, the ones not yet started are skipped.
/// </summary>
internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
using var failed = new CancellationTokenSource();
var tasks = keys.Select(key => pool.RunAsync(() => Guarded(key, execute, failed))).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>Runs a unit unless another one has failed; a failure stops the units not yet started.</summary>
internal static TrialUnitResult Guarded(TrialUnitKey key, Func<TrialUnitKey, TrialUnitResult> execute, CancellationTokenSource failed)
{
failed.Token.ThrowIfCancellationRequested();
try
{
return execute(key);
}
catch
{
failed.Cancel();
throw;
}
}
}
/// <summary>
/// Units on a pool that records each one in <c>tournament_units</c>: a claim before it runs, its outcome once done. The units
/// already done (<paramref name="done"/>, from <see cref="TrialUnitStore.ResumeAsync"/>) come back from their outcome and do
/// not run again.
/// </summary>
internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary<string, byte[]> done) : ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var missing = keys.Where(k => !done.ContainsKey(k.Text)).ToList();
if (missing.Count > 0)
{
await store.ClaimAsync(trialId, tournamentId, missing, cancellationToken).ConfigureAwait(false);
}
using var failed = new CancellationTokenSource();
async Task<TrialUnitResult> OneAsync(TrialUnitKey key)
{
var (result, outcome, seconds) = await pool.RunAsync(() =>
{
var watch = Stopwatch.StartNew();
var unit = PooledTrialUnits.Guarded(key, execute, failed);
return (unit, TrialUnitOutcomes.Encode(unit), watch.Elapsed.TotalSeconds);
}).ConfigureAwait(false);
await store.DoneAsync(trialId, key, outcome, seconds, cancellationToken).ConfigureAwait(false);
return result;
}
var tasks = keys.Select(key => done.TryGetValue(key.Text, out var outcome) ? Task.FromResult(TrialUnitOutcomes.Decode(key, outcome)) : OneAsync(key)).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
/// <summary>
/// The two stages of the units of a trial. The first: every variant of the grid in grid order, then the variant in use when
/// the grid does not have it. The second, once the plateau rule has chosen on the first: the costed runs of the judged
/// variant (multipliers other than 1, in increasing order), the benchmark, the look-ahead check. Parameters always come
/// from the grid or from the plan, never from the text of a key.
/// </summary>
internal sealed class TrialStages
{
private readonly TrialPlan _plan;
private readonly IResearchFamily _family;
private readonly ITrialEngine _engine;
private readonly StrategyParameters? _named;
private readonly IReadOnlyList<decimal> _multipliers;
private StrategyParameters? _judged;
private IReadOnlyList<TrialUnitKey>? _second;
public TrialStages(TrialPlan plan, IResearchFamily family, ITrialEngine engine)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
_plan = plan;
_family = family;
_engine = engine;
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
}
Grid = ParameterGrid.Of(family, plan.Grid);
if (Grid.Count == 0)
{
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
var (named, namedIndex) = TrialRunner.Named(plan, family, Grid);
_named = namedIndex < 0 ? named : null;
_multipliers = [.. plan.CostMultipliers.Distinct().Order().Where(m => m != 1m)];
First =
[
.. Grid.Select((v, i) => new TrialUnitKey(TrialUnitKind.Variant, i, v.ToString(), 1m)),
.. _named is null ? Array.Empty<TrialUnitKey>() : [new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, _named.ToString(), 1m)],
];
}
public IReadOnlyList<Variant> Grid { get; }
public IReadOnlyList<TrialUnitKey> First { get; }
/// <summary>How many units the second stage has: it does not depend on the choice.</summary>
public int SecondCount => _multipliers.Count + 2;
private StrategyParameters Judged => _judged ?? throw new InvalidOperationException("The second stage needs the choice of the first.");
/// <summary>The plateau choice on the runs of the first stage, and the keys of the second.</summary>
public IReadOnlyList<TrialUnitKey> Second(IReadOnlyDictionary<string, TrialUnitResult> first)
{
ArgumentNullException.ThrowIfNull(first);
var sharpes = First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => Moments.Of(RunOf(first, k).DailyReturns()).Sharpe).ToArray();
_judged = TrialRunner.Choose(_plan, _family, Grid, sharpes).Judged;
var judged = _judged.ToString();
_second =
[
.. _multipliers.Select(m => new TrialUnitKey(TrialUnitKind.Costed, 0, judged, m)),
new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m),
new TrialUnitKey(TrialUnitKind.LookAhead, 0, judged, 1m),
];
return _second;
}
/// <summary>One engine execution.</summary>
public TrialUnitResult Execute(TrialUnitKey key)
{
ArgumentNullException.ThrowIfNull(key);
return key.Kind switch
{
TrialUnitKind.Variant => new TrialUnitResult(key, _engine.Run(VariantOf(key).Parameters), null),
TrialUnitKind.OutsideGrid => new TrialUnitResult(key, _engine.Run(_named ?? throw new InvalidOperationException("The judged variant is in the grid.")), null),
TrialUnitKind.Costed => new TrialUnitResult(key, _engine.Run(Judged, key.CostMultiplier), null),
TrialUnitKind.Benchmark => new TrialUnitResult(key, _engine.Benchmark(), null),
TrialUnitKind.LookAhead => new TrialUnitResult(key, null, _engine.LookAhead(Judged, _plan.Validation.LookAheadCuts)),
_ => throw new ArgumentOutOfRangeException(nameof(key), key.Kind, "Not a unit of a trial."),
};
}
/// <summary>The runs of both stages, by key.</summary>
public TrialRuns Assemble(IReadOnlyDictionary<string, TrialUnitResult> results)
{
ArgumentNullException.ThrowIfNull(results);
var second = _second ?? throw new InvalidOperationException("The second stage was not planned.");
var outside = First.FirstOrDefault(k => k.Kind == TrialUnitKind.OutsideGrid);
return new TrialRuns(
Grid,
[.. First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => RunOf(results, k))],
outside is null ? null : RunOf(results, outside),
second.Where(k => k.Kind == TrialUnitKind.Costed).ToDictionary(k => k.CostMultiplier, k => RunOf(results, k)),
RunOf(results, second.Single(k => k.Kind == TrialUnitKind.Benchmark)),
ResultOf(results, second.Single(k => k.Kind == TrialUnitKind.LookAhead)).LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."));
}
private Variant VariantOf(TrialUnitKey key)
{
var variant = Grid[key.Index];
return variant.ToString() == key.Parameters ? variant : throw new InvalidOperationException("The key " + key.Text + " is not the variant " + variant + ".");
}
private static TrialUnitResult ResultOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
results.TryGetValue(key.Text, out var result) ? result : throw new InvalidOperationException("The unit " + key.Text + " has no result.");
private static BacktestRun RunOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
ResultOf(results, key).Run ?? throw new InvalidOperationException("The unit " + key.Text + " has no run.");
}
/// <summary>
/// The outcome of a unit as the database keeps it: the gzip of its JSON, with the options of the plans (decimals keep their
/// scale, doubles their exact value). A run is kept without its decisions, which only the look-ahead check reads; the order
/// of fills, trades and notes is kept, so a run read back gives the same report byte for byte.
/// </summary>
internal static class TrialUnitOutcomes
{
private sealed record StoredRun(
string Currency,
decimal InitialCapital,
IReadOnlyList<EquityPoint> Equity,
IReadOnlyList<BacktestFill> Fills,
IReadOnlyList<BacktestTrade> Trades,
IReadOnlyList<BacktestNote> Notes,
decimal Dividends,
decimal WrittenOff,
IReadOnlyList<BacktestBasket> Baskets);
public static byte[] Encode(TrialUnitResult result)
{
ArgumentNullException.ThrowIfNull(result);
var json = result.Key.Kind == TrialUnitKind.LookAhead
? JsonSerializer.SerializeToUtf8Bytes(result.LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."), TrialPlan.Json)
: JsonSerializer.SerializeToUtf8Bytes(Stored(result.Run ?? throw new InvalidOperationException("The unit " + result.Key.Text + " has no run.")), TrialPlan.Json);
using var buffer = new MemoryStream();
using (var zip = new GZipStream(buffer, CompressionLevel.Optimal, leaveOpen: true))
{
zip.Write(json);
}
return buffer.ToArray();
}
public static TrialUnitResult Decode(TrialUnitKey key, byte[] outcome)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(outcome);
using var zip = new GZipStream(new MemoryStream(outcome), CompressionMode.Decompress);
if (key.Kind == TrialUnitKind.LookAhead)
{
return new TrialUnitResult(key, null, JsonSerializer.Deserialize<LookAheadResult>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome"));
}
var run = JsonSerializer.Deserialize<StoredRun>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome");
return new TrialUnitResult(key, new BacktestRun(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, [], run.Notes)
{
Dividends = run.Dividends,
WrittenOff = run.WrittenOff,
Baskets = run.Baskets,
}, null);
}
private static StoredRun Stored(BacktestRun run) =>
new(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, run.Notes, run.Dividends, run.WrittenOff, run.Baskets);
}
/// <summary>States of a row of <c>tournament_units</c>.</summary>
public static class TrialUnitStatuses
{
public const string Running = "running";
public const string Done = "done";
}
/// <summary>A unit as the database keeps it, without its outcome.</summary>
public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId);
/// <summary>
/// The units of the trials in <c>tournament_units</c> (Phase 13): one row per engine execution, claimed before it runs and
/// done with its outcome, so a trial stopped halfway runs again only what it had not finished. A plain trial drops its
/// outcomes when it ends (<see cref="TrialStore.FinishAsync"/>, <see cref="TrialStore.FailAsync"/>); a unit never counts as a
/// trial.
/// </summary>
public sealed class TrialUnitStore(Database db, IClock clock)
{
/// <summary>
/// A trial that starts, or starts again after a restart: the units left running (their work was lost with the process) and
/// those without an outcome are dropped; the outcomes of the units done are returned by key.
/// </summary>
public async Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, CancellationToken cancellationToken)
{
var rows = await db.WriteAsync(async s =>
{
await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND (status <> @d OR outcome IS NULL)", cancellationToken,
("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
return await s.QueryAsync("SELECT unit_key, outcome FROM tournament_units WHERE trial_id = @t AND status = @d",
r => (Key: r.Text("unit_key"), Outcome: r.Bytes("outcome")), ("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal);
}
/// <summary>Claims the units about to run, in one transaction. A unit already claimed stays as it is.</summary>
public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList<TrialUnitKey> keys, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
return db.WriteAsync(async s =>
{
foreach (var key in keys)
{
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @now) " +
"ON CONFLICT (trial_id, unit_key) DO NOTHING",
cancellationToken, ("id", Ids.NewId(clock)), ("t", trialId), ("tour", tournamentId), ("k", key.Text), ("kind", key.KindText),
("r", TrialUnitStatuses.Running), ("now", clock.UtcNow)).ConfigureAwait(false);
}
}, cancellationToken);
}
/// <summary>A unit done: its outcome and the seconds it took.</summary>
public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(key);
return db.WriteAsync(s => s.ExecuteAsync(
"UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r",
cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text),
("r", TrialUnitStatuses.Running)), cancellationToken);
}
/// <summary>The units of a trial, in the order they were claimed.</summary>
public async Task<IReadOnlyList<TrialUnitRow>> ListAsync(Guid trialId, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT unit_key, kind, status, outcome, seconds, tournament_id FROM tournament_units WHERE trial_id = @t ORDER BY id",
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"),
r.IdOrNull("tournament_id")),
("t", trialId)), cancellationToken).ConfigureAwait(false);
}
+25 -10
View File
@@ -226,21 +226,36 @@ public sealed class TrialStore(Database db, IClock clock)
await db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @r, started_at = @now WHERE id = @id AND status = @p",
cancellationToken, ("r", TrialStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned)), cancellationToken).ConfigureAwait(false) == 1;
/// <summary>A trial done, with its report. A trial outside a tournament drops the outcomes of its units: the rows stay as a record.</summary>
public Task FinishAsync(Guid id, string fingerprint, TrialSummary summary, string reportJson, bool passed, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync(
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r",
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint),
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)), cancellationToken);
db.WriteAsync(async s =>
{
await s.ExecuteAsync(
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r",
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint),
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>A trial failed, with the reason. A trial outside a tournament drops the outcomes of its units, as when it is done.</summary>
public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)",
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned),
("r", TrialStatuses.Running)), cancellationToken);
db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)",
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
// The units of a tournament keep their outcome until the tournament ends: it judges them again.
private static Task<int> ReleaseUnitsAsync(DbSession s, Guid id, CancellationToken cancellationToken) =>
s.ExecuteAsync("UPDATE tournament_units SET outcome = NULL WHERE trial_id = @id AND tournament_id IS NULL AND outcome IS NOT NULL", cancellationToken, ("id", id));
/// <summary>
/// After a restart: trials left running go back to planned (their work was lost with the process), and every planned
/// trial is returned oldest first, to run again from the start with the same plan.
/// After a restart: trials left running go back to planned, and every planned trial is returned oldest first, to run again
/// with the same plan. The units they had finished are kept (<see cref="TrialUnitStore.ResumeAsync"/>): only the rest runs
/// again.
/// </summary>
public async Task<IReadOnlyList<Guid>> ResumeAsync(CancellationToken cancellationToken) =>
await db.WriteAsync(async s =>
+1 -1
View File
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All, .. Backtest.LaboratorySettings.All];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
@@ -0,0 +1,39 @@
-- The tournament of the strategies (ADR 0026): its plan, written before any result and never changed, its state and its
-- verdict. The final tract of the data is opened once: holdout_opened_at and finalists are written together, only once.
CREATE TABLE tournaments (
id {uuid} PRIMARY KEY,
name TEXT NOT NULL,
plan {json} NOT NULL,
plan_hash TEXT NOT NULL,
status TEXT NOT NULL,
verdict TEXT,
finalists {json},
report {json},
error TEXT,
holdout_opened_at {timestamp},
created_at {timestamp} NOT NULL,
started_at {timestamp},
finished_at {timestamp}
){strict};
CREATE INDEX tournaments_status ON tournaments (status);
-- One engine execution of a trial of the laboratory (a variant, a costed run, the benchmark, the look-ahead check), so a
-- trial stopped halfway runs again only what it had not finished. The outcome is the gzip of its JSON; a plain trial
-- (tournament_id NULL) drops it when it ends, the row stays as a record.
CREATE TABLE tournament_units (
id {uuid} PRIMARY KEY,
trial_id {uuid} NOT NULL REFERENCES backtest_trials (id),
tournament_id {uuid} REFERENCES tournaments (id),
unit_key TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL,
outcome {bytes},
seconds {float},
created_at {timestamp} NOT NULL,
finished_at {timestamp},
UNIQUE (trial_id, unit_key)
){strict};
CREATE INDEX tournament_units_trial ON tournament_units (trial_id, status);
-- The tournament a contender trial belongs to. No foreign key: backtest_trials is imported before tournaments.
ALTER TABLE backtest_trials ADD COLUMN tournament_id {uuid};
+15
View File
@@ -35,6 +35,21 @@ public sealed class ArchiveTests
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
// A tournament, one of its trials and a unit with its outcome: JSON, bytes and a measure across engines (Phase 13).
var tournament = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(40));
var trial = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(41));
await s.ExecuteAsync(
"INSERT INTO tournaments (id, name, plan, plan_hash, status, finalists, created_at, started_at) VALUES (@id, 'Campionato', @p, 'abc', 'running', @f, @t, @t)",
("id", tournament), ("p", new DbJson("{\"name\": \"Campionato\", \"cost_multipliers\": [1, 2, 3]}")), ("f", new DbJson("[\"a\", \"b\"]")),
("t", _clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, tournament_id) VALUES (@id, 'sma_cross', '1', @p, 'def', 4, 'running', @t, @tour)",
("id", trial), ("p", new DbJson("{\"strategy\": \"sma_cross\"}")), ("t", _clock.UtcNow), ("tour", tournament)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', @o, @sec, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(42))), ("tr", trial), ("tour", tournament), ("o", new byte[] { 31, 139, 8, 0, 255, 0 }), ("sec", 0.1234567890123),
("t", _clock.UtcNow)).ConfigureAwait(false);
}).ConfigureAwait(false);
}
+410
View File
@@ -0,0 +1,410 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The units of a trial and the pool of the laboratory (Phase 13, issue #122): the judge works on runs already done, assembled
/// by key, so one thread, four threads and units read back from the database give the same report as the golden ones; a trial
/// stopped halfway runs again only what it had not finished.
/// </summary>
[TestClass]
public sealed class TrialUnitTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12");
private static readonly DateOnly Through = new(2026, 12, 31);
private static readonly TrialUnitKey RunKey = new(TrialUnitKind.Variant, 0, "", 1m);
private static readonly TrialUnitKey LookKey = new(TrialUnitKind.LookAhead, 0, "", 1m);
private sealed record Golden(string Name, TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data, PriorTrials Prior)
{
public string Hash => TrialPlan.Hash(Plan.ToJson());
public DailyTrialEngine Engine() => new(Plan, Family, Data);
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task JudgeOfVariantsGivesTheJsonOfRun()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task FourWorkersGiveTheReportOfOne()
{
using var pool = new LowPriorityPool("anubis-test-four", 4);
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = await TrialRunner.VariantsAsync(golden.Plan, golden.Family, engine, new PooledTrialUnits(pool), null, _none).ConfigureAwait(false);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task ARunReloadedFromItsStoredUnitGivesTheSameReport()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
var reloaded = new TrialRuns(
runs.Variants,
[.. runs.Grid.Select(Again)],
runs.OutsideGrid is null ? null : Again(runs.OutsideGrid),
runs.Costed.ToDictionary(c => c.Key, c => Again(c.Value)),
Again(runs.Benchmark),
TrialUnitOutcomes.Decode(LookKey, TrialUnitOutcomes.Encode(new TrialUnitResult(LookKey, null, runs.LookAhead))).LookAhead!);
Assert.IsTrue(reloaded.Grid.All(r => r.Decisions.Count == 0), "The decisions are not kept: only the look-ahead check reads them.");
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, reloaded, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AStoredUnitIsTheSameBytesWhenWrittenAgain()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: Through.AddDays(-399)));
var run = BacktestEngine.Run(new MovingAverageCross(5, 20), data);
var stored = TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null));
var back = TrialUnitOutcomes.Decode(RunKey, stored).Run!;
CollectionAssert.AreEqual(stored, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, back, null)));
Assert.AreEqual(run.Fees, back.Fees);
Assert.AreEqual(run.FinalEquity, back.FinalEquity);
CollectionAssert.AreEqual(run.Fills.ToList(), back.Fills.ToList());
CollectionAssert.AreEqual(run.Trades.ToList(), back.Trades.ToList());
CollectionAssert.AreEqual(run.Notes.ToList(), back.Notes.ToList());
Assert.IsTrue(stored.Length < 200_000, "The outcome is compressed.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheKeyOfAUnitIsTheSameTextInEveryCulture()
{
var before = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
Assert.AreEqual("variant:3:a=1;kind=0:x1", new TrialUnitKey(TrialUnitKind.Variant, 3, "a=1;kind=0", 1m).Text);
Assert.AreEqual("costed:0:a=1;kind=0:x2", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1;kind=0", 2.00m).Text);
Assert.AreEqual("costed:0:a=1:x1.5", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1", 1.50m).Text);
Assert.AreEqual("outside_grid:0:a=4;kind=1:x1", new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, "a=4;kind=1", 1m).Text);
Assert.AreEqual("benchmark:0::x1", new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m).Text);
Assert.AreEqual("look_ahead", new TrialUnitKey(TrialUnitKind.LookAhead, 0, "a=1", 1m).KindText);
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnOneWorkerThePoolCallsTheEngineInTheOrderOfToday()
{
var (plan, family, data) = SmallCross();
var inline = new List<string>();
var sequential = TrialRunner.Variants(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), inline));
using var pool = new LowPriorityPool("anubis-test-one", 1);
var pooled = new List<string>();
var parallel = await TrialRunner.VariantsAsync(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), pooled), new PooledTrialUnits(pool),
null, _none).ConfigureAwait(false);
Assert.HasCount(4 + 2 + 2, inline);
CollectionAssert.AreEqual(inline, pooled);
StringAssert.StartsWith(inline[^1], "look_ahead ");
Assert.AreEqual("benchmark", inline[^2]);
var inlineUnits = await TrialRunner.VariantsAsync(plan, family, new DailyTrialEngine(plan, family, data), InlineTrialUnits.Instance, null, _none).ConfigureAwait(false);
var hash = TrialPlan.Hash(plan.ToJson());
var one = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), sequential, PriorTrials.None, Now, TimeSpan.Zero).Report;
foreach (var other in new[] { parallel, inlineUnits })
{
var report = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), other, PriorTrials.None, Now, TimeSpan.Zero).Report;
Assert.AreEqual((one with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AUnitThatFailsStopsTheOnesNotYetStartedAndItsErrorComesBack()
{
var (plan, family, data) = SmallCross();
using var pool = new LowPriorityPool("anubis-test-fail", 1);
var calls = new List<string>();
var engine = new RecordingEngine(new DailyTrialEngine(plan, family, data), calls, _ => throw new InvalidOperationException("rotto"));
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => TrialRunner.VariantsAsync(plan, family, engine, new PooledTrialUnits(pool), null, _none))
.ConfigureAwait(false);
Assert.AreEqual("rotto", error.Message, "The error of the unit comes back, not the skip of the others.");
Assert.HasCount(1, calls, "After a failure the units still queued do not run.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ThePoolRunsOnNamedLowPriorityBackgroundThreadsAndFinishesWhatItWasGiven()
{
using var pool = new LowPriorityPool("anubis-test-pool", 2);
using var both = new Barrier(2);
(bool Together, string? Name, ThreadPriority Priority, bool Background) Probe() =>
(both.SignalAndWait(TimeSpan.FromSeconds(30)), Thread.CurrentThread.Name, Thread.CurrentThread.Priority, Thread.CurrentThread.IsBackground);
var seen = await Task.WhenAll(pool.RunAsync(Probe), pool.RunAsync(Probe)).ConfigureAwait(false);
Assert.AreEqual(2, pool.Workers);
Assert.IsTrue(seen.All(s => s.Together), "Two threads run two pieces of work at once.");
CollectionAssert.AreEquivalent(new[] { "anubis-test-pool-1", "anubis-test-pool-2" }, seen.Select(s => s.Name).ToArray());
Assert.IsTrue(seen.All(s => s.Priority == ThreadPriority.BelowNormal && s.Background));
await Assert.ThrowsAsync<ArithmeticException>(() => pool.RunAsync<int>(() => throw new ArithmeticException())).ConfigureAwait(false);
// Work handed over before the pool stops still runs; nothing more is taken; stopping twice is harmless.
using var release = new ManualResetEventSlim();
var slow = pool.RunAsync(() => release.Wait(TimeSpan.FromSeconds(30)));
var queued = pool.RunAsync(() => 7);
var stopping = Task.Run(pool.Dispose);
release.Set();
await stopping.ConfigureAwait(false);
Assert.IsTrue(await slow.ConfigureAwait(false));
Assert.AreEqual(7, await queued.ConfigureAwait(false));
Assert.Throws<InvalidOperationException>(() => pool.RunAsync(() => 1));
pool.Dispose();
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AfterAnInterruptionTheFinishedUnitsAreNotRunAgain()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
var workers = 1;
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers));
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TrialStatuses.Running, (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.Status);
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
var finished = rows.Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
var left = rows.Where(r => r.Status == TrialUnitStatuses.Running).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
Assert.IsNotEmpty(left, "The units claimed and not finished stay running.");
Assert.IsTrue(rows.All(r => r.Status != TrialUnitStatuses.Done || (r.HasOutcome && r.Seconds is >= 0)));
Assert.IsTrue(rows.All(r => r.TournamentId is null));
// The next start plans it again and runs only what was not finished, now on two threads.
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
workers = 2;
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total - finished.Count, second);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(second, CallOf(key), "A finished unit does not run again: " + key);
}
foreach (var key in left)
{
CollectionAssert.Contains(second, CallOf(key), "A unit left running runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
Assert.AreEqual(clock.UtcNow, report.ComputedAt);
// A trial outside a tournament keeps its units as a record, without their outcomes.
var after = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, after);
Assert.IsTrue(after.All(r => r.Status == TrialUnitStatuses.Done && !r.HasOutcome));
CollectionAssert.AreEquivalent(new[] { "variant", "costed", "benchmark", "look_ahead" }, after.Select(r => r.Kind).Distinct().ToArray());
Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors()
{
var workers = LaboratorySettings.Workers;
Assert.AreEqual("laboratory.workers", workers.Key);
Assert.AreEqual("1", workers.Default);
Assert.AreEqual("Operai del Laboratorio", workers.Label);
Assert.AreSame(workers, SettingsStore.Definition(workers.Key));
var max = Math.Max(1, Environment.ProcessorCount - 1);
Assert.AreEqual(max, LaboratorySettings.MaxWorkers);
Assert.IsNull(workers.Check!("1"));
Assert.IsNull(workers.Check(max.ToString(CultureInfo.InvariantCulture)));
foreach (var wrong in new[] { "0", (max + 1).ToString(CultureInfo.InvariantCulture), "", "due", "1.5", "-1", "+2", " 2" })
{
Assert.AreEqual($"Serve un numero intero tra 1 e {max}.", workers.Check(wrong), wrong);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWorkersOfTheLaboratoryAreSetInTheSystemSettings()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Operai del Laboratorio");
StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading");
StringAssert.Contains(page, "Vale dalla prossima prova.");
async Task<string> Save(string value)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LaboratorySettings.Workers.Key, ("ritorno", "/impostazioni#sistema"), ("valore", value));
return ServerHarness.Location(answer);
}
var settings = server.Host.Services!.Settings;
Assert.AreEqual("/impostazioni#sistema", await Save("1"));
Assert.AreEqual(1, await LaboratorySettings.WorkersAsync(settings, _none));
StringAssert.Contains(await Save("0"), "errore=operai");
StringAssert.Contains(await Save((LaboratorySettings.MaxWorkers + 1).ToString(CultureInfo.InvariantCulture)), "errore=operai");
StringAssert.Contains(await Save("tanti"), "errore=operai");
Assert.AreEqual("1", (await settings.GetAsync(LaboratorySettings.Workers.Key, _none)).Value);
StringAssert.Contains(await server.TextAsync("/impostazioni?errore=operai#sistema"), "Gli operai del Laboratorio sono un numero intero da 1 a");
}
private static BacktestRun Again(BacktestRun run) => TrialUnitOutcomes.Decode(RunKey, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null))).Run!;
/// <summary>The call of the recording engine a unit key stands for.</summary>
private static string CallOf(string key)
{
var parts = key.Split(':');
return parts[0] switch
{
"benchmark" => "benchmark",
"look_ahead" => $"look_ahead {parts[2]} {TrialValidation.Default.LookAheadCuts}",
_ => $"run {parts[2]} {parts[3]}",
};
}
private static (TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data) SmallCross()
{
var first = new DateOnly(2024, 1, 1);
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: first));
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
first.AddDays(60), first.AddDays(399), 10_000m, grid), Now).Plan;
return (plan, MovingAverageCrossFamily.Instance, data);
}
/// <summary>The inputs of the three golden reports of <see cref="TrialSeamTests"/>, built the same way.</summary>
private static async Task<IReadOnlyList<Golden>> GoldensAsync()
{
var walk = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03));
var cross = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan;
var folder = TempFolder.Create("golden-units");
try
{
var store = new ResearchStore(folder);
var seed = 21u;
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" })
{
var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
(decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList();
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false);
}
var trend = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow,
CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan;
var data = await Laboratory.LoadResearchAsync(folder, trend.Data, _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(StrategyNames.CryptoTrend)!;
return
[
new("sma_cross", cross, MovingAverageCrossFamily.Instance, walk, new PriorTrials(2, 18, [0.4, 0.9, -0.1])),
new("crypto_trend", trend, family, data, PriorTrials.None),
new("crypto_trend_judged", trend with { Judged = "coin_vol=12;max_stop=15" }, family, data, PriorTrials.None),
];
}
finally
{
TempFolder.Delete(folder);
}
}
private static void Same(string name, BacktestReport report) =>
Assert.AreEqual(Fixture.Text(Path.Combine("golden", name + ".report.json")), (report with { Seconds = 0 }).ToJson(), $"The report of {name} changed.");
/// <summary>An engine in between: it records every call (safe from several threads) and may act on the n-th one.</summary>
private sealed class RecordingEngine(ITrialEngine inner, List<string> calls, Action<int>? onCall = null) : ITrialEngine
{
private int _count;
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
Record(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark()
{
Record("benchmark");
return inner.Benchmark();
}
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
Record(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
return inner.LookAhead(parameters, cuts);
}
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
private void Record(string call)
{
lock (calls)
{
calls.Add(call);
}
onCall?.Invoke(Interlocked.Increment(ref _count));
}
}
}