diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index cf6e46f..56e6b63 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -1,4 +1,5 @@ using Anubis.Access; +using Anubis.Backtest; using Anubis.Core; using Anubis.Data; using Anubis.Db; @@ -37,7 +38,7 @@ internal sealed record HostChanged(HostMode Mode); /// Everything that needs the database, built once it is reachable and the installation checks out. internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler, - MarketDataService? MarketData = null, TradingService? Trading = null); + MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null); /// /// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured @@ -65,6 +66,7 @@ internal sealed partial class AnubisHost( private CancellationTokenSource? _schedulerStop; private MarketDataService? _market; private TradingService? _trading; + private Laboratory? _lab; private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0); private volatile AppServices? _services; @@ -292,7 +294,9 @@ internal sealed partial class AnubisHost( ? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId, overrides?.MarketHttp, overrides?.MarketSockets, logger) : null; - _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading); + // 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); + _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab); StartScheduler(scheduler, backups); SetStatus(HostMode.Ready, null); } @@ -426,12 +430,14 @@ internal sealed partial class AnubisHost( var token = _schedulerStop.Token; var market = _market; var trading = _trading; + var lab = _lab; _schedulerLoop = Task.Run(async () => { using var runs = bus.Subscribe(); var recorder = RecordJobsAsync(runs, token); var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token); var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token); + var testing = lab is null ? Task.CompletedTask : RunLabAsync(lab, token); try { await scheduler.RunAsync(token).ConfigureAwait(false); @@ -442,6 +448,7 @@ internal sealed partial class AnubisHost( await collecting.ConfigureAwait(false); await dealing.ConfigureAwait(false); + await testing.ConfigureAwait(false); await recorder.ConfigureAwait(false); }, CancellationToken.None); } @@ -461,6 +468,21 @@ internal sealed partial class AnubisHost( } } + private async Task RunLabAsync(Laboratory lab, CancellationToken cancellationToken) + { + try + { + await lab.RunAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + LogLabFailed(logger, ex); + } + } + private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken) { try @@ -532,6 +554,8 @@ internal sealed partial class AnubisHost( _market = null; _trading?.Dispose(); _trading = null; + _lab?.Dispose(); + _lab = null; } // Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5). @@ -571,6 +595,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")] private static partial void LogMarketDataFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Laboratory stopped")] + private static partial void LogLabFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Trading stopped")] private static partial void LogTradingFailed(ILogger logger, Exception exception); diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 4d3bab2..2e81dd9 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -256,6 +256,7 @@ textarea { .form { display: flex; flex-direction: column; gap: 8px; max-width: 420px; } .form label { font-weight: 550; margin-top: 6px; } .form .btn { align-self: flex-start; margin-top: 10px; } +.form fieldset { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; } .form-inline { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 8px 0; } .form-inline label { min-width: 80px; font-weight: 550; } .row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } @@ -349,6 +350,8 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .account-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; } .account-head h2 { display: flex; align-items: center; gap: 10px; } .tag { padding: 2px 8px; border-radius: 6px; background: var(--surface-2); color: var(--text-2); font-size: 13px; font-weight: 500; line-height: 20px; } +.tag.gain { background: var(--gain-bg); color: var(--gain); } +.tag.loss { background: var(--loss-bg); color: var(--loss); } .link-state { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13.5px; } .link-state.down .dot { background: var(--loss); } .account-value { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin: 14px 0 12px; } diff --git a/src/Anubis.Server/Components/EquityChart.razor b/src/Anubis.Server/Components/EquityChart.razor index 7d32e9c..3039dcb 100644 --- a/src/Anubis.Server/Components/EquityChart.razor +++ b/src/Anubis.Server/Components/EquityChart.razor @@ -5,8 +5,8 @@ HTML placed in percent, so nothing gets distorted at any width. *@ @if (Points.Count >= 2) { - var values = Points.Select(p => Shell.Convert(p.Equity, Currency)).ToList(); - var bench = Points.Select(p => p.Benchmark is { } b ? Shell.Convert(b, Currency) : (decimal?)null).ToList(); + var values = Points.Select(p => Value(p.Equity)).ToList(); + var bench = Points.Select(p => p.Benchmark is { } b ? Value(b) : (decimal?)null).ToList(); var all = values.Concat(bench.OfType()).ToList(); var (lo, hi, step) = Scale(all.Min(), all.Max()); double X(int i) => i * 1000.0 / (Points.Count - 1); @@ -15,7 +15,7 @@ var equityLine = Line(values.Select((v, i) => (i, v))); var benchLine = Line(bench.Select((v, i) => (i, v)).Where(p => p.v is not null).Select(p => (p.i, p.v!.Value))); var last = values[^1]; -
+
- Con Anubis + @EquityLabel @if (benchLine.Length > 0) { - Senza bot: Bitcoin e S&P 500 comprati e tenuti + @BenchmarkLabel }
Vedi i numeri in una tabella
- + @foreach (var p in Points.AsEnumerable().Reverse()) { - + }
GiornoCon il botSenza bot
Giorno@EquityColumn@BenchmarkColumn
@Format.LongDate(p.Day)@Shell.Money(p.Equity, Currency)@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")
@Format.LongDate(p.Day)@Text(p.Equity)@(p.Benchmark is { } b ? Text(b) : "—")
@@ -79,6 +79,29 @@ [Parameter] public string Currency { get; set; } = "EUR"; + /// True when the amounts are already in (a backtest report): no conversion from euro. + [Parameter] + public bool Native { get; set; } + + [Parameter] + public string Label { get; set; } = "Patrimonio nel tempo, con il bot e senza"; + + [Parameter] + public string EquityLabel { get; set; } = "Con Anubis"; + + [Parameter] + public string BenchmarkLabel { get; set; } = "Senza bot: Bitcoin e S&P 500 comprati e tenuti"; + + [Parameter] + public string EquityColumn { get; set; } = "Con il bot"; + + [Parameter] + public string BenchmarkColumn { get; set; } = "Senza bot"; + + private decimal Value(decimal amount) => Native ? amount : Shell.Convert(amount, Currency); + + private string Text(decimal amount, int decimals = 2) => Native ? Format.Money(amount, Currency, decimals: decimals) : Shell.Money(amount, Currency, decimals: decimals); + private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture); private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%"; diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor index de56aad..688cc29 100644 --- a/src/Anubis.Server/Components/Pages/Laboratorio.razor +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -1,5 +1,239 @@ +@inherits LoadedComponent @page "/laboratorio" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Backtest +@using Anubis.Data +@using Anubis.Strategies Laboratorio · Anubis -Il laboratorio dei test sul passato arriva con il motore dei backtest. +@if (_running) +{ + +} + +@if (_message is { } message) +{ + +} + +@if (_lab is null) +{ + Nella modalità dimostrativa i test sul passato non partono: avvia Anubis normalmente per provare una strategia. +} + +
+
+

Test eseguiti

+ @if (_trials.Count(t => t.Status == TrialStatuses.Done) >= 2) + { +
+ + + + + +
+ } +
+ @if (_trials.Count == 0) + { +
+

Nessun test eseguito.

+

Ogni test prova una strategia su un periodo passato, con tutte le combinazioni della sua griglia di parametri, costi realistici e poi doppi e tripli, e le convalide del protocollo anti-illusioni. Il piano si scrive prima di vedere i risultati e resta nel registro.

+
+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var t in _trials) + { + var s = t.Summary; + + + + + + + + + + + + } + +
PianificatoStrategiaDatiVariantiStatoEsitoRisultato nettoSharpeCalo massimo
@Format.ShortDate(t.CreatedAt, Shell.Now, Shell.Zone)@Name(t.Strategy)@LabText.Symbols(t.Plan.Data.Symbols)
@LabText.Period(t.Plan.Data.From, t.Plan.Data.To)
@t.Variants@LabText.Status(t, _lab?.Progress(t.Id)) + @if (t.Verdict is { } verdict) + { + @LabText.Verdict(verdict) + } + else + { + @LabText.Missing + } + @(s is null ? LabText.Missing : LabText.Money(s.NetResult, s.Currency, withSign: true))@(s is null ? LabText.Missing : LabText.Number(s.Sharpe))@(s is null ? LabText.Missing : LabText.Percent(s.MaxDrawdown))
+
+ } +
+ +@if (_lab is not null) +{ + var family = _family; +
+
+

Nuovo test

+ +
+

@family.Description

+
+ + + + + + + + +

Simboli del mercato scelto: BTC-EUR su OKX, AAPL su Alpaca, BTCUSDT nello storico di ricerca. @Research()

+
+
+ + +
+
+ + +
+
+ + + @if (family.Parameters.Count > 0) + { +
+ Griglia dei parametri + @foreach (var p in family.Parameters) + { + + v.ToString(CultureInfo.InvariantCulture)))" /> +

Da @p.Min.ToString(CultureInfo.InvariantCulture) a @p.Max.ToString(CultureInfo.InvariantCulture), valori separati da virgole; ogni combinazione è una variante.

+ } +
+ } +

Soglie del protocollo, fissate nel piano: risultato netto positivo anche con costi doppi, Deflated Sharpe Ratio almeno 0,90, probabilità di sovra-adattamento non oltre 0,40 con più varianti, calo massimo non oltre il 25%.

+ + +
+} + +
+

Migliorie in osservazione

+
+

Nessuna miglioria in osservazione.

+

Le modifiche che potrebbero migliorare il risultato o ridurre i costi si calcolano in ombra accanto alle regole in vigore e compaiono qui con l'effetto che avrebbero avuto. Arrivano con la Fase 9.

+
+
+ +
+

Stime di costo da confermare

+
+

Nessuna stima da confermare.

+

Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma. Arrivano con la Fase 8.

+
+
+ +@code { + private Laboratory? _lab; + private IReadOnlyList _trials = []; + private IStrategyFamily _family = StrategyCatalog.All[0]; + private bool _running; + private string? _message; + private DateOnly _from; + private DateOnly _to; + private IReadOnlyList _research = []; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "strategia")] + public string? Strategia { get; set; } + + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + _lab = services.Lab; + _trials = await new TrialStore(services.Db, Clock).ListAsync(100, ct); + _running = _trials.Any(t => !t.IsFinished); + _family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0]; + var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime); + _to = today.AddDays(-1); + _from = _to.AddYears(-3); + _research = new ResearchStore(Host.Config.Data.Research).Series() + .Where(s => s.Timeframe == Timeframes.Day) + .Select(s => s.Symbol) + .Order(StringComparer.Ordinal) + .ToList(); + _message = Errore switch + { + null => null, + "motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.", + TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.", + TrialRequestErrors.Source => "Scegli da dove prendere i dati e, per le barre raccolte, il mercato.", + TrialRequestErrors.Symbols => $"Indica da 1 a {Laboratory.MaxSymbols} strumenti, separati da virgole.", + TrialRequestErrors.Dates => "Controlla le date: l'inizio deve venire prima della fine.", + TrialRequestErrors.Capital => "Il capitale iniziale deve essere un importo tra 1 e 10.000.000.", + TrialRequestErrors.Grid => "Un valore della griglia non si legge o è fuori dall'intervallo del parametro: usa numeri separati da virgole, con il punto per i decimali.", + TrialRequestErrors.Combinations => $"La griglia non dà combinazioni valide, oppure ne dà più di {Laboratory.MaxVariants}: restringila.", + _ => "Non è stato possibile avviare il test: riprova.", + }; + } + + private string Research() => _research.Count == 0 + ? "Lo storico di ricerca è vuoto: lo riempie la raccolta dei dati." + : "Nello storico di ricerca: " + LabText.Symbols(_research) + "."; + + private static string Name(string strategy) => StrategyCatalog.Find(strategy)?.Name ?? strategy; + + private string Title(Trial t) => $"{Name(t.Strategy)}, {LabText.Symbols(t.Plan.Data.Symbols)}, {Format.ShortDate(t.CreatedAt, Shell.Now, Shell.Zone)}"; +} diff --git a/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor b/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor new file mode 100644 index 0000000..c2ba41a --- /dev/null +++ b/src/Anubis.Server/Components/Pages/LaboratorioConfronto.razor @@ -0,0 +1,105 @@ +@inherits LoadedComponent +@page "/laboratorio/confronto" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Backtest +@using Anubis.Strategies + +Confronto tra test · Anubis + +

← Laboratorio

+ +@if (_a is null || _b is null) +{ + Scegli due test conclusi dall'elenco del Laboratorio. + return; +} + +@{ + var a = _a.Value; + var b = _b.Value; + var ra = a.Report; + var rb = b.Report; +} +
+

Confronto tra due test

+ @if (ra.DataFingerprint != rb.DataFingerprint) + { +

I due test hanno letto dati diversi (strumenti, periodo o valuta): il confronto è indicativo.

+ } + else + { +

Stessi dati per entrambi: le differenze vengono dalla strategia, dalla griglia o dalle soglie.

+ } +
+ + + + + + + + + + @Row("Esito", x => LabText.Verdict(x.Trial.Verdict)) + @Row("Dati", x => LabText.Symbols(x.Trial.Plan.Data.Symbols) + ", " + LabText.Period(x.Trial.Plan.Data.From, x.Trial.Plan.Data.To)) + @Row("Variante scelta", x => LabText.Parameters(x.Report.Chosen) + $" (di {x.Trial.Variants})") + @Row("Risultato netto", x => LabText.Money(x.Report.Metrics.NetResult, x.Report.Currency, withSign: true)) + @Row("Con costi doppi", x => x.Report.Costs.FirstOrDefault(k => k.Multiplier == 2m) is { } k ? LabText.Money(k.NetResult, x.Report.Currency, withSign: true) : LabText.Missing) + @Row("Rendimento annuo", x => LabText.Percent(x.Report.Metrics.AnnualReturn, 1, true)) + @Row("Comprare e tenere, annuo", x => LabText.Percent(x.Report.Benchmark.AnnualReturn, 1, true)) + @Row("Volatilità annua", x => LabText.Percent(x.Report.Metrics.Volatility)) + @Row("Sharpe annuo", x => LabText.Number(x.Report.Metrics.Sharpe)) + @Row("Calo massimo", x => LabText.Percent(x.Report.Metrics.MaxDrawdown)) + @Row("Operazioni chiuse", x => x.Report.Metrics.Trades.ToString(CultureInfo.InvariantCulture)) + @Row("Operazioni in guadagno", x => x.Report.Metrics.Trades == 0 ? LabText.Missing : LabText.Percent(x.Report.Metrics.WinRate, 0)) + @Row("Rapporto guadagni/perdite", x => LabText.Number(x.Report.Metrics.ProfitFactor)) + @Row("Deflated Sharpe Ratio", x => LabText.Number(x.Report.DeflatedSharpe.Value)) + @Row("Probabilità di sovra-adattamento", x => x.Report.Overfitting is { } p ? LabText.Number(p.Probability) : "non si applica") + @Row("Finestre che avanzano, rendimento", x => x.Report.WalkForward is { } w ? LabText.Percent(w.Return, 1, true) : LabText.Missing) + @Row("Decisioni cambiate dai dati futuri", x => x.Report.LookAhead.Changed.ToString(CultureInfo.InvariantCulture)) + +
@Name(a)@Name(b)
+
+
+ +@code { + private (Trial Trial, BacktestReport Report)? _a; + private (Trial Trial, BacktestReport Report)? _b; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "a")] + public Guid? A { get; set; } + + [SupplyParameterFromQuery(Name = "b")] + public Guid? B { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var store = new TrialStore(Host.Services!.Db, Clock); + _a = await ReadAsync(store, A, ct); + _b = await ReadAsync(store, B, ct); + } + + private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, Guid? id, CancellationToken ct) + { + if (id is not { } key || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json) + { + return null; + } + + return (trial, BacktestReport.FromJson(json)); + } + + private string Name((Trial Trial, BacktestReport Report) x) => + $"{StrategyCatalog.Find(x.Trial.Strategy)?.Name ?? x.Trial.Strategy}, {Format.ShortDate(x.Trial.CreatedAt, Shell.Now, Shell.Zone)}"; + + private RenderFragment Row(string label, Func<(Trial Trial, BacktestReport Report), string> value) => __builder => + { + @label@value(_a!.Value)@value(_b!.Value) + }; +} diff --git a/src/Anubis.Server/Components/Pages/LaboratorioProva.razor b/src/Anubis.Server/Components/Pages/LaboratorioProva.razor new file mode 100644 index 0000000..723ebc7 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/LaboratorioProva.razor @@ -0,0 +1,336 @@ +@inherits LoadedComponent +@page "/laboratorio/{Id:guid}" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Backtest +@using Anubis.Strategies + +Test del laboratorio · Anubis + +@if (_trial is null) +{ + Torna al Laboratorio per l'elenco dei test. + return; +} + +@{ + var t = _trial; + var plan = t.Plan; + var r = _report; +} +@if (!t.IsFinished) +{ + +} + +

← Laboratorio

+ +
+
+

@Name(t.Strategy) su @LabText.Symbols(plan.Data.Symbols)

+ @if (t.Verdict is { } verdict) + { + @LabText.Verdict(verdict) + } + else + { + @LabText.Status(t, _progress) + } +
+
+
Dati
+
@LabText.Source(plan.Data), @LabText.Period(plan.Data.From, plan.Data.To)
+
Varianti provate
+
@t.Variants (@string.Join("; ", plan.Grid.Select(g => g.Key + " " + string.Join(", ", g.Value.Select(v => v.ToString(CultureInfo.InvariantCulture))))))
+
Capitale iniziale
+
@(r is null ? Format.Number(plan.InitialCapital, 2) : Format.Money(plan.InitialCapital, r.Currency))
+
Piano scritto
+
@Format.LongDateTime(t.CreatedAt, Shell.Zone), prima dei risultati. Impronta @Short(t.PlanHash)
+ @if (t.FinishedAt is { } finished) + { +
Concluso
+
@Format.LongDateTime(finished, Shell.Zone)@(r is null ? "" : $", in {LabText.Number(r.Seconds, 1)} secondi")
+ } +
+ @if (t.Status == TrialStatuses.Failed) + { + + } + else if (!t.IsFinished) + { +

@(t.Status == TrialStatuses.Planned ? "In coda: parte appena finisce il test precedente." : "In corso" + (_progress is null ? "." : ": " + _progress + ".")) La pagina si aggiorna da sola.

+ } +
+ +@if (r is not null) +{ + var c = r.Currency; + var m = r.Metrics; + var b = r.Benchmark; +
+

Esito del protocollo

+

Variante scelta: @LabText.Parameters(r.Chosen), la migliore zona della griglia e non il singolo punto migliore.

+
+ + + + @foreach (var check in r.Checks) + { + + + + + + + } + +
ControlloValoreSogliaEsito
@check.Name@LabText.CheckValue(check, c)@LabText.CheckThreshold(check, c) + @switch (check.Passed) + { + case true: + Superato + break; + case false: + Non superato + break; + default: + Non si applica + break; + } +
+
+
+ +
+

Risultato della variante scelta

+
+ + + + + + + + + + + + + + + + +
Variante sceltaComprare e tenere
Risultato netto@LabText.Money(m.NetResult, c, withSign: true)@LabText.Money(b.NetResult, c, withSign: true)
Rendimento totale@LabText.Percent(m.TotalReturn, 1, true)@LabText.Percent(b.TotalReturn, 1, true)
Rendimento annuo@LabText.Percent(m.AnnualReturn, 1, true)@LabText.Percent(b.AnnualReturn, 1, true)
Volatilità annua@LabText.Percent(m.Volatility)@LabText.Percent(b.Volatility)
Sharpe annuo@LabText.Number(m.Sharpe)@LabText.Number(b.Sharpe)
Calo massimo@LabText.Percent(m.MaxDrawdown)@LabText.Percent(b.MaxDrawdown)
Operazioni chiuse@m.Trades@LabText.Missing
Operazioni in guadagno@(m.Trades == 0 ? LabText.Missing : LabText.Percent(m.WinRate, 0))@LabText.Missing
Rapporto guadagni/perdite@(m.ProfitFactor is { } pf ? LabText.Number(pf) : m.Trades > 0 ? "nessuna perdita" : LabText.Missing)@LabText.Missing
Guadagno e perdita medi@LabText.Money(m.AverageWin, c, true) / @LabText.Money(m.AverageLoss, c, true)@LabText.Missing
Commissioni@LabText.Money(m.Fees, c)@LabText.Money(b.Fees, c)
Tempo investito, in media@LabText.Percent(m.Exposure, 0)@LabText.Percent(b.Exposure, 0)
+
+ +
+ +
+

Risultato per anno

+
+ + + + @foreach (var y in m.Years) + { + var bh = b.Years.FirstOrDefault(x => x.Year == y.Year); + + } + +
AnnoRisultatoRendimentoComprare e tenere
@y.Year@LabText.Money(y.Result, c, true)@LabText.Percent(y.Return, 1, true)@(bh is null ? LabText.Missing : LabText.Percent(bh.Return, 1, true))
+
+
+ +
+

Sensibilità ai costi

+

Commissioni e scostamento moltiplicati: una strategia che muore con i costi doppi non passa.

+
+ + + + @foreach (var k in r.Costs) + { + + } + +
CostiRisultato nettoRendimentoSharpeCalo massimoCommissioni
@(k.Multiplier == 1m ? "realistici" : $"× {Format.Number(k.Multiplier)}")@LabText.Money(k.NetResult, c, true)@LabText.Percent(k.TotalReturn, 1, true)@LabText.Number(k.Sharpe)@LabText.Percent(k.MaxDrawdown)@LabText.Money(k.Fees, c)
+
+
+ +
+

Convalide

+

Sharpe corretto per il numero di prove

+ @{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); } +

Deflated Sharpe Ratio @LabText.Number(d.Value): la probabilità che lo Sharpe della variante scelta (@LabText.Number(d.Sharpe * annual) all'anno) superi quello che il migliore di @d.Trials tentativi mostrerebbe per caso (@LabText.Number(d.Benchmark * annual) all'anno). Contati tutti i test di questa strategia: @r.TrialsCounted varianti. Su @d.Observations sedute, asimmetria @LabText.Number(d.Skewness), curtosi @LabText.Number(d.Kurtosis).

+ +

Probabilità di sovra-adattamento

+ @if (r.Overfitting is { } pbo) + { +

PBO @LabText.Number(pbo.Probability): in @Format.Number(pbo.Combinations) divisioni del periodo in due metà, la quota di volte in cui la variante migliore in una metà è finita nella metà peggiore dell'altra. Con @pbo.Variants varianti e @pbo.Groups blocchi.

+ } + else + { +

Con una sola variante non c'è nulla da scegliere, quindi nulla da sovra-adattare: il controllo non si applica.

+ } + +

Finestre che avanzano

+ @if (r.WalkForward is { } wf) + { +

Ogni finestra sceglie la variante sui dati precedenti e la giudica su quelli successivi, mai visti. Rendimento fuori campione complessivo @LabText.Percent(wf.Return, 1, true), Sharpe @LabText.Number(wf.Sharpe * annual) all'anno; @wf.Purge sedute tolte tra addestramento e prova.

+
+ + + + @foreach (var w in wf.Windows) + { + + } + +
FinestraScelta suProvata suVarianteRendimentoSharpe
@w.Window@LabText.Period(w.TrainFrom, w.TrainTo)@LabText.Period(w.TestFrom, w.TestTo)@LabText.Parameters(w.Chosen)@LabText.Percent(w.Return, 1, true)@LabText.Number(w.Sharpe * annual)
+
+ } + else + { +

Periodo troppo breve per le finestre.

+ } + +

K-fold purgato combinatorio

+ @if (r.Combinatorial is { } cv) + { +

@cv.Groups blocchi, @cv.TestGroups alla volta in prova: @cv.Splits divisioni e @cv.PathSharpes.Count percorsi completi fuori campione, con @cv.Purge sedute tolte prima di ogni blocco di prova e @cv.Embargo dopo. Sharpe medio dei percorsi @LabText.Number(cv.MeanSharpe * annual) all'anno, il peggiore @LabText.Number(cv.WorstSharpe * annual); percorsi in positivo @LabText.Percent(cv.PositiveShare, 0).

+ } + else + { +

Periodo troppo breve per i blocchi.

+ } + +

Nessuno sguardo in avanti

+

+ Il test è stato rifatto con i dati tagliati al @string.Join(", ", r.LookAhead.Cutoffs.Select(x => LabText.Day(x))): delle @r.LookAhead.Decisions decisioni confrontate, + @(r.LookAhead.Changed == 0 ? "nessuna è cambiata." : $"{r.LookAhead.Changed} sono cambiate: la strategia guarda dati che al momento della decisione non esistevano.") +

+ @if (r.LookAhead.Examples.Count > 0) + { +
    + @foreach (var e in r.LookAhead.Examples) + { +
  • @e
  • + } +
+ } +
+ +
+

Tutte le varianti

+

Ogni variante vale il suo Sharpe, ma non più della media della sua zona (lei e le vicine nella griglia): si preferisce una collina larga a un picco isolato.

+
+ + + + @foreach (var v in r.Variants) + { + + + + + + + + + } + +
ParametriSharpe annuoPunteggio di zonaRisultato nettoCalo massimoOperazioni
@LabText.Parameters(v.Parameters)@if (v.Chosen) { scelta}@LabText.Number(v.Sharpe * annual)@LabText.Number(v.PlateauScore * annual)@LabText.Money(v.NetResult, c, true)@LabText.Percent(v.MaxDrawdown)@v.Trades
+
+
+ +
+

Cosa questo test non considera

+
    + @foreach (var l in r.Limitations) + { +
  • @l
  • + } +
+ @if (r.Notes.Count > 0) + { +

Ordini non eseguiti come chiesto

+
    + @foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value)) + { +
  • @LabText.Note(reason): @count
  • + } +
+ } +

Dati usati

+
+ + + + @foreach (var i in r.Instruments) + { + + } + +
StrumentoOriginePeriodoBarreAzioni societarie
@i.Symbol@i.Source@LabText.Day(i.First) – @LabText.Day(i.Last)@i.Bars@i.Actions
+
+

Impronta dei dati @Short(r.DataFingerprint): due test con la stessa impronta hanno letto esattamente gli stessi dati. Motore versione @plan.Engine, strategia versione @r.StrategyVersion.

+
+ + @if (r.Trades.Count > 0) + { +
+

Operazioni della variante scelta

+
+ Vedi le ultime @r.Trades.Count operazioni +
+ + + + @foreach (var tr in r.Trades.Reverse()) + { + + } + +
StrumentoApertaChiusaInvestitoRisultatoCommissioni
@tr.Symbol@LabText.Day(tr.Opened)@(tr.Closed is { } closed ? LabText.Day(closed) : "aperta")@LabText.Money(tr.Invested, c)@LabText.Money(tr.Result, c, true)@LabText.Money(tr.Fees, c)
+
+
+
+ } +} + +@code { + private Trial? _trial; + private BacktestReport? _report; + private string? _progress; + private IReadOnlyList _curve = []; + + [Parameter] + public Guid Id { get; set; } + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + var store = new TrialStore(services.Db, Clock); + _trial = await store.GetAsync(Id, ct); + if (_trial is null) + { + return; + } + + _progress = services.Lab?.Progress(Id); + if (await store.ReportJsonAsync(Id, ct) is { } json) + { + _report = BacktestReport.FromJson(json); + _curve = _report.Curve.Select(p => new Anubis.Server.EquityPoint(new DateTimeOffset(p.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), p.Day, p.Equity, p.Benchmark)).ToList(); + } + } + + private static string Name(string strategy) => StrategyCatalog.Find(strategy)?.Name ?? strategy; + + private static string Short(string hash) => hash.Length > 12 ? hash[..12] : hash; +} diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 816fd1e..e13a5ed 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -34,6 +34,7 @@ internal static partial class Forms signed.MapPost("/chiavi/{broker}", SaveKeysAsync); signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); signed.MapPost("/capitale/{broker}", SetCapitalAsync); + signed.MapPost("/laboratorio", PlanTrialAsync); } private static string Back(IFormCollection form, string fallback) @@ -324,6 +325,93 @@ internal static partial class Forms return Results.Redirect(back + "?ok=capitale#conti"); } + /// + /// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it. + /// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address. + /// + private static async Task PlanTrialAsync(IFormCollection form, AnubisHost host, CancellationToken ct) + { + var family = Anubis.Strategies.StrategyCatalog.Find(form["strategia"].ToString()); + string Back(string code) => "/laboratorio?errore=" + code + (family is null ? "" : "&strategia=" + Uri.EscapeDataString(family.Id)) + "#nuovo"; + if (host.IsDemo || host.Services?.Lab is not { } lab) + { + return Results.Redirect(Back("motore")); + } + + if (family is null) + { + return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Strategy)); + } + + var source = form["origine"].ToString(); + var venue = source == Anubis.Backtest.TrialSources.Research ? Anubis.Data.Venues.Binance : form["mercato"].ToString(); + if (source == Anubis.Backtest.TrialSources.Database && venue is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) + { + return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Source)); + } + + if (ParseDay(form["dal"].ToString()) is not { } from || ParseDay(form["al"].ToString()) is not { } to) + { + return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Dates)); + } + + if (ParseEuro(form["capitale"].ToString()) is not { } capital) + { + return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Capital)); + } + + var grid = new Dictionary>(StringComparer.Ordinal); + foreach (var p in family.Parameters) + { + var text = form["griglia_" + p.Name].ToString(); + if (string.IsNullOrWhiteSpace(text)) + { + continue; + } + + if (ParseList(text) is not { } values) + { + return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Grid)); + } + + grid[p.Name] = values; + } + + var symbols = form["strumenti"].ToString() + .Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(x => x.ToUpperInvariant()) + .ToList(); + try + { + var trial = await lab.PlanAsync(new Anubis.Backtest.TrialRequest(family.Id, source, venue, symbols, from, to, capital, grid), ct).ConfigureAwait(false); + return Results.Redirect("/laboratorio/" + trial.Id.ToString("D")); + } + catch (Anubis.Backtest.TrialRequestException ex) + { + return Results.Redirect(Back(ex.Code)); + } + } + + private static DateOnly? ParseDay(string text) => + DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null; + + /// Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point. + internal static IReadOnlyList? ParseList(string text) + { + var result = new List(); + foreach (var item in (text ?? "").Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (!decimal.TryParse(item, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value)) + { + return null; + } + + result.Add(value); + } + + return result.Count is > 0 and <= 20 ? result : null; + } + /// An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50". internal static decimal? ParseEuro(string text) { diff --git a/src/Anubis.Server/LabText.cs b/src/Anubis.Server/LabText.cs new file mode 100644 index 0000000..97015f2 --- /dev/null +++ b/src/Anubis.Server/LabText.cs @@ -0,0 +1,88 @@ +using Anubis.Backtest; +using Anubis.Core; + +namespace Anubis.Server; + +/// How the laboratory pages write the numbers of a backtest, in plain Italian (SPEC 13.3). +internal static class LabText +{ + public const string Missing = "—"; + + /// A fraction as a percentage: 0,1234 is "12,3%". + public static string Percent(double? fraction, int decimals = 1, bool withSign = false) => + fraction is { } x && double.IsFinite(x) ? Format.Percent((decimal)(x * 100), decimals, withSign) : Missing; + + public static string Number(double? value, int decimals = 2) => + value is { } x && double.IsFinite(x) ? Format.Number((decimal)x, decimals) : Missing; + + public static string Money(decimal value, string currency, bool withSign = false) => Format.Money(value, currency, withSign); + + public static string Day(DateOnly? day) => day is { } d ? d.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) : Missing; + + public static string Period(DateOnly from, DateOnly to) => $"{Day(from)} – {Day(to)}"; + + /// Parameters as the user reads them: "fast=20;slow=100" becomes "fast 20, slow 100". + public static string Parameters(string text) => + string.IsNullOrEmpty(text) ? "nessun parametro" : string.Join(", ", text.Split(';').Select(p => p.Replace('=', ' ').Replace('.', ','))); + + public static string Status(Trial trial, string? progress) => trial.Status switch + { + TrialStatuses.Planned => "In coda", + TrialStatuses.Running => progress is null ? "In corso" : "In corso: " + progress, + TrialStatuses.Failed => "Non riuscito", + _ => "Completato", + }; + + public static string Verdict(string? verdict) => verdict switch + { + TrialVerdicts.Passed => "Superato", + TrialVerdicts.Rejected => "Non superato", + _ => Missing, + }; + + public static string Source(TrialData data) => data.Source == TrialSources.Research + ? "storico di ricerca " + Venue(data.Venue) + : "barre raccolte di " + Venue(data.Venue); + + public static string Venue(string venue) => venue switch + { + "okx" => "OKX", + "alpaca" => "Alpaca", + "binance" => "Binance", + _ => venue, + }; + + public static string Symbols(IReadOnlyList symbols) => + symbols.Count <= 4 ? string.Join(", ", symbols) : string.Join(", ", symbols.Take(3)) + $" e altri {symbols.Count - 3}"; + + /// The value of a check, written in its unit. + public static string CheckValue(ReportCheck check, string currency) => check.Value is not { } v + ? "non si applica" + : check.Unit switch + { + "money" => Format.Money((decimal)v, currency, withSign: true), + "percent" => Percent(v), + "count" => Format.Number((decimal)v), + _ => Number(v), + }; + + public static string CheckThreshold(ReportCheck check, string currency) => check.Comparison + " " + check.Unit switch + { + "money" => Format.Money((decimal)check.Threshold, currency), + "percent" => Percent(check.Threshold, 0), + "count" => Format.Number((decimal)check.Threshold), + _ => Number(check.Threshold), + }; + + /// What the engine did not do as asked, in words. + public static string Note(string reason) => reason switch + { + BacktestReasons.NoCash => "Acquisti ridotti per mancanza di liquidità", + BacktestReasons.NoPrice => "Ordini senza prezzo di apertura", + BacktestReasons.UnknownSymbol => "Strumenti chiesti dalla strategia ma assenti dai dati", + BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate", + BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita", + BacktestReasons.Dividend => "Dividendi incassati", + _ => "Ordini sotto il minimo dello strumento, non inviati", + }; +} diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 17e818e..1d6896b 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -21,8 +21,23 @@ public sealed record TrialRequest( decimal InitialCapital, IReadOnlyDictionary>? Grid = null); -/// A request the laboratory refuses, with the reason in Italian for the form. -public sealed class TrialRequestException(string message) : Exception(message); +/// A request the laboratory refuses: a short code for the address of the form, and the reason in Italian. +public sealed class TrialRequestException(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} + +/// Codes of . +public static class TrialRequestErrors +{ + public const string Strategy = "strategia"; + public const string Source = "origine"; + public const string Symbols = "strumenti"; + public const string Dates = "date"; + public const string Capital = "capitale"; + public const string Grid = "griglia"; + public const string Combinations = "combinazioni"; +} /// /// 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 @@ -70,31 +85,31 @@ public sealed partial class Laboratory : IDisposable public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now) { ArgumentNullException.ThrowIfNull(request); - var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException("Strategia sconosciuta."); + var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta."); if (request.Source is not (TrialSources.Database or TrialSources.Research)) { - throw new TrialRequestException("Origine dei dati sconosciuta."); + throw new TrialRequestException(TrialRequestErrors.Source, "Origine dei dati sconosciuta."); } var symbols = request.Symbols.Select(s => s.Trim()).Where(s => s.Length > 0).Distinct(StringComparer.Ordinal).ToList(); if (symbols.Count == 0) { - throw new TrialRequestException("Indica almeno uno strumento."); + throw new TrialRequestException(TrialRequestErrors.Symbols, "Indica almeno uno strumento."); } if (symbols.Count > MaxSymbols) { - throw new TrialRequestException($"Al massimo {MaxSymbols} strumenti per prova."); + throw new TrialRequestException(TrialRequestErrors.Symbols, $"Al massimo {MaxSymbols} strumenti per prova."); } if (request.From >= request.To) { - throw new TrialRequestException("La data di inizio deve venire prima di quella di fine."); + 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) { - throw new TrialRequestException("Il capitale iniziale deve essere tra 1 e 10.000.000."); + throw new TrialRequestException(TrialRequestErrors.Capital, "Il capitale iniziale deve essere tra 1 e 10.000.000."); } var grid = new SortedDictionary>(StringComparer.Ordinal); @@ -103,7 +118,7 @@ public sealed partial class Laboratory : IDisposable var values = request.Grid?.GetValueOrDefault(p.Name) is { Count: > 0 } given ? given : p.Grid; if (values.Any(x => x < p.Min || x > p.Max)) { - throw new TrialRequestException(string.Create(CultureInfo.GetCultureInfo("it-IT"), $"{p.Label}: i valori vanno da {p.Min} a {p.Max}.")); + throw new TrialRequestException(TrialRequestErrors.Grid, string.Create(CultureInfo.GetCultureInfo("it-IT"), $"{p.Label}: i valori vanno da {p.Min} a {p.Max}.")); } grid[p.Name] = [.. values.Distinct().Order()]; @@ -123,12 +138,12 @@ public sealed partial class Laboratory : IDisposable var variants = ParameterGrid.Of(family, plan.Grid).Count; if (variants == 0) { - throw new TrialRequestException("Nessuna combinazione dei parametri è valida."); + throw new TrialRequestException(TrialRequestErrors.Combinations, "Nessuna combinazione dei parametri è valida."); } if (variants > MaxVariants) { - throw new TrialRequestException($"Troppe combinazioni ({variants}): al massimo {MaxVariants}."); + throw new TrialRequestException(TrialRequestErrors.Combinations, $"Troppe combinazioni ({variants}): al massimo {MaxVariants}."); } return (plan, variants); @@ -208,7 +223,7 @@ public sealed partial class Laboratory : IDisposable ?? throw new InvalidOperationException($"Strumento sconosciuto: {symbol} su {data.Venue}."); var daily = await bars.DailyAsync(instrument.Id, data.From, data.To, cancellationToken).ConfigureAwait(false); var events = instrument.IsCrypto ? [] : await actions.ForSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); - instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.From && a.ExDate <= data.To)], "database")); + instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.From && a.ExDate <= data.To)], "barre raccolte")); } } else @@ -224,7 +239,7 @@ public sealed partial class Laboratory : IDisposable daily.Add(new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, (double)b.Close, (double)b.Volume)); } - instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, "storico di ricerca " + data.Venue)); + instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, "storico di ricerca")); } } diff --git a/src/Anubis/Backtest/Metrics.cs b/src/Anubis/Backtest/Metrics.cs index ebb947e..053013f 100644 --- a/src/Anubis/Backtest/Metrics.cs +++ b/src/Anubis/Backtest/Metrics.cs @@ -63,7 +63,8 @@ public sealed record BacktestMetrics( var losses = closed.Where(t => t.Result <= 0m).ToList(); var gains = wins.Sum(t => t.Result); var lost = -losses.Sum(t => t.Result); - double? profitFactor = lost > 0m ? (double)(gains / lost) : gains > 0m ? null : 0d; + // Gains over losses of the closed trades; no value without a losing trade (nothing to divide by). + double? profitFactor = lost > 0m ? (double)(gains / lost) : null; var exposure = equity.Count > 0 ? equity.Average(p => p.Equity > 0m ? (double)(p.Invested / p.Equity) : 0d) diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs new file mode 100644 index 0000000..784bea2 --- /dev/null +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -0,0 +1,137 @@ +using System.Net; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Server; + +namespace Anubis.Tests; + +/// The Laboratorio screen (issue #36): a new test from the form, its report, the comparison. +[TestClass] +public sealed class LaboratoryScreenTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheReportOpensFromTheLaboratory() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var db = server.Host.Services!.Db; + var btc = await new InstrumentCatalog(db, SystemClock.Instance).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None); + await new BarStore(db, SystemClock.Instance).UpsertDailyAsync(btc.Id, + BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)), "test", CancellationToken.None); + + var empty = await server.TextAsync("/laboratorio"); + StringAssert.Contains(empty, "Nessun test eseguito."); + StringAssert.Contains(empty, "Scrivi il piano e avvia il test"); + StringAssert.Contains(empty, "Migliorie in osservazione"); + StringAssert.Contains(empty, "Stime di costo da confermare"); + + // A grid value out of range goes back to the form with the reason, and nothing is planned. + using (var wrong = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields(("griglia_fast", "1, 5")))) + { + Assert.AreEqual("/laboratorio?errore=griglia&strategia=sma_cross#nuovo", ServerHarness.Location(wrong)); + } + + StringAssert.Contains(await server.TextAsync("/laboratorio?errore=griglia&strategia=sma_cross"), "fuori dall'intervallo del parametro"); + Assert.HasCount(0, await new TrialStore(db, SystemClock.Instance).ListAsync(10, CancellationToken.None)); + + var first = await PlanAsync(server, Fields()); + var second = await PlanAsync(server, Fields(("griglia_fast", "10"), ("griglia_slow", "30"))); + await WaitAsync(db, first); + await WaitAsync(db, second); + + var list = await server.TextAsync("/laboratorio"); + StringAssert.Contains(list, $"href=\"/laboratorio/{first}\""); + StringAssert.Contains(list, "Completato"); + StringAssert.Contains(list, "Confronta"); + + var report = await server.TextAsync($"/laboratorio/{first}"); + foreach (var part in new[] + { + "Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)", + "Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano", + "K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera", + "Fase 5", "Impronta dei dati", "Vedi i numeri in una tabella", + }) + { + StringAssert.Contains(report, part, $"Missing \"{part}\" in the report."); + } + + var compare = await server.TextAsync($"/laboratorio/confronto?a={first}&b={second}"); + StringAssert.Contains(compare, "Stessi dati per entrambi"); + StringAssert.Contains(compare, "non si applica", "The second test has one variant: no PBO."); + + using var missing = await server.GetAsync($"/laboratorio/{Guid.NewGuid()}"); + StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoRunsNoTests() + { + string demoRoot; + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + demoRoot = server.Host.Config.Data.Root; + var page = await server.TextAsync("/laboratorio"); + StringAssert.Contains(page, "Il laboratorio non esegue test in questa modalità."); + Assert.IsFalse(page.Contains("/azioni/laboratorio", StringComparison.Ordinal), "No form in the demo."); + using var post = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields()); + Assert.AreEqual("/laboratorio?errore=motore&strategia=sma_cross#nuovo", ServerHarness.Location(post)); + } + + // After the server has stopped, so the demo database is closed. + + TempFolder.Delete(demoRoot); + } + + private static (string, string)[] Fields(params (string Name, string Value)[] overrides) + { + var fields = new Dictionary(StringComparer.Ordinal) + { + ["strategia"] = "sma_cross", + ["origine"] = TrialSources.Database, + ["mercato"] = Venues.Okx, + ["strumenti"] = "btc-eur", + ["dal"] = "2024-01-01", + ["al"] = "2025-02-03", + ["capitale"] = "10.000", + ["griglia_fast"] = "5, 10", + ["griglia_slow"] = "20, 40", + }; + foreach (var (name, value) in overrides) + { + fields[name] = value; + } + + return [.. fields.Select(f => (f.Key, f.Value))]; + } + + private static async Task PlanAsync(ServerHarness server, (string, string)[] fields) + { + using var response = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", fields); + Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode); + var location = ServerHarness.Location(response); + StringAssert.StartsWith(location, "/laboratorio/"); + return Guid.Parse(location["/laboratorio/".Length..]); + } + + private static async Task WaitAsync(Anubis.Db.Database db, Guid id) + { + var store = new TrialStore(db, SystemClock.Instance); + for (var i = 0; i < 600; i++) + { + var trial = await store.GetAsync(id, CancellationToken.None); + if (trial!.IsFinished) + { + Assert.AreEqual(TrialStatuses.Done, trial.Status, trial.Error); + return; + } + + await Task.Delay(50); + } + + Assert.Fail("The trial did not finish in 30 seconds."); + } +}