Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8967575d2c | ||
|
|
b564871391 |
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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}.";
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>
|
||||
/// One sign a calendar day, +1 or −1, from <see cref="First"/> on: the same sign for every instrument on the same day. Two
|
||||
/// datasets that must share their signs (the contenders of one tournament) draw them from the same first day and seed.
|
||||
/// </summary>
|
||||
public sealed class DaySigns
|
||||
{
|
||||
private readonly int[] _signs;
|
||||
|
||||
public DaySigns(DateOnly first, IReadOnlyList<int> signs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(signs);
|
||||
if (signs.Any(s => s is not (1 or -1)))
|
||||
{
|
||||
throw new ArgumentException("A sign is +1 or −1.", nameof(signs));
|
||||
}
|
||||
|
||||
First = first;
|
||||
_signs = [.. signs];
|
||||
}
|
||||
|
||||
/// <summary>The day of the first sign.</summary>
|
||||
public DateOnly First { get; }
|
||||
|
||||
/// <summary>How many days have a sign.</summary>
|
||||
public int Count => _signs.Length;
|
||||
|
||||
/// <summary>The day of the last sign (<see cref="First"/> when there is none).</summary>
|
||||
public DateOnly Last => First.AddDays(Math.Max(_signs.Length - 1, 0));
|
||||
|
||||
/// <summary>The sign of <paramref name="day"/>; a day outside the signs is an error, never a default.</summary>
|
||||
public int this[DateOnly day]
|
||||
{
|
||||
get
|
||||
{
|
||||
var at = day.DayNumber - First.DayNumber;
|
||||
if (at < 0 || at >= _signs.Length)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(day), day, "No sign for this day.");
|
||||
}
|
||||
|
||||
return _signs[at];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The signs of every calendar day from <paramref name="first"/> to <paramref name="last"/>, drawn with <see cref="TournamentStatistics.Signs"/>.</summary>
|
||||
public static DaySigns Draw(DateOnly first, DateOnly last, int seed)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(last, first);
|
||||
return new DaySigns(first, TournamentStatistics.Signs(last.DayNumber - first.DayNumber + 1, seed));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The surrogate series of the control against chance (ADR 0026 point 4; appendix G.5 of the research document of
|
||||
/// 2 December 2026): every day the returns of all the instruments change sign together, with probability one half. The
|
||||
/// size of every day, the tails and the correlations between instruments stay; every tendency to revert or to go on is
|
||||
/// lost. The strategy is then run again on the surrogate prices.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>The work is on log returns from the previous close: open, high, low and close of day t, each as l = ln(p / close of
|
||||
/// t − 1). With the sign s of the day, l becomes s·l, or μ + s·(l − μ) when centred, μ being the mean daily log return of
|
||||
/// the instrument's closes over the loaded bars. Centred is for long-only rules: the drift stays, so a rule that only rides
|
||||
/// it does as well on the surrogates as on the real data. When s = −1 the high and the low swap.</para>
|
||||
/// <para>The first bar of each instrument stays as it is, the volume does not change, the value traded follows the close.
|
||||
/// The surrogate covers the whole loaded history, the warm-up included. It is deterministic: no culture, no clock.
|
||||
/// Instruments with corporate actions are refused for now.</para>
|
||||
/// </remarks>
|
||||
public static class Surrogates
|
||||
{
|
||||
/// <summary>The message of the refusal, for the user.</summary>
|
||||
public const string CorporateActionsRefused = "Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.";
|
||||
|
||||
/// <summary>
|
||||
/// The surrogate of a series of log returns: each one times the sign of its position, or, centred, around the mean of
|
||||
/// the series. The absolute value of every return (centred: its distance from the mean) is kept exactly.
|
||||
/// </summary>
|
||||
public static double[] Flip(IReadOnlyList<double> logReturns, IReadOnlyList<int> signs, bool centred)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logReturns);
|
||||
ArgumentNullException.ThrowIfNull(signs);
|
||||
if (signs.Count < logReturns.Count)
|
||||
{
|
||||
throw new ArgumentException("One sign for every return.", nameof(signs));
|
||||
}
|
||||
|
||||
var mean = centred && logReturns.Count > 0 ? logReturns.Average() : 0;
|
||||
var result = new double[logReturns.Count];
|
||||
for (var i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = Flip(logReturns[i], signs[i], centred, mean);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The surrogate of every instrument of <paramref name="data"/>, with signs drawn from <paramref name="seed"/> over its calendar days.</summary>
|
||||
public static BacktestDataset Of(BacktestDataset data, int seed, bool centred)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
var days = data.Instruments.Where(i => i.Bars.Count > 0).ToList();
|
||||
var signs = days.Count == 0
|
||||
? new DaySigns(DateOnly.MinValue, [])
|
||||
: DaySigns.Draw(days.Min(i => i.Bars[0].Day), days.Max(i => i.Bars[^1].Day), seed);
|
||||
return Of(data, signs, centred);
|
||||
}
|
||||
|
||||
/// <summary>The surrogate of every instrument of <paramref name="data"/>, the ones read only as data included, with the given signs.</summary>
|
||||
public static BacktestDataset Of(BacktestDataset data, DaySigns signs, bool centred)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(signs);
|
||||
if (data.Instruments.Any(i => i.Actions.Count > 0))
|
||||
{
|
||||
throw new NotSupportedException(CorporateActionsRefused);
|
||||
}
|
||||
|
||||
return new BacktestDataset(
|
||||
data.Instruments.Select(i => new BacktestInstrument(i.Spec, Bars(i.Bars, signs, centred), [], i.Source)),
|
||||
data.Currency,
|
||||
data.Calendar,
|
||||
data.DataOnly);
|
||||
}
|
||||
|
||||
/// <summary>The surrogate of one instrument's bars, oldest first, one per day.</summary>
|
||||
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<DailyBar> bars, DaySigns signs, bool centred)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
ArgumentNullException.ThrowIfNull(signs);
|
||||
if (bars.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
for (var i = 0; i < bars.Count; i++)
|
||||
{
|
||||
var b = bars[i];
|
||||
if (!(b.Open > 0 && b.High > 0 && b.Low > 0 && b.Close > 0) || !double.IsFinite(b.Open + b.High + b.Low + b.Close))
|
||||
{
|
||||
throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture,
|
||||
$"Il controllo contro il caso vuole prezzi positivi: la barra del {b.Day:yyyy-MM-dd} ne ha uno che non lo è."));
|
||||
}
|
||||
|
||||
if (i > 0 && b.Day <= bars[i - 1].Day)
|
||||
{
|
||||
throw new ArgumentException("The bars must be in order of day, one a day.", nameof(bars));
|
||||
}
|
||||
}
|
||||
|
||||
var mean = 0.0;
|
||||
if (centred && bars.Count > 1)
|
||||
{
|
||||
for (var i = 1; i < bars.Count; i++)
|
||||
{
|
||||
mean += Math.Log(bars[i].Close / bars[i - 1].Close);
|
||||
}
|
||||
|
||||
mean /= bars.Count - 1;
|
||||
}
|
||||
|
||||
var result = new List<DailyBar>(bars.Count) { bars[0] };
|
||||
var previous = bars[0].Close;
|
||||
var made = bars[0].Close;
|
||||
for (var i = 1; i < bars.Count; i++)
|
||||
{
|
||||
var bar = bars[i];
|
||||
var s = signs[bar.Day];
|
||||
double Price(double p) => made * Math.Exp(Flip(Math.Log(p / previous), s, centred, mean));
|
||||
var open = Price(bar.Open);
|
||||
var close = Price(bar.Close);
|
||||
var (high, low) = s > 0 ? (Price(bar.High), Price(bar.Low)) : (Price(bar.Low), Price(bar.High));
|
||||
high = Math.Max(high, Math.Max(open, close));
|
||||
low = Math.Min(low, Math.Min(open, close));
|
||||
result.Add(bar with
|
||||
{
|
||||
Open = open,
|
||||
High = high,
|
||||
Low = low,
|
||||
Close = close,
|
||||
QuoteVolume = bar.QuoteVolume is { } value ? value * (close / bar.Close) : null,
|
||||
Adjusted = null,
|
||||
});
|
||||
previous = bar.Close;
|
||||
made = close;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static double Flip(double l, int sign, bool centred, double mean) =>
|
||||
centred ? mean + (sign * (l - mean)) : sign * l;
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>The returns of several series on one calendar: <see cref="Returns"/>[k][d] is the return of series k on <see cref="Days"/>[d].</summary>
|
||||
public sealed record AlignedReturns(IReadOnlyList<DateOnly> Days, IReadOnlyList<double[]> Returns);
|
||||
|
||||
/// <summary>The daily Sharpe ratios of every variant of one contender, and the sessions in its year (365 crypto, 252 stocks and currencies).</summary>
|
||||
public sealed record FieldSharpes(int PeriodsPerYear, IReadOnlyList<double> DailySharpes);
|
||||
|
||||
/// <summary>
|
||||
/// The statistics of the tournament (ADR 0026, Phase 13), pure and written in house: one number of trials for the whole
|
||||
/// field, the bar it sets, the variance of the field, the probability of overfitting of every variant together, the effective
|
||||
/// number of bets, the control against chance and a bootstrap interval that keeps neighbouring days together. Each function
|
||||
/// computes one thing from its arguments; none reads a clock or a database.
|
||||
/// </summary>
|
||||
public static class TournamentStatistics
|
||||
{
|
||||
/// <summary>
|
||||
/// The common number of trials N of the deflated Sharpe ratio: every variant of every contender, every combination of
|
||||
/// finalists, every variant already in the register and every variant tried before outside it (the protocols of
|
||||
/// <c>docs/backtests</c>). Nothing is taken away: a failed contender still counts.
|
||||
/// </summary>
|
||||
public static int CommonTrials(int fieldVariants, int combinations, int registryVariants, int priorCounted)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariants);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(combinations);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(registryVariants);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(priorCounted);
|
||||
return checked(fieldVariants + combinations + registryVariants + priorCounted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The combinations of finalists the plan counts: every pair and the whole set, each with every weighting scheme. Eight
|
||||
/// finalists and three schemes give (28 + 1) × 3 = 87; fewer than two finalists give none.
|
||||
/// </summary>
|
||||
public static int Combinations(int finalists, int weightSchemes)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(finalists);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(weightSchemes);
|
||||
return finalists < 2 ? 0 : checked(((finalists * (finalists - 1) / 2) + 1) * weightSchemes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bar the plan shows before the start: the Sharpe ratio the best of <paramref name="trials"/> tries of nothing would
|
||||
/// show by chance alone, in standard deviations of the field. Zero for one trial.
|
||||
/// </summary>
|
||||
public static double Bar(int trials) => SharpeTests.ExpectedMaximum(trials, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Puts series of different calendars on one: the union of their days inside the common window, from the latest first day
|
||||
/// to the earliest last day. A day without a session for a series is a return of zero, because its equity does not move
|
||||
/// (crypto trades every day, stocks and currencies on weekdays). Each series gives its days in increasing order and one
|
||||
/// return per day.
|
||||
/// </summary>
|
||||
public static AlignedReturns Align(IReadOnlyList<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)> series)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(series);
|
||||
foreach (var (days, returns) in series)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(days);
|
||||
ArgumentNullException.ThrowIfNull(returns);
|
||||
if (days.Count != returns.Count)
|
||||
{
|
||||
throw new ArgumentException("Every series needs one return per day.", nameof(series));
|
||||
}
|
||||
|
||||
for (var i = 1; i < days.Count; i++)
|
||||
{
|
||||
if (days[i] <= days[i - 1])
|
||||
{
|
||||
throw new ArgumentException("The days of a series must be in increasing order, each once.", nameof(series));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (series.Count == 0 || series.Any(s => s.Days.Count == 0))
|
||||
{
|
||||
return new AlignedReturns([], [.. series.Select(_ => Array.Empty<double>())]);
|
||||
}
|
||||
|
||||
var first = series.Max(s => s.Days[0]);
|
||||
var last = series.Min(s => s.Days[^1]);
|
||||
var calendar = series.SelectMany(s => s.Days).Where(d => d >= first && d <= last).Distinct().Order().ToList();
|
||||
var position = new Dictionary<DateOnly, int>(calendar.Count);
|
||||
for (var i = 0; i < calendar.Count; i++)
|
||||
{
|
||||
position[calendar[i]] = i;
|
||||
}
|
||||
|
||||
var aligned = new List<double[]>(series.Count);
|
||||
foreach (var (days, returns) in series)
|
||||
{
|
||||
var values = new double[calendar.Count];
|
||||
for (var i = 0; i < days.Count; i++)
|
||||
{
|
||||
if (position.TryGetValue(days[i], out var at))
|
||||
{
|
||||
values[at] = returns[i];
|
||||
}
|
||||
}
|
||||
|
||||
aligned.Add(values);
|
||||
}
|
||||
|
||||
return new AlignedReturns(calendar, aligned);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The variance of the field: the sample variance of the annual Sharpe ratios (daily × √P) of every variant of every
|
||||
/// contender, so that a crypto year of 365 days and a stock year of 252 are compared in the same unit. Variants counted
|
||||
/// before the tournament count in N but not here, because their ratios are not all kept: the field is the variance.
|
||||
/// Zero with fewer than two variants.
|
||||
/// </summary>
|
||||
public static double FieldVariance(IReadOnlyList<FieldSharpes> field)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(field);
|
||||
var annual = new List<double>();
|
||||
foreach (var contender in field)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(contender);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(contender.PeriodsPerYear, 1);
|
||||
var root = Math.Sqrt(contender.PeriodsPerYear);
|
||||
annual.AddRange(contender.DailySharpes.Select(s => s * root));
|
||||
}
|
||||
|
||||
var deviation = Moments.Of([.. annual]).StandardDeviation;
|
||||
return deviation * deviation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The deflated Sharpe ratio of one contender against the whole field: its daily returns (Sharpe, length, skewness and
|
||||
/// kurtosis), the common number of trials and the variance of the field brought back to daily with the contender's own
|
||||
/// year (annual variance / P).
|
||||
/// </summary>
|
||||
public static DeflatedSharpe CommonDeflated(ReadOnlySpan<double> returns, int periodsPerYear, int trials, double fieldVariance)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(periodsPerYear, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariance);
|
||||
return SharpeTests.Deflated(returns, trials, fieldVariance / periodsPerYear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The probability of overfitting of the whole field (CSCV, <see cref="Validation.Overfitting"/>): every variant of every
|
||||
/// contender, on one calendar. Null when it cannot be computed (fewer than two variants or too few days).
|
||||
/// </summary>
|
||||
public static OverfittingResult? CommonOverfitting(AlignedReturns aligned, int groups = 16)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(aligned);
|
||||
return Validation.Overfitting(aligned.Returns, groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The seed of repetition <paramref name="repetition"/> of the control: the plan's seed plus the repetition, wrapping
|
||||
/// around instead of failing, so repetition k always draws the same signs.
|
||||
/// </summary>
|
||||
public static int ReplicaSeed(int seed, int repetition)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(repetition);
|
||||
return unchecked(seed + repetition);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signs of a surrogate: one per calendar day, +1 or −1 with the same probability, drawn in order from
|
||||
/// <see cref="SeededRandom"/> with <paramref name="seed"/>. Every instrument takes the sign of its day.
|
||||
/// </summary>
|
||||
public static int[] Signs(int days, int seed)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(days);
|
||||
var random = new SeededRandom(seed);
|
||||
var signs = new int[days];
|
||||
for (var i = 0; i < days; i++)
|
||||
{
|
||||
signs[i] = random.Bool() ? 1 : -1;
|
||||
}
|
||||
|
||||
return signs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The share of replicas on surrogate series that do as well as the real result or better: count(replica ≥ observed) /
|
||||
/// count. The control passes when it is at most the plan's threshold (0.05: the real result beats at least 190 of 200).
|
||||
/// What cannot be compared never helps: an observed NaN gives 1 and a NaN replica counts as at least as good.
|
||||
/// </summary>
|
||||
public static double ControlShare(double observed, IReadOnlyList<double> replicas)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(replicas);
|
||||
ArgumentOutOfRangeException.ThrowIfZero(replicas.Count);
|
||||
if (double.IsNaN(observed))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return (double)replicas.Count(r => double.IsNaN(r) || r >= observed) / replicas.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A bootstrap interval of <paramref name="statistic"/> that keeps neighbouring days together: each of
|
||||
/// <paramref name="rounds"/> resamples is made of blocks of <paramref name="block"/> days in a row, starting at random
|
||||
/// and going round the end of the series (circular moving blocks), until it is as long as the series. The bounds are the
|
||||
/// percentiles of the sorted statistics, with the convention of <c>Learning.Judge.Interval</c>. With fewer than three
|
||||
/// blocks nothing can be said: the interval is everything.
|
||||
/// </summary>
|
||||
public static (double Low, double High) Interval(IReadOnlyList<double> returns, Func<ReadOnlySpan<double>, double> statistic, int block, int rounds, double confidence, int seed)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(returns);
|
||||
ArgumentNullException.ThrowIfNull(statistic);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(block, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(rounds, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(confidence);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(confidence, 1);
|
||||
var n = returns.Count;
|
||||
if (n < 3 * block)
|
||||
{
|
||||
return (double.NegativeInfinity, double.PositiveInfinity);
|
||||
}
|
||||
|
||||
var random = new SeededRandom(seed);
|
||||
var sample = new double[n];
|
||||
var values = new double[rounds];
|
||||
for (var r = 0; r < rounds; r++)
|
||||
{
|
||||
for (var filled = 0; filled < n;)
|
||||
{
|
||||
var start = random.Int(0, n);
|
||||
for (var k = 0; k < block && filled < n; k++, filled++)
|
||||
{
|
||||
sample[filled] = returns[(start + k) % n];
|
||||
}
|
||||
}
|
||||
|
||||
values[r] = statistic(sample);
|
||||
}
|
||||
|
||||
Array.Sort(values);
|
||||
var tail = (1 - confidence) / 2;
|
||||
return (values[(int)Math.Floor(tail * (rounds - 1))], values[(int)Math.Ceiling((1 - tail) * (rounds - 1))]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The effective number of independent bets among series on one calendar: the participation ratio of their correlation
|
||||
/// matrix, n² / Σᵢⱼ ρᵢⱼ², which needs no eigenvalues (the trace of R is n, the trace of R² is Σρ²). Identical series are
|
||||
/// one bet, uncorrelated series are n. A flat series is correlated only with itself.
|
||||
/// </summary>
|
||||
public static double EffectiveBets(IReadOnlyList<double[]> aligned)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(aligned);
|
||||
var n = aligned.Count;
|
||||
if (n == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var length = aligned[0].Length;
|
||||
if (aligned.Any(s => s is null || s.Length != length))
|
||||
{
|
||||
throw new ArgumentException("Every series needs the same days.", nameof(aligned));
|
||||
}
|
||||
|
||||
// Centred series and their norms, once.
|
||||
var centred = new double[n][];
|
||||
var norms = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var mean = length > 0 ? aligned[i].Average() : 0;
|
||||
centred[i] = [.. aligned[i].Select(x => x - mean)];
|
||||
norms[i] = Math.Sqrt(centred[i].Sum(x => x * x));
|
||||
}
|
||||
|
||||
var squares = 0.0;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
squares += 1; // ρᵢᵢ = 1, flat or not
|
||||
for (var j = i + 1; j < n; j++)
|
||||
{
|
||||
if (norms[i] <= 0 || norms[j] <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var dot = 0.0;
|
||||
for (var t = 0; t < length; t++)
|
||||
{
|
||||
dot += centred[i][t] * centred[j][t];
|
||||
}
|
||||
|
||||
var rho = Math.Clamp(dot / (norms[i] * norms[j]), -1, 1);
|
||||
squares += 2 * rho * rho;
|
||||
}
|
||||
}
|
||||
|
||||
return (double)n * n / squares;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 =>
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Anubis.Core;
|
||||
|
||||
/// <summary>
|
||||
/// A fixed-seed generator based on SplitMix64 (Steele, Lea and Flood, 2014). Unlike a seeded <see cref="Random"/>, its
|
||||
/// sequence is fixed by this code, so it stays the same on every platform and .NET version: a control, a bootstrap or a
|
||||
/// synthetic series drawn from a seed repeats exactly. It moved here from the tests (Phase 13) without changing a bit of
|
||||
/// its algorithm, so every series the tests drew before draws the same today.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Two older generators stay as they are, because their outputs are recorded: <c>Learning.FixedRandom</c> (same stream,
|
||||
/// but its <c>Next</c> multiplies instead of rejecting) and <c>Backtest.PathBootstrap</c> (a seeded <see cref="Random"/>,
|
||||
/// whose results are in the committed outcome files).
|
||||
/// </remarks>
|
||||
[SuppressMessage("Naming", "CA1720", Justification = "Long, Int, Double and Decimal name what they draw; the tests have called them so since Phase 1.")]
|
||||
public sealed class SeededRandom(int seed)
|
||||
{
|
||||
// The seed is sign-extended: seed −1 starts from 0xFFFF_FFFF_FFFF_FFFF, as it always did.
|
||||
private ulong _state = unchecked((ulong)(long)seed);
|
||||
|
||||
/// <summary>The next 64 bits of SplitMix64.</summary>
|
||||
public ulong NextUInt64()
|
||||
{
|
||||
var z = _state += 0x9E3779B97F4A7C15UL;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>), without bias (rejection sampling).</summary>
|
||||
public long Long(long minInclusive, long maxExclusive)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
|
||||
var range = unchecked((ulong)(maxExclusive - minInclusive));
|
||||
var limit = ulong.MaxValue - (ulong.MaxValue % range);
|
||||
ulong x;
|
||||
do
|
||||
{
|
||||
x = NextUInt64();
|
||||
}
|
||||
while (x >= limit);
|
||||
|
||||
return unchecked(minInclusive + (long)(x % range));
|
||||
}
|
||||
|
||||
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
|
||||
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
|
||||
|
||||
/// <summary>True or false with the same probability: the lowest bit of the next draw.</summary>
|
||||
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
|
||||
|
||||
/// <summary>Uniform value in [0, 1).</summary>
|
||||
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
|
||||
|
||||
/// <summary>A standard normal value (Box–Muller, cosine branch, two draws per value), for synthetic prices and returns.</summary>
|
||||
public double Normal()
|
||||
{
|
||||
var u = 1.0 - Double();
|
||||
var v = Double();
|
||||
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
|
||||
}
|
||||
|
||||
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals, uniform on that grid.</summary>
|
||||
public decimal Decimal(decimal min, decimal max, int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
|
||||
|
||||
var unit = 1m;
|
||||
for (var i = 0; i < scale; i++)
|
||||
{
|
||||
unit /= 10m;
|
||||
}
|
||||
|
||||
var low = decimal.Ceiling(min / unit);
|
||||
var high = decimal.Floor(max / unit);
|
||||
if (low > high)
|
||||
{
|
||||
throw new ArgumentException("No value with this scale in the interval.", nameof(scale));
|
||||
}
|
||||
|
||||
var steps = high - low;
|
||||
if (steps >= long.MaxValue)
|
||||
{
|
||||
throw new ArgumentException("The interval is too wide for this scale.", nameof(scale));
|
||||
}
|
||||
|
||||
var k = Long(0, (long)steps + 1);
|
||||
return (low + k) * unit;
|
||||
}
|
||||
|
||||
/// <summary>One of <paramref name="items"/>, each with the same probability.</summary>
|
||||
public T Pick<T>(IReadOnlyList<T> items)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
|
||||
return items[Int(0, items.Count)];
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// The fixed-seed generator lives in Core since Phase 13; the tests keep calling it Gen, as they always did.
|
||||
global using Gen = Anubis.Core.SeededRandom;
|
||||
@@ -29,87 +29,3 @@ internal static class Property
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fixed-seed generator based on SplitMix64. Unlike a seeded <see cref="Random"/>, its sequence is
|
||||
/// fixed by this code, so it stays the same on every platform and .NET version.
|
||||
/// </summary>
|
||||
internal sealed class Gen(int seed)
|
||||
{
|
||||
private ulong _state = unchecked((ulong)(long)seed);
|
||||
|
||||
public ulong NextUInt64()
|
||||
{
|
||||
var z = _state += 0x9E3779B97F4A7C15UL;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
|
||||
public long Long(long minInclusive, long maxExclusive)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
|
||||
var range = unchecked((ulong)(maxExclusive - minInclusive));
|
||||
var limit = ulong.MaxValue - (ulong.MaxValue % range);
|
||||
ulong x;
|
||||
do
|
||||
{
|
||||
x = NextUInt64();
|
||||
}
|
||||
while (x >= limit);
|
||||
|
||||
return unchecked(minInclusive + (long)(x % range));
|
||||
}
|
||||
|
||||
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
|
||||
|
||||
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
|
||||
|
||||
/// <summary>Uniform value in [0, 1).</summary>
|
||||
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
|
||||
|
||||
/// <summary>A standard normal value (Box–Muller), for synthetic price series and returns.</summary>
|
||||
public double Normal()
|
||||
{
|
||||
var u = 1.0 - Double();
|
||||
var v = Double();
|
||||
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
|
||||
}
|
||||
|
||||
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
|
||||
public decimal Decimal(decimal min, decimal max, int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
|
||||
|
||||
var unit = 1m;
|
||||
for (var i = 0; i < scale; i++)
|
||||
{
|
||||
unit /= 10m;
|
||||
}
|
||||
|
||||
var low = decimal.Ceiling(min / unit);
|
||||
var high = decimal.Floor(max / unit);
|
||||
if (low > high)
|
||||
{
|
||||
throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale));
|
||||
}
|
||||
|
||||
var steps = high - low;
|
||||
if (steps >= long.MaxValue)
|
||||
{
|
||||
throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale));
|
||||
}
|
||||
|
||||
var k = Long(0, (long)steps + 1);
|
||||
return (low + k) * unit;
|
||||
}
|
||||
|
||||
public T Pick<T>(IReadOnlyList<T> items)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
|
||||
return items[Int(0, items.Count)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The control against chance (issue #124, criteria 3 and 4 of Phase 13): the surrogate series keep each day's size and
|
||||
/// the correlations and lose every memory; a rule with an edge beats them, a rule without one does not.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SurrogateTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheSurrogateKeepsEveryDaysAbsoluteReturnAndTheCorrelations()
|
||||
{
|
||||
// On returns: flipped, every day keeps its size exactly; centred, its distance from the mean.
|
||||
var returns = Synthetic.WalkReturns(1000, 3, drift: 0.001);
|
||||
var signs = TournamentStatistics.Signs(returns.Length, 5);
|
||||
var flipped = Surrogates.Flip(returns, signs, centred: false);
|
||||
var centred = Surrogates.Flip(returns, signs, centred: true);
|
||||
var mean = returns.Average();
|
||||
for (var i = 0; i < returns.Length; i++)
|
||||
{
|
||||
Assert.AreEqual(Math.Abs(returns[i]), Math.Abs(flipped[i]));
|
||||
Assert.AreEqual(signs[i] * returns[i], flipped[i]);
|
||||
Assert.AreEqual(Math.Abs(returns[i] - mean), Math.Abs(centred[i] - mean), 1e-15);
|
||||
}
|
||||
|
||||
Assert.IsTrue(signs.Count(s => s < 0) is > 400 and < 600, "About half the days change sign.");
|
||||
|
||||
// On bars: two correlated coins flip together, so their correlation stays and each day keeps its size.
|
||||
var (a, b) = Synthetic.CorrelatedReturns(2000, 0.7, 11);
|
||||
var data = Synthetic.Dataset(("AAA-EUR", Synthetic.Bars(a, 1)), ("BBB-EUR", Synthetic.Bars(b, 2)));
|
||||
var surrogate = Surrogates.Of(data, seed: 21, centred: false);
|
||||
var ra = Synthetic.CloseReturns(data["AAA-EUR"]!.Bars);
|
||||
var rb = Synthetic.CloseReturns(data["BBB-EUR"]!.Bars);
|
||||
var sa = Synthetic.CloseReturns(surrogate["AAA-EUR"]!.Bars);
|
||||
var sb = Synthetic.CloseReturns(surrogate["BBB-EUR"]!.Bars);
|
||||
var changed = 0;
|
||||
for (var i = 0; i < ra.Length; i++)
|
||||
{
|
||||
Assert.AreEqual(Math.Abs(ra[i]), Math.Abs(sa[i]), 1e-12);
|
||||
Assert.AreEqual(Math.Abs(rb[i]), Math.Abs(sb[i]), 1e-12);
|
||||
Assert.AreEqual(Math.Sign(sa[i]) * Math.Sign(ra[i]), Math.Sign(sb[i]) * Math.Sign(rb[i]), "One sign a day for every instrument.");
|
||||
changed += Math.Sign(sa[i]) != Math.Sign(ra[i]) ? 1 : 0;
|
||||
}
|
||||
|
||||
Assert.IsTrue(changed is > 800 and < 1200, $"{changed} days flipped");
|
||||
Assert.AreEqual(Synthetic.Correlation(ra, rb), Synthetic.Correlation(sa, sb), 0.02);
|
||||
Assert.AreEqual(0.7, Synthetic.Correlation(sa, sb), 0.05);
|
||||
|
||||
// The first bar is the same, the volume never changes, the high stays the highest and the low the lowest.
|
||||
foreach (var symbol in new[] { "AAA-EUR", "BBB-EUR" })
|
||||
{
|
||||
var real = data[symbol]!.Bars;
|
||||
var made = surrogate[symbol]!.Bars;
|
||||
Assert.AreEqual(real[0], made[0]);
|
||||
Assert.HasCount(real.Count, made);
|
||||
for (var i = 0; i < made.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(real[i].Day, made[i].Day);
|
||||
Assert.AreEqual(real[i].Volume, made[i].Volume);
|
||||
Assert.IsTrue(made[i].High >= Math.Max(made[i].Open, made[i].Close) && made[i].Low <= Math.Min(made[i].Open, made[i].Close), made[i].ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ASeriesWithMemoryLosesItInTheSurrogate()
|
||||
{
|
||||
var returns = Synthetic.AutoregressiveReturns(2000, 0.6, 4);
|
||||
Assert.AreEqual(0.6, Synthetic.LagOne(returns), 0.05, "The hand-built series has memory.");
|
||||
|
||||
var lost = Enumerable.Range(0, 20)
|
||||
.Select(k => Synthetic.LagOne(Surrogates.Flip(returns, TournamentStatistics.Signs(returns.Length, TournamentStatistics.ReplicaSeed(9, k)), centred: false)))
|
||||
.ToList();
|
||||
Assert.IsTrue(lost.Average(Math.Abs) < 0.1, string.Join(" ", lost));
|
||||
Assert.IsTrue(lost.All(x => Math.Abs(x) < 0.15), string.Join(" ", lost));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AFallingDayTurnedUpSwapsHighAndLow()
|
||||
{
|
||||
// From a close of 100: open 101, high 103, low 98, close 99. With the sign turned, every price p becomes
|
||||
// 100 × 100 / p, so the old low makes the new high and the old high the new low.
|
||||
var day = Synthetic.Start;
|
||||
IReadOnlyList<DailyBar> bars = [new(day, 100, 100, 100, 100, 10), new(day.AddDays(1), 101, 103, 98, 99, 20)];
|
||||
var signs = new DaySigns(day, [1, -1]);
|
||||
|
||||
var made = Surrogates.Bars(bars, signs, centred: false);
|
||||
|
||||
Assert.AreEqual(bars[0], made[0]);
|
||||
Assert.AreEqual(10_000.0 / 101, made[1].Open, 1e-9);
|
||||
Assert.AreEqual(10_000.0 / 98, made[1].High, 1e-9);
|
||||
Assert.AreEqual(10_000.0 / 103, made[1].Low, 1e-9);
|
||||
Assert.AreEqual(10_000.0 / 99, made[1].Close, 1e-9);
|
||||
Assert.AreEqual(20, made[1].Volume);
|
||||
|
||||
// The same day with its sign kept is the same bar.
|
||||
var kept = Surrogates.Bars(bars, new DaySigns(day, [1, 1]), centred: false);
|
||||
Assert.AreEqual(101, kept[1].Open, 1e-9);
|
||||
Assert.AreEqual(103, kept[1].High, 1e-9);
|
||||
Assert.AreEqual(98, kept[1].Low, 1e-9);
|
||||
Assert.AreEqual(99, kept[1].Close, 1e-9);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheSurrogateRepeatsWithItsSeedAndChangesWithAnother()
|
||||
{
|
||||
var data = Synthetic.Walk(300, 2);
|
||||
var one = Surrogates.Of(data, seed: 5, centred: true);
|
||||
var again = Surrogates.Of(data, seed: 5, centred: true);
|
||||
var other = Surrogates.Of(data, seed: 6, centred: true);
|
||||
|
||||
Assert.AreEqual(one.Fingerprint(), again.Fingerprint());
|
||||
Assert.AreNotEqual(one.Fingerprint(), other.Fingerprint());
|
||||
Assert.AreNotEqual(data.Fingerprint(), one.Fingerprint());
|
||||
Assert.AreEqual(data.Currency, one.Currency);
|
||||
CollectionAssert.AreEqual(data.Calendar.ToArray(), one.Calendar.ToArray());
|
||||
|
||||
// Signs belong to calendar days: the same days get the same signs whatever the instrument.
|
||||
var signs = DaySigns.Draw(Synthetic.Start, Synthetic.Start.AddDays(9), 5);
|
||||
Assert.AreEqual(Synthetic.Start, signs.First);
|
||||
Assert.AreEqual(Synthetic.Start.AddDays(9), signs.Last);
|
||||
CollectionAssert.AreEqual(TournamentStatistics.Signs(10, 5), Enumerable.Range(0, 10).Select(i => signs[Synthetic.Start.AddDays(i)]).ToArray());
|
||||
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => signs[Synthetic.Start.AddDays(10)]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ASurrogateOfInstrumentsWithCorporateActionsIsRefused()
|
||||
{
|
||||
var bars = BacktestData.Walk(60, 3);
|
||||
var split = new CorporateAction("AAPL", CorporateActionKinds.Split, bars[30].Day, "test", "s1") { Ratio = 2m };
|
||||
var data = BacktestData.One(BacktestData.Stock(), bars, [split]);
|
||||
|
||||
var error = Assert.ThrowsExactly<NotSupportedException>(() => Surrogates.Of(data, seed: 1, centred: true));
|
||||
Assert.AreEqual("Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.", error.Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Criterion 4, first half: three coins whose prices halve their distance from the mean in 50 bars, over 3000 days, and
|
||||
/// a rule that buys them low and sells them back at the mean. Its result is real: at most 1 surrogate in 20 does as well.
|
||||
/// One coin is not enough: the edge of this rule is a daily Sharpe ratio of about 0.03, the spread of the replicas
|
||||
/// about 0.017, so on one coin of 3000 days the control passes on one seed out of three; three coins make it about
|
||||
/// three spreads.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OnAMeanRevertingSeriesAReversionRulePassesTheControl()
|
||||
{
|
||||
var data = Synthetic.MeanReverting(3000, 7, coins: 3, halfLife: 50, volatility: 0.01);
|
||||
|
||||
var (observed, replicas, share) = Synthetic.Control(ReversionFamily.Instance, ReversionFamily.With(300, 1m), data, 200, seed: 20_261_204, centred: true);
|
||||
|
||||
Assert.IsTrue(observed > 0, $"observed {observed}");
|
||||
Assert.IsTrue(share <= 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Criterion 4, second half: on a random walk that drifts up, a long-only trend rule earns the drift and nothing
|
||||
/// else. The centred surrogates keep the drift, so they do as well and the rule fails the control.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OnARandomWalkWithDriftALongOnlyTrendRuleFailsTheControl()
|
||||
{
|
||||
var data = Synthetic.Walk(3000, 8, drift: 0.0008, volatility: 0.02);
|
||||
var parameters = new StrategyParameters([new("fast", 20m), new("slow", 100m)]);
|
||||
|
||||
var (observed, replicas, share) = Synthetic.Control(MovingAverageCrossFamily.Instance, parameters, data, 200, seed: 20_261_204, centred: true);
|
||||
|
||||
Assert.IsTrue(share > 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Synthetic series with a known nature, built from a fixed seed (Phase 13): a mean-reverting price (Ornstein–Uhlenbeck on
|
||||
/// the logarithm), a random walk with or without drift, returns with memory, correlated pairs. The statistics of the
|
||||
/// tournament are proved on them, because only there is the truth known in advance. Shared by the tests of the control,
|
||||
/// of the common statistics and of the tournament.
|
||||
/// </summary>
|
||||
internal static class Synthetic
|
||||
{
|
||||
public static readonly DateOnly Start = new(2018, 1, 1);
|
||||
|
||||
/// <summary>A coin quoted in euro on OKX, traded every day: the synthetic series live on it.</summary>
|
||||
public static InstrumentSpec Coin(string symbol = "AAA-EUR") => new(Venues.Okx, symbol, symbol, AssetClasses.Crypto, "EUR")
|
||||
{
|
||||
BaseCurrency = symbol.Split('-')[0],
|
||||
TickSize = 0.0001m,
|
||||
LotSize = 0.00000001m,
|
||||
MinSize = 0.00001m,
|
||||
Status = "live",
|
||||
};
|
||||
|
||||
/// <summary>The autoregressive coefficient of a daily series whose distance from its mean halves in <paramref name="halfLife"/> bars.</summary>
|
||||
public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife);
|
||||
|
||||
/// <summary>
|
||||
/// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the
|
||||
/// <paramref name="halfLife"/> and the series started at its level. The return of day t is x(t) − x(t−1).
|
||||
/// </summary>
|
||||
public static double[] MeanRevertingReturns(int days, int seed, double halfLife = 50, double volatility = 0.01)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
var phi = Phi(halfLife);
|
||||
var result = new double[days];
|
||||
var x = 0.0;
|
||||
for (var i = 0; i < days; i++)
|
||||
{
|
||||
var next = (phi * x) + (volatility * gen.Normal());
|
||||
result[i] = next - x;
|
||||
x = next;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Log returns of a random walk: <paramref name="drift"/> plus normal noise, no memory.</summary>
|
||||
public static double[] WalkReturns(int days, int seed, double drift = 0, double volatility = 0.01)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
var result = new double[days];
|
||||
for (var i = 0; i < days; i++)
|
||||
{
|
||||
result[i] = drift + (volatility * gen.Normal());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ.</summary>
|
||||
public static double[] AutoregressiveReturns(int days, double phi, int seed, double volatility = 0.01)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
var result = new double[days];
|
||||
var previous = 0.0;
|
||||
for (var i = 0; i < days; i++)
|
||||
{
|
||||
previous = (phi * previous) + (volatility * gen.Normal());
|
||||
result[i] = previous;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Two series of returns with correlation about <paramref name="correlation"/>: a common part and a part of each.</summary>
|
||||
public static (double[] A, double[] B) CorrelatedReturns(int days, double correlation, int seed, double volatility = 0.01)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
var own = Math.Sqrt(1 - (correlation * correlation));
|
||||
var a = new double[days];
|
||||
var b = new double[days];
|
||||
for (var i = 0; i < days; i++)
|
||||
{
|
||||
var common = gen.Normal();
|
||||
a[i] = volatility * common;
|
||||
b[i] = volatility * ((correlation * common) + (own * gen.Normal()));
|
||||
}
|
||||
|
||||
return (a, b);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Daily bars from log returns of the close: the first bar at <paramref name="start"/>, then each close the one before
|
||||
/// times e^r. The open is the previous close, high and low a little beyond the body, all unrounded.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<double> logReturns, int seed = 1, double start = 100, DateOnly? from = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logReturns);
|
||||
var gen = new Gen(seed);
|
||||
var day = from ?? Start;
|
||||
var bars = new List<DailyBar>(logReturns.Count + 1) { new(day, start, start * 1.002, start * 0.998, start, 1000) };
|
||||
var close = start;
|
||||
for (var i = 0; i < logReturns.Count; i++)
|
||||
{
|
||||
var open = close;
|
||||
close = open * Math.Exp(logReturns[i]);
|
||||
var high = Math.Max(open, close) * (1 + (0.003 * gen.Double()));
|
||||
var low = Math.Min(open, close) * (1 - (0.003 * gen.Double()));
|
||||
bars.Add(new DailyBar(day.AddDays(i + 1), open, high, low, close, 1000));
|
||||
}
|
||||
|
||||
return bars;
|
||||
}
|
||||
|
||||
/// <summary>A dataset in euro of synthetic coins, one per series of bars.</summary>
|
||||
public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList<DailyBar> Bars)[] series) =>
|
||||
new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR");
|
||||
|
||||
/// <summary>A mean-reverting coin: <paramref name="days"/> returns of <see cref="MeanRevertingReturns"/> turned into bars.</summary>
|
||||
public static BacktestDataset MeanReverting(int days, int seed, double halfLife = 50, double volatility = 0.01, string symbol = "AAA-EUR") =>
|
||||
Dataset((symbol, Bars(MeanRevertingReturns(days, seed, halfLife, volatility), seed)));
|
||||
|
||||
/// <summary>Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed.</summary>
|
||||
public static BacktestDataset MeanReverting(int days, int seed, int coins, double halfLife = 50, double volatility = 0.01) =>
|
||||
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(MeanRevertingReturns(days, seed + (1000 * k), halfLife, volatility), seed + k)))]);
|
||||
|
||||
/// <summary>Several independent coins walking at random with the same <paramref name="drift"/>, each from its own seed.</summary>
|
||||
public static BacktestDataset Walk(int days, int seed, int coins, double drift = 0, double volatility = 0.01) =>
|
||||
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(WalkReturns(days, seed + (1000 * k), drift, volatility), seed + k)))]);
|
||||
|
||||
/// <summary>The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR…</summary>
|
||||
public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR");
|
||||
|
||||
/// <summary>A coin that walks at random with a <paramref name="drift"/> a day (zero for pure noise).</summary>
|
||||
public static BacktestDataset Walk(int days, int seed, double drift = 0, double volatility = 0.01, string symbol = "AAA-EUR") =>
|
||||
Dataset((symbol, Bars(WalkReturns(days, seed, drift, volatility), seed)));
|
||||
|
||||
/// <summary>Log returns of the closes of a series of bars, one per bar after the first.</summary>
|
||||
public static double[] CloseReturns(IReadOnlyList<DailyBar> bars)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
return [.. Enumerable.Range(1, Math.Max(bars.Count - 1, 0)).Select(i => Math.Log(bars[i].Close / bars[i - 1].Close))];
|
||||
}
|
||||
|
||||
/// <summary>Pearson correlation of two series of the same length.</summary>
|
||||
public static double Correlation(IReadOnlyList<double> x, IReadOnlyList<double> y)
|
||||
{
|
||||
var mx = x.Average();
|
||||
var my = y.Average();
|
||||
double sxy = 0, sxx = 0, syy = 0;
|
||||
for (var i = 0; i < x.Count; i++)
|
||||
{
|
||||
sxy += (x[i] - mx) * (y[i] - my);
|
||||
sxx += (x[i] - mx) * (x[i] - mx);
|
||||
syy += (y[i] - my) * (y[i] - my);
|
||||
}
|
||||
|
||||
return sxy / Math.Sqrt(sxx * syy);
|
||||
}
|
||||
|
||||
/// <summary>Autocorrelation at lag one.</summary>
|
||||
public static double LagOne(IReadOnlyList<double> x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]);
|
||||
|
||||
/// <summary>The daily Sharpe ratio of a run: what the control compares between the real series and its replicas.</summary>
|
||||
public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe;
|
||||
|
||||
/// <summary>
|
||||
/// The control of a rule on a dataset: its daily Sharpe on the real data, and on <paramref name="repetitions"/>
|
||||
/// surrogates whose signs come from <paramref name="seed"/> + k. Returns the observed Sharpe, the replicas and the
|
||||
/// share of replicas at least as good.
|
||||
/// </summary>
|
||||
public static (double Observed, double[] Replicas, double Share) Control(IStrategyFamily family, StrategyParameters parameters, BacktestDataset data, int repetitions, int seed, bool centred)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(family);
|
||||
var options = new BacktestOptions();
|
||||
var observed = Sharpe(BacktestEngine.Run(family.Create(parameters), data, options));
|
||||
var replicas = new double[repetitions];
|
||||
for (var k = 0; k < repetitions; k++)
|
||||
{
|
||||
var surrogate = Surrogates.Of(data, TournamentStatistics.ReplicaSeed(seed, k), centred);
|
||||
replicas[k] = Sharpe(BacktestEngine.Run(family.Create(parameters), surrogate, options));
|
||||
}
|
||||
|
||||
return (observed, replicas, TournamentStatistics.ControlShare(observed, replicas));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A test-only reversion rule, long only: it buys an instrument when its close falls <c>entry</c> standard deviations
|
||||
/// below the mean of the last <c>lookback</c> closes (on the logarithm), and sells when the close is back at the mean. It
|
||||
/// has an edge on a mean-reverting series and none on a random walk. It never enters the catalogue and has no order code.
|
||||
/// </summary>
|
||||
internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy
|
||||
{
|
||||
/// <summary>Bars it waits for before the first decision; until <c>lookback</c> bars, the mean is of those there are.</summary>
|
||||
public const int MinimumBars = 50;
|
||||
|
||||
public string Id => ReversionFamily.FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
var intents = new List<Intent>();
|
||||
var weight = 1m / Math.Max(context.Universe.Count, 1);
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
if (bars.Count < Math.Min(lookback, MinimumBars))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var logs = bars.Closes(lookback).Select(c => Math.Log(c)).ToArray();
|
||||
var m = Moments.Of(logs);
|
||||
if (m.StandardDeviation <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var z = (logs[^1] - m.Mean) / m.StandardDeviation;
|
||||
var held = context.Portfolio.Holds(symbol);
|
||||
if (!held && z < -(double)entry)
|
||||
{
|
||||
intents.Add(new Intent(symbol, weight, "reversion_entry"));
|
||||
}
|
||||
else if (held && z >= 0)
|
||||
{
|
||||
intents.Add(new Intent(symbol, 0m, "reversion_exit"));
|
||||
}
|
||||
}
|
||||
|
||||
return intents;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The family of <see cref="ReversionRule"/>: the window of the mean and the distance of the entry.</summary>
|
||||
internal sealed class ReversionFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "test_reversion";
|
||||
|
||||
public static ReversionFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public string Name => "Rientro di prova";
|
||||
|
||||
public string Description => "Regola di prova, solo nei test: compra sotto la media e vende quando il prezzo vi torna.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("lookback", "Giorni della media", 100m, [50m, 100m, 150m], 10m, 400m, Whole: true),
|
||||
new("entry", "Distanza d'ingresso in deviazioni", 1m, [0.5m, 1m, 1.5m], 0.1m, 4m),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new ReversionRule(parameters.Whole("lookback"), parameters["entry"]);
|
||||
}
|
||||
|
||||
/// <summary>The parameters of a variant, as the laboratory would build them.</summary>
|
||||
public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
using Anubis.Backtest;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The common statistics of the tournament (issue #124, criterion 5 of Phase 13): one number of trials for the whole field,
|
||||
/// one bar, one variance, one PBO, the effective number of bets, the bootstrap interval and the calendars put side by side.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class TournamentStatisticsTests
|
||||
{
|
||||
private static readonly DateOnly Monday = new(2024, 1, 1);
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TwentyEightIdenticalSeriesAreWorthOneBet()
|
||||
{
|
||||
var one = Synthetic.WalkReturns(500, 1);
|
||||
var copies = Enumerable.Range(0, 28).Select(_ => one.ToArray()).ToList();
|
||||
Assert.AreEqual(1.0, TournamentStatistics.EffectiveBets(copies), 1e-12);
|
||||
|
||||
// Independent series are about as many bets as series; a flat series is a bet of its own.
|
||||
var independent = Enumerable.Range(0, 28).Select(k => Synthetic.WalkReturns(500, 100 + k)).ToList();
|
||||
Assert.IsTrue(TournamentStatistics.EffectiveBets(independent) > 20, TournamentStatistics.EffectiveBets(independent).ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
Assert.AreEqual(2.0, TournamentStatistics.EffectiveBets([one, new double[500]]), 1e-12);
|
||||
Assert.AreEqual(0.0, TournamentStatistics.EffectiveBets([]));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.EffectiveBets([one, new double[10]]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A rule with no edge, tried in a hundred variants on noise: the best one looks good alone, but against the common
|
||||
/// number of trials and the variance of the field it never reaches the threshold of 0.90.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AStrategyWithNoEdgeTriedInOneHundredVariantsStaysBelowTheBar()
|
||||
{
|
||||
for (var seed = 1; seed <= 10; seed++)
|
||||
{
|
||||
var variants = Enumerable.Range(0, 100).Select(k => Synthetic.WalkReturns(1000, (seed * 1000) + k)).ToList();
|
||||
var sharpes = variants.Select(v => Moments.Of(v).Sharpe).ToList();
|
||||
var best = variants[sharpes.IndexOf(sharpes.Max())];
|
||||
var variance = TournamentStatistics.FieldVariance([new FieldSharpes(365, sharpes)]);
|
||||
var trials = TournamentStatistics.CommonTrials(100, 0, 0, 0);
|
||||
|
||||
var dsr = TournamentStatistics.CommonDeflated(best, 365, trials, variance);
|
||||
|
||||
Assert.AreEqual(100, dsr.Trials);
|
||||
Assert.IsTrue(dsr.Value < 0.90, $"seed {seed}: DSR {dsr.Value}");
|
||||
Assert.IsTrue(SharpeTests.Deflated(best, 1, 0).Value > dsr.Value, "Alone, the best variant looks better.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFieldVarianceIsTakenOnAnnualisedSharpes()
|
||||
{
|
||||
// A crypto contender (365 days a year) and a stock one (252): their daily Sharpes become annual before the
|
||||
// variance, and the variance goes back to daily with the year of the series judged.
|
||||
var field = new[] { new FieldSharpes(365, [0.05, 0.07]), new FieldSharpes(252, [0.05, 0.07]) };
|
||||
double[] annual = [0.05 * Math.Sqrt(365), 0.07 * Math.Sqrt(365), 0.05 * Math.Sqrt(252), 0.07 * Math.Sqrt(252)];
|
||||
var expected = Math.Pow(Moments.Of(annual).StandardDeviation, 2);
|
||||
Assert.AreEqual(expected, TournamentStatistics.FieldVariance(field), 1e-15);
|
||||
|
||||
var returns = Synthetic.WalkReturns(500, 2, drift: 0.001);
|
||||
var crypto = TournamentStatistics.CommonDeflated(returns, 365, 50, expected);
|
||||
var stock = TournamentStatistics.CommonDeflated(returns, 252, 50, expected);
|
||||
Assert.AreEqual(expected / 365, crypto.SharpeVariance, 1e-18);
|
||||
Assert.AreEqual(expected / 252, stock.SharpeVariance, 1e-18);
|
||||
Assert.IsTrue(stock.Benchmark > crypto.Benchmark, "Fewer days a year, a higher daily bar.");
|
||||
|
||||
Assert.AreEqual(0, TournamentStatistics.FieldVariance([new FieldSharpes(365, [0.05])]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Noise on two calendars, crypto every day and stocks on weekdays, put side by side with zero on the days without a
|
||||
/// session: the probability of overfitting of the whole field is about one half. On average over forty seeds, because on
|
||||
/// one seed alone it swings widely (from 0.14 to 0.54 on the first eight).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCommonPboOnNoiseIsAboutOneHalf()
|
||||
{
|
||||
var values = new List<double>();
|
||||
for (var seed = 1; seed <= 40; seed++)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
var everyDay = Enumerable.Range(0, 1100).Select(i => Monday.AddDays(i)).ToList();
|
||||
var weekdays = everyDay.Where(d => d.DayOfWeek is not DayOfWeek.Saturday and not DayOfWeek.Sunday).ToList();
|
||||
var series = new List<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)>();
|
||||
for (var v = 0; v < 10; v++)
|
||||
{
|
||||
series.Add((everyDay, [.. everyDay.Select(_ => 0.01 * gen.Normal())]));
|
||||
series.Add((weekdays, [.. weekdays.Select(_ => 0.01 * gen.Normal())]));
|
||||
}
|
||||
|
||||
var aligned = TournamentStatistics.Align(series);
|
||||
var pbo = TournamentStatistics.CommonOverfitting(aligned);
|
||||
|
||||
Assert.IsNotNull(pbo);
|
||||
Assert.AreEqual(20, pbo.Variants);
|
||||
Assert.AreEqual(12870, pbo.Combinations);
|
||||
values.Add(pbo.Probability);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0.5, values.Average(), 0.1, string.Join(" ", values));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheBarGrowsWithTheTrials()
|
||||
{
|
||||
Assert.AreEqual(0, TournamentStatistics.Bar(1));
|
||||
Assert.IsTrue(TournamentStatistics.Bar(10) < TournamentStatistics.Bar(100));
|
||||
Assert.IsTrue(TournamentStatistics.Bar(100) < TournamentStatistics.Bar(1000));
|
||||
Assert.AreEqual(SharpeTests.ExpectedMaximum(100, 1), TournamentStatistics.Bar(100));
|
||||
// The best of a hundred tries of nothing stands about two and a half standard deviations above zero.
|
||||
Assert.AreEqual(2.5, TournamentStatistics.Bar(100), 0.1);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void EightFinalistsGiveEightySevenCombinations()
|
||||
{
|
||||
// 28 pairs and the whole set, each with three weighting schemes.
|
||||
Assert.AreEqual(87, TournamentStatistics.Combinations(8, 3));
|
||||
Assert.AreEqual(6, TournamentStatistics.Combinations(2, 3));
|
||||
Assert.AreEqual(0, TournamentStatistics.Combinations(1, 3));
|
||||
Assert.AreEqual(0, TournamentStatistics.Combinations(0, 3));
|
||||
|
||||
Assert.AreEqual(500 + 87 + 40 + 27, TournamentStatistics.CommonTrials(500, 87, 40, 27));
|
||||
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.CommonTrials(-1, 0, 0, 0));
|
||||
Assert.ThrowsExactly<OverflowException>(() => TournamentStatistics.CommonTrials(int.MaxValue, 1, 0, 0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheIntervalContainsTheTrueMeanOfAKnownSeries()
|
||||
{
|
||||
var gen = new Gen(3);
|
||||
var values = Enumerable.Range(0, 400).Select(_ => 0.05 + gen.Normal()).ToArray();
|
||||
static double Mean(ReadOnlySpan<double> x)
|
||||
{
|
||||
var sum = 0.0;
|
||||
foreach (var v in x)
|
||||
{
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return sum / x.Length;
|
||||
}
|
||||
|
||||
var (low, high) = TournamentStatistics.Interval(values, Mean, block: 10, rounds: 2000, confidence: 0.95, seed: 1);
|
||||
Assert.IsTrue(low < 0.05 && 0.05 < high, $"{low} – {high}");
|
||||
Assert.IsTrue(high - low is > 0.1 and < 0.3, $"width {high - low}");
|
||||
Assert.AreEqual((low, high), TournamentStatistics.Interval(values, Mean, 10, 2000, 0.95, 1), "The same seed gives the same interval.");
|
||||
|
||||
// Dependent data: each value ten times in a row. As many numbers as independent ones, ten times fewer facts.
|
||||
var twins = values.SelectMany(v => Enumerable.Repeat(v, 10)).ToArray();
|
||||
var independent = Enumerable.Range(0, twins.Length).Select(_ => 0.05 + gen.Normal()).ToArray();
|
||||
var (tl, th) = TournamentStatistics.Interval(twins, Mean, 10, 2000, 0.95, 1);
|
||||
var (il, ih) = TournamentStatistics.Interval(independent, Mean, 10, 2000, 0.95, 1);
|
||||
Assert.IsTrue(th - tl > 1.8 * (ih - il), $"twins {th - tl}, independent {ih - il}");
|
||||
|
||||
// Fewer than three blocks: nothing can be said.
|
||||
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), TournamentStatistics.Interval(values[..29], Mean, 10, 2000, 0.95, 1));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AlignmentPutsTheSeriesOnTheUnionOfTheirDaysWithZeroWhereThereIsNoSession()
|
||||
{
|
||||
// Crypto from Monday 1 January for ten days; a stock from Wednesday 3 January on weekdays to Friday 12.
|
||||
var crypto = Enumerable.Range(0, 10).Select(i => Monday.AddDays(i)).ToList();
|
||||
var stock = new[] { 2, 3, 4, 7, 8, 9, 10, 11 }.Select(i => Monday.AddDays(i)).ToList();
|
||||
var aligned = TournamentStatistics.Align(
|
||||
[
|
||||
(crypto, [.. crypto.Select((_, i) => (i + 1) / 100.0)]),
|
||||
(stock, [.. stock.Select((_, i) => -(i + 1) / 100.0)]),
|
||||
]);
|
||||
|
||||
// The common window runs from the latest first day (3 January) to the earliest last day (10 January).
|
||||
CollectionAssert.AreEqual(Enumerable.Range(2, 8).Select(i => Monday.AddDays(i)).ToArray(), aligned.Days.ToArray());
|
||||
CollectionAssert.AreEqual(new[] { 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10 }, aligned.Returns[0]);
|
||||
// Saturday 6 and Sunday 7 January: the stock has no session, its equity does not move.
|
||||
CollectionAssert.AreEqual(new[] { -0.01, -0.02, -0.03, 0, 0, -0.04, -0.05, -0.06 }, aligned.Returns[1]);
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([(crypto, [0.1])]));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([([Monday.AddDays(1), Monday], [0.1, 0.2])]));
|
||||
Assert.IsEmpty(TournamentStatistics.Align([(crypto[..3], [0.1, 0.2, 0.3]), (crypto[5..], [0.1, 0.2, 0.3, 0.4, 0.5])]).Days);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void SignsAreOnePerDayAndRepeatWithTheirSeed()
|
||||
{
|
||||
var signs = TournamentStatistics.Signs(1000, 7);
|
||||
Assert.HasCount(1000, signs);
|
||||
Assert.IsTrue(signs.All(s => s is 1 or -1));
|
||||
Assert.IsTrue(signs.Count(s => s > 0) is > 450 and < 550);
|
||||
CollectionAssert.AreEqual(signs, TournamentStatistics.Signs(1000, 7));
|
||||
CollectionAssert.AreNotEqual(signs, TournamentStatistics.Signs(1000, TournamentStatistics.ReplicaSeed(7, 1)));
|
||||
Assert.AreEqual(10, TournamentStatistics.ReplicaSeed(7, 3));
|
||||
Assert.AreEqual(int.MinValue, TournamentStatistics.ReplicaSeed(int.MaxValue, 1), "The seed wraps instead of failing.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheControlShareCountsTheReplicasAtLeastAsGood()
|
||||
{
|
||||
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(1.0, [0.0, 1.0, 2.0, 0.5]));
|
||||
Assert.AreEqual(0.0, TournamentStatistics.ControlShare(3.0, [0.0, 1.0, 2.0, 0.5]));
|
||||
// Nothing to say is never a pass: an observed NaN fails, a NaN replica counts against.
|
||||
Assert.AreEqual(1.0, TournamentStatistics.ControlShare(double.NaN, [0.0, 1.0]));
|
||||
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(3.0, [double.NaN, 1.0]));
|
||||
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.ControlShare(1.0, []));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user