diff --git a/docs/adr/0010-scelte-fase-4.md b/docs/adr/0010-scelte-fase-4.md index 08d2158..cce86b0 100644 --- a/docs/adr/0010-scelte-fase-4.md +++ b/docs/adr/0010-scelte-fase-4.md @@ -39,7 +39,7 @@ La Fase 4 costruisce il motore di prova sullo storico, le convalide del protocol **9. Il numero di prove del DSR.** N è la somma delle varianti di tutte le prove concluse della stessa strategia più quelle della prova corrente; la varianza degli Sharpe è quella di tutte queste varianti. Ogni nuovo tentativo alza l'asticella dei successivi. **10. Il piano si scrive prima e non cambia.** -- Prima di qualsiasi calcolo si salvano il piano in JSON (strategia e versione, griglia, dati, capitale, moltiplicatori dei costi, misure delle convalide, soglie, versione del motore) e la sua impronta SHA-256. Il codice non aggiorna mai piano e impronta: un test controlla che dopo la corsa testo e impronta siano identici. +- Prima di qualsiasi calcolo si salvano il piano in JSON (strategia e versione, griglia, dati, capitale, moltiplicatori dei costi, misure delle convalide, soglie, versione del motore) e la sua impronta SHA-256. Il codice non aggiorna mai piano e impronta: un test controlla che dopo la corsa testo e impronta siano identici. Prima di partire la prova ricalcola l'impronta: se il piano non le corrisponde più, non parte. - Su PostgreSQL la colonna è `json`, non `jsonb`, così il testo resta identico e l'impronta si ricontrolla. - Le soglie sono nel piano: risultato netto positivo con costi doppi, DSR almeno 0,90, PBO non oltre 0,40, calo massimo non oltre il 25%, nessuna decisione cambiata dai dati futuri. La prova è superata se nessun controllo è fallito; un controllo che non si applica non la fa fallire. @@ -49,14 +49,15 @@ La Fase 4 costruisce il motore di prova sullo storico, le convalide del protocol - Una prova alla volta, su un thread suo a priorità bassa. Solo la parte asincrona tocca il database. - All'avvio le prove rimaste "in corso" tornano "pianificate" e ripartono con lo stesso piano. - Una prova fallita tiene il motivo. -- Massimo 20 strumenti e 200 varianti per prova, almeno 30 sedute. +- Massimo 20 strumenti e 200 varianti per prova, almeno 30 sedute, capitale tra 1 e 10.000.000. I parametri che contano giorni accettano solo numeri interi: 10,5 girerebbe come 10 e conterebbe due volte nel DSR. +- Un errore del database (per esempio PostgreSQL che riparte) non ferma la coda: si riprova dopo 30 secondi. - Nella modalità dimostrativa il laboratorio è spento. **13. Le due origini dei dati.** - "Barre raccolte": le barre giornaliere del database, con frazionamenti e dividendi per le azioni. -- "Storico di ricerca": gli archivi Binance (Fase 2), nella loro valuta (USDT). Le regole d'ordine non ci sono negli archivi: passo di prezzo e di quantità di 0,00000001 e controvalore minimo 5, che non bloccano mai; i costi sono quelli di OKX. Il rapporto lo scrive. La conversione in euro (annunciata nello STATE della Fase 2) non serve: una prova lavora in una sola valuta e rifiuta strumenti quotati in valute diverse. +- "Storico di ricerca": gli archivi Binance (Fase 2), nella loro valuta (USDT). Le regole d'ordine non ci sono negli archivi: passo di prezzo e di quantità di 0,00000001 e controvalore minimo di 5 (come i minimi tipici delle borse crypto: un ordine più piccolo non parte e un residuo sotto i 5 si perde all'uscita); i costi sono quelli di OKX. Il rapporto lo scrive. La conversione in euro (annunciata nello STATE della Fase 2) non serve: una prova lavora in una sola valuta e rifiuta strumenti quotati in valute diverse. -**14. Il rapporto.** Contiene i controlli del protocollo, la variante scelta contro "comprare e tenere" (pesi uguali, stessi costi), i risultati per anno, la sensibilità ai costi, DSR, PBO, finestre, percorsi, sguardo in avanti, tutte le varianti con il loro punteggio, ciò che il test non considera, l'impronta dei dati e le operazioni. La curva tiene al massimo 500 punti e l'elenco le ultime 300 operazioni, per restare leggero nel database. Il confronto tra due prove dice se hanno letto gli stessi dati. +**14. Il rapporto.** Contiene i controlli del protocollo, la variante scelta contro "comprare e tenere" (pesi uguali, stessi costi; uno strumento la cui storia comincia dopo si compra alla sua prima chiusura, con la quota rimasta libera per lui), i risultati per anno, la sensibilità ai costi, DSR, PBO, finestre, percorsi, sguardo in avanti, tutte le varianti con il loro punteggio, ciò che il test non considera, l'impronta dei dati e le operazioni. La curva tiene al massimo 500 punti e l'elenco le ultime 300 operazioni, per restare leggero nel database. Il confronto tra due prove dice se hanno letto gli stessi dati. **15. Le sezioni che arrivano dopo.** "Migliorie in osservazione" (8.7) e "Stime di costo da confermare" (11.6) sono già nella schermata, vuote, con la fase che le riempie (9 e 8). diff --git a/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor b/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor index c2ba41a..73940cf 100644 --- a/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor +++ b/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor @@ -71,11 +71,12 @@ [CascadingParameter] public HttpContext? HttpContext { get; set; } + // Text, not Guid: a malformed value must give "servono due test", not an error page. [SupplyParameterFromQuery(Name = "a")] - public Guid? A { get; set; } + public string? A { get; set; } [SupplyParameterFromQuery(Name = "b")] - public Guid? B { get; set; } + public string? B { get; set; } protected override async Task LoadAsync() { @@ -85,9 +86,9 @@ _b = await ReadAsync(store, B, ct); } - private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, Guid? id, CancellationToken ct) + private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, string? id, CancellationToken ct) { - if (id is not { } key || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json) + if (!Guid.TryParse(id, out var key) || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json) { return null; } diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 1d6896b..4787daa 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -50,6 +50,9 @@ public sealed partial class Laboratory : IDisposable public const int MaxVariants = 200; + /// The pause after an error of the queue itself (the database out of reach), before trying again. + public static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(30); + private readonly Database _db; private readonly IClock _clock; private readonly string _researchRoot; @@ -107,7 +110,7 @@ public sealed partial class Laboratory : IDisposable throw new TrialRequestException(TrialRequestErrors.Dates, "La data di inizio deve venire prima di quella di fine."); } - if (request.InitialCapital is <= 0m or > 10_000_000m) + if (request.InitialCapital is < 1m or > 10_000_000m) { throw new TrialRequestException(TrialRequestErrors.Capital, "Il capitale iniziale deve essere tra 1 e 10.000.000."); } @@ -121,6 +124,12 @@ public sealed partial class Laboratory : IDisposable throw new TrialRequestException(TrialRequestErrors.Grid, string.Create(CultureInfo.GetCultureInfo("it-IT"), $"{p.Label}: i valori vanno da {p.Min} a {p.Max}.")); } + // A whole parameter given 10.5 would run as 10: two variants that are the same would count twice in the DSR. + if (p.Whole && values.Any(x => x != decimal.Truncate(x))) + { + throw new TrialRequestException(TrialRequestErrors.Grid, p.Label + ": servono numeri interi."); + } + grid[p.Name] = [.. values.Distinct().Order()]; } @@ -150,16 +159,42 @@ public sealed partial class Laboratory : IDisposable } /// Runs the queue until stopped: first the trials left planned or halfway by the last run, then the new ones. + /// + /// An error of the queue itself (the database out of reach) never stops it: it waits and + /// tries the same trial again. A trial left running by such an error is planned again at the next start. + /// public async Task RunAsync(CancellationToken cancellationToken) { - foreach (var id in await Trials.ResumeAsync(cancellationToken).ConfigureAwait(false)) + while (true) { - await _queue.Writer.WriteAsync(id, cancellationToken).ConfigureAwait(false); + try + { + foreach (var id in await Trials.ResumeAsync(cancellationToken).ConfigureAwait(false)) + { + await _queue.Writer.WriteAsync(id, cancellationToken).ConfigureAwait(false); + } + + break; + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogQueueFailed(_logger, ex); + await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false); + } } await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) { - await ProcessAsync(id, cancellationToken).ConfigureAwait(false); + try + { + await ProcessAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogQueueFailed(_logger, ex); + await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false); + _queue.Writer.TryWrite(id); + } } } @@ -171,10 +206,15 @@ public sealed partial class Laboratory : IDisposable return; } - var trial = (await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false))!; _progress[id] = "lettura dei dati"; try { + var trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata."); + if (!trial.PlanIntact) + { + throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte."); + } + var family = StrategyCatalog.Find(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy); if (family.Version != trial.StrategyVersion) { @@ -285,6 +325,9 @@ public sealed partial class Laboratory : IDisposable [LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")] private static partial void LogFinished(ILogger logger, Guid id, string strategy, bool passed); + [LoggerMessage(Level = LogLevel.Warning, Message = "Laboratory queue error, trying again shortly")] + private static partial void LogQueueFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")] private static partial void LogFailed(ILogger logger, Guid id, Exception exception); } diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index a89a15c..01e4274 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -142,7 +142,7 @@ public static class TrialRunner costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } - var benchmarkRun = BacktestEngine.Run(new BuyAndHold(), data, options); + var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Instruments.Count), data, options); var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 49b9e6c..35260c8 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -112,6 +112,9 @@ public sealed record Trial( DateTimeOffset? FinishedAt) { public bool IsFinished => Status is TrialStatuses.Done or TrialStatuses.Failed; + + /// The stored plan text still gives the stored hash: nobody changed it after it was written. + public bool PlanIntact { get; init; } = true; } /// The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios. @@ -210,6 +213,9 @@ public sealed class TrialStore(Database db, IClock clock) r.TextOrNull("error"), r.Moment("created_at"), r.MomentOrNull("started_at"), - r.MomentOrNull("finished_at")); + r.MomentOrNull("finished_at")) + { + PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"), + }; } } diff --git a/src/Anubis/Strategies/Research.cs b/src/Anubis/Strategies/Research.cs index b74ee69..04dabc0 100644 --- a/src/Anubis/Strategies/Research.cs +++ b/src/Anubis/Strategies/Research.cs @@ -1,17 +1,19 @@ namespace Anubis.Strategies; /// -/// Buy at the first close in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2, -/// step 6. It decides only from its own book, so it can restart from any recorded state. +/// Buy in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2, step 6. Each +/// instrument is bought at its first close, so one whose history starts later is bought then, with the share kept for +/// it. It decides only from its own book, so it can restart from any recorded state. /// -public sealed class BuyAndHold : IStrategy +/// How many instruments share the capital; null means those available at each decision. +public sealed class BuyAndHold(int? instruments = null) : IStrategy { /// A little cash stays aside for the fees, so the last purchase is not cut short. public const decimal Invested = 0.995m; public string Id => BuyAndHoldFamily.FamilyId; - public string Version => "1"; + public string Version => "2"; public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; @@ -24,13 +26,14 @@ public sealed class BuyAndHold : IStrategy public IReadOnlyList Decide(StrategyContext context) { ArgumentNullException.ThrowIfNull(context); - if (context.Portfolio.Holdings.Count > 0 || context.Universe.Count == 0) + var parts = Math.Max(instruments ?? context.Universe.Count, context.Universe.Count); + if (parts == 0) { return []; } - var weight = Invested / context.Universe.Count; - return [.. context.Universe.Select(s => new Intent(s, weight, "buy_and_hold"))]; + var weight = Invested / parts; + return [.. context.Universe.Where(s => context.Portfolio.Of(s) is null).Select(s => new Intent(s, weight, "buy_and_hold"))]; } } @@ -42,11 +45,11 @@ public sealed class BuyAndHoldFamily : IStrategyFamily public string Id => FamilyId; - public string Version => "1"; + public string Version => "2"; public string Name => "Comprare e tenere"; - public string Description => "Compra in parti uguali alla prima chiusura e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla."; + public string Description => "Compra in parti uguali alla prima chiusura di ogni strumento e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla."; public IReadOnlyList Parameters => []; @@ -123,8 +126,8 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily public IReadOnlyList Parameters => [ - new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m), - new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m), + new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m, Whole: true), + new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m, Whole: true), ]; public bool Accepts(StrategyParameters parameters) diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index 5ac5241..24bd73d 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -185,8 +185,11 @@ public interface IStrategy IReadOnlyList Decide(StrategyContext context); } -/// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results). -public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max); +/// +/// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results). +/// parameters take only whole numbers, such as a number of days. +/// +public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max, bool Whole = false); /// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. public interface IStrategyFamily diff --git a/tests/Anubis.Tests/BacktestTests.cs b/tests/Anubis.Tests/BacktestTests.cs index 46038fd..32b9605 100644 --- a/tests/Anubis.Tests/BacktestTests.cs +++ b/tests/Anubis.Tests/BacktestTests.cs @@ -222,6 +222,28 @@ public sealed class BacktestTests Assert.IsEmpty(run.Decisions[0].Final); } + [TestMethod] + [TestCategory(Category.Unit)] + public void BuyAndHoldKeepsTheShareOfAnInstrumentWhoseHistoryStartsLater() + { + // ETH has bars only from day 30: buy and hold buys it then, with half the equity, not never. + var data = new BacktestDataset( + [ + new BacktestInstrument(BacktestData.Btc(), BacktestData.Walk(60, 3, start: 40_000, from: D1)), + new BacktestInstrument(BacktestData.Btc() with { Symbol = "ETH-EUR", BaseCurrency = "ETH" }, BacktestData.Walk(30, 5, start: 2_000, from: D1.AddDays(30))), + ], "EUR"); + var run = BacktestEngine.Run(new BuyAndHold(2), data); + Assert.HasCount(2, run.Fills); + var btc = run.Fills.Single(f => f.Symbol == "BTC-EUR"); + var eth = run.Fills.Single(f => f.Symbol == "ETH-EUR"); + Assert.AreEqual(D1.AddDays(1), btc.Day); + Assert.AreEqual(D1.AddDays(31), eth.Day); + Assert.AreEqual(0.4975, (double)(btc.Gross / run.InitialCapital), 0.005); + var before = run.Equity.Single(p => p.Day == D1.AddDays(30)).Equity; + Assert.AreEqual(0.4975, (double)(eth.Gross / before), 0.01); + Assert.IsTrue(run.Equity.All(e => e.Cash >= 0m)); + } + [TestMethod] [TestCategory(Category.Unit)] public void OneCycleRestartsFromARecordedBook() diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs index 784bea2..b096892 100644 --- a/tests/Anubis.Tests/LaboratoryScreenTests.cs +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -62,6 +62,8 @@ public sealed class LaboratoryScreenTests StringAssert.Contains(compare, "Stessi dati per entrambi"); StringAssert.Contains(compare, "non si applica", "The second test has one variant: no PBO."); + StringAssert.Contains(await server.TextAsync("/laboratorio/confronto?a=nonunid&b=" + first), "Servono due test completati."); + using var missing = await server.GetAsync($"/laboratorio/{Guid.NewGuid()}"); StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato."); } diff --git a/tests/Anubis.Tests/LaboratoryTests.cs b/tests/Anubis.Tests/LaboratoryTests.cs index 4fc6a85..a39937f 100644 --- a/tests/Anubis.Tests/LaboratoryTests.cs +++ b/tests/Anubis.Tests/LaboratoryTests.cs @@ -116,8 +116,51 @@ public sealed class LaboratoryTests await stop.CancelAsync().ConfigureAwait(false); await Assert.ThrowsAsync(() => running).ConfigureAwait(false); Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(halfway.Id, CancellationToken.None).ConfigureAwait(false))!.Status); + + // A plan changed after it was written no longer gives its hash: the trial does not run. + var tampered = await lab.PlanAsync(Request(), CancellationToken.None).ConfigureAwait(false); + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", CancellationToken.None, ("h", "0"), ("id", tampered.Id)), + CancellationToken.None).ConfigureAwait(false); + await lab.ProcessAsync(tampered.Id, CancellationToken.None).ConfigureAwait(false); + var refused = (await lab.Trials.GetAsync(tampered.Id, CancellationToken.None).ConfigureAwait(false))!; + Assert.IsFalse(refused.PlanIntact); + Assert.AreEqual(TrialStatuses.Failed, refused.Status); + StringAssert.Contains(refused.Error, "impronta"); } + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheQueueOutlivesTheDatabaseGoingAway() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + await SeedBitcoinAsync(test, clock, 60).ConfigureAwait(false); + using var lab = new Laboratory(test.Db, clock, Path.GetTempPath()); + var trial = await lab.PlanAsync(Request(), CancellationToken.None).ConfigureAwait(false); + + // The table is out of reach: every read and write of the queue fails, as when the database restarts. + await RenameAsync(test, "backtest_trials", "backtest_trials_away").ConfigureAwait(false); + using var stop = new CancellationTokenSource(); + var running = lab.RunAsync(stop.Token); + await Task.Delay(300).ConfigureAwait(false); + Assert.IsFalse(running.IsCompleted, "An error of the database does not stop the laboratory."); + + await RenameAsync(test, "backtest_trials_away", "backtest_trials").ConfigureAwait(false); + for (var i = 0; i < 600 && !(await lab.Trials.GetAsync(trial.Id, CancellationToken.None).ConfigureAwait(false))!.IsFinished; i++) + { + clock.Advance(Laboratory.RetryDelay); + await Task.Delay(50).ConfigureAwait(false); + } + + await stop.CancelAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(() => running).ConfigureAwait(false); + var done = (await lab.Trials.GetAsync(trial.Id, CancellationToken.None).ConfigureAwait(false))!; + Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error); + } + + private static Task RenameAsync(TestDb test, string from, string to) => + test.Db.WriteAsync(s => s.ExecuteAsync($"ALTER TABLE {from} RENAME TO {to}", CancellationToken.None), CancellationToken.None); + [TestMethod] [TestCategory(Category.Unit)] public void RequestsOutsideTheRulesAreRefusedBeforeAnythingIsWritten() @@ -127,6 +170,12 @@ public sealed class LaboratoryTests Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with { To = From }, now)); Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with { Symbols = [" "] }, now)); Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with { InitialCapital = 0m }, now)); + Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with { InitialCapital = 0.5m }, now)); + var half = Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with + { + Grid = new Dictionary> { ["fast"] = [10m, 10.5m] }, + }, now)); + StringAssert.Contains(half.Message, "numeri interi", "10,5 days would run as 10 and count twice in the DSR."); var outOfRange = Assert.ThrowsExactly(() => Laboratory.BuildPlan(Request() with { Grid = new Dictionary> { ["fast"] = [1m] },