Add the Laboratorio screen: new test, report, comparison (refs #36)
The laboratory starts with the host (off in demo mode) and runs its queue next to market data and trading. The page lists every trial with status, verdict and headline figures, refreshing itself while one is queued or running, and offers the form for a new test: strategy, data origin and market, instruments, period, initial capital and the grid, with the thresholds stated before the run. The form posts with the antiforgery token; errors come back as a short code. The report page shows the protocol checks, the chosen variant against buy and hold (table and chart), results per year, cost sensitivity, the Deflated Sharpe Ratio, PBO, walk-forward windows, purged CV paths, the look-ahead result, every variant with its zone score, what the backtest does not model, the data used and the trades. A comparison page puts two finished tests side by side and says whether they read the same data. The improvements of 8.7 and the cost estimates of 11.6 have their sections, empty until Phases 9 and 8. The equity chart takes amounts in their own currency and its labels as parameters. The profit factor has no value without a losing trade. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5efb149fd6
commit
953ffe5e9b
11 files changed
+1083
-26
No files matched your search
@@ -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<decimal>()).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];
|
||||
<figure class="chart" aria-label="Patrimonio nel tempo, con il bot e senza">
|
||||
<figure class="chart" aria-label="@Label">
|
||||
<div class="chart-box">
|
||||
<div class="chart-axis" aria-hidden="true">
|
||||
@for (var t = lo; t <= hi; t += step)
|
||||
@@ -42,28 +42,28 @@
|
||||
var gap = Math.Abs(Y(last) - Y(lastBench)) / 10;
|
||||
var benchTop = gap < 7 ? Y(last) / 10 + (Y(lastBench) >= Y(last) ? 7 : -7) : Y(lastBench) / 10;
|
||||
<span class="end-dot bench-dot" style="left:100%;top:@Pct(Y(lastBench) / 10)"></span>
|
||||
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Shell.Money(Points[^1].Benchmark!.Value, Currency, decimals: 0)</span>
|
||||
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Text(Points[^1].Benchmark!.Value, 0)</span>
|
||||
}
|
||||
<span class="end-dot" style="left:100%;top:@Pct(Y(last) / 10)"></span>
|
||||
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Shell.Money(Points[^1].Equity, Currency, decimals: 0)</span>
|
||||
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Text(Points[^1].Equity, 0)</span>
|
||||
</div>
|
||||
</div>
|
||||
<figcaption class="legend">
|
||||
<span class="key key-equity">Con Anubis</span>
|
||||
<span class="key key-equity">@EquityLabel</span>
|
||||
@if (benchLine.Length > 0)
|
||||
{
|
||||
<span class="key key-bench">Senza bot: Bitcoin e S&P 500 comprati e tenuti</span>
|
||||
<span class="key key-bench">@BenchmarkLabel</span>
|
||||
}
|
||||
</figcaption>
|
||||
<details class="chart-table">
|
||||
<summary>Vedi i numeri in una tabella</summary>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">Con il bot</th><th scope="col" class="num">Senza bot</th></tr></thead>
|
||||
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">@EquityColumn</th><th scope="col" class="num">@BenchmarkColumn</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var p in Points.AsEnumerable().Reverse())
|
||||
{
|
||||
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Shell.Money(p.Equity, Currency)</td><td class="num">@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")</td></tr>
|
||||
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Text(p.Equity)</td><td class="num">@(p.Benchmark is { } b ? Text(b) : "—")</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -79,6 +79,29 @@
|
||||
[Parameter]
|
||||
public string Currency { get; set; } = "EUR";
|
||||
|
||||
/// <summary>True when the amounts are already in <see cref="Currency"/> (a backtest report): no conversion from euro.</summary>
|
||||
[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) + "%";
|
||||
|
||||
@@ -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
|
||||
|
||||
<PageTitle>Laboratorio · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Nessun test eseguito.">Il laboratorio dei test sul passato arriva con il motore dei backtest.</Pending>
|
||||
@if (_running)
|
||||
{
|
||||
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
|
||||
}
|
||||
|
||||
@if (_message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
|
||||
@if (_lab is null)
|
||||
{
|
||||
<Pending Title="Il laboratorio non esegue test in questa modalità.">Nella modalità dimostrativa i test sul passato non partono: avvia Anubis normalmente per provare una strategia.</Pending>
|
||||
}
|
||||
|
||||
<section class="panel" aria-labelledby="prove">
|
||||
<div class="panel-head">
|
||||
<h2 id="prove">Test eseguiti</h2>
|
||||
@if (_trials.Count(t => t.Status == TrialStatuses.Done) >= 2)
|
||||
{
|
||||
<form method="get" action="/laboratorio/confronto" class="form-inline">
|
||||
<label for="a" class="sr-only">Primo test</label>
|
||||
<select id="a" name="a">
|
||||
@foreach (var t in _trials.Where(t => t.Status == TrialStatuses.Done))
|
||||
{
|
||||
<option value="@t.Id">@Title(t)</option>
|
||||
}
|
||||
</select>
|
||||
<label for="b" class="sr-only">Secondo test</label>
|
||||
<select id="b" name="b">
|
||||
@foreach (var (t, i) in _trials.Where(t => t.Status == TrialStatuses.Done).Select((t, i) => (t, i)))
|
||||
{
|
||||
<option value="@t.Id" selected="@(i == 1)">@Title(t)</option>
|
||||
}
|
||||
</select>
|
||||
<button class="btn btn-small" type="submit">Confronta</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
@if (_trials.Count == 0)
|
||||
{
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessun test eseguito.</p>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Pianificato</th>
|
||||
<th scope="col">Strategia</th>
|
||||
<th scope="col">Dati</th>
|
||||
<th scope="col" class="num">Varianti</th>
|
||||
<th scope="col">Stato</th>
|
||||
<th scope="col">Esito</th>
|
||||
<th scope="col" class="num">Risultato netto</th>
|
||||
<th scope="col" class="num">Sharpe</th>
|
||||
<th scope="col" class="num">Calo massimo</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var t in _trials)
|
||||
{
|
||||
var s = t.Summary;
|
||||
<tr>
|
||||
<td class="nowrap"><a href="/laboratorio/@t.Id">@Format.ShortDate(t.CreatedAt, Shell.Now, Shell.Zone)</a></td>
|
||||
<td>@Name(t.Strategy)</td>
|
||||
<td>@LabText.Symbols(t.Plan.Data.Symbols)<br /><span class="muted">@LabText.Period(t.Plan.Data.From, t.Plan.Data.To)</span></td>
|
||||
<td class="num">@t.Variants</td>
|
||||
<td>@LabText.Status(t, _lab?.Progress(t.Id))</td>
|
||||
<td>
|
||||
@if (t.Verdict is { } verdict)
|
||||
{
|
||||
<span class="tag @(verdict == TrialVerdicts.Passed ? "gain" : "loss")">@LabText.Verdict(verdict)</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
@LabText.Missing
|
||||
}
|
||||
</td>
|
||||
<td class="num">@(s is null ? LabText.Missing : LabText.Money(s.NetResult, s.Currency, withSign: true))</td>
|
||||
<td class="num">@(s is null ? LabText.Missing : LabText.Number(s.Sharpe))</td>
|
||||
<td class="num">@(s is null ? LabText.Missing : LabText.Percent(s.MaxDrawdown))</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (_lab is not null)
|
||||
{
|
||||
var family = _family;
|
||||
<section class="panel" id="nuovo" aria-labelledby="nuovo-titolo">
|
||||
<div class="panel-head">
|
||||
<h2 id="nuovo-titolo">Nuovo test</h2>
|
||||
<nav class="segmented" aria-label="Strategia">
|
||||
@foreach (var f in StrategyCatalog.All)
|
||||
{
|
||||
<a href="/laboratorio?strategia=@f.Id#nuovo" class="@(f.Id == family.Id ? "on" : null)" aria-current="@(f.Id == family.Id ? "true" : null)">@f.Name</a>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
<p>@family.Description</p>
|
||||
<form method="post" action="/azioni/laboratorio" class="form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="strategia" value="@family.Id" />
|
||||
<label for="origine">Dati</label>
|
||||
<select id="origine" name="origine">
|
||||
<option value="@TrialSources.Database">Barre giornaliere raccolte da Anubis</option>
|
||||
<option value="@TrialSources.Research">Storico di ricerca (archivi Binance dal 2017)</option>
|
||||
</select>
|
||||
<label for="mercato">Mercato, per le barre raccolte</label>
|
||||
<select id="mercato" name="mercato">
|
||||
<option value="@Venues.Okx">Crypto su OKX, in euro</option>
|
||||
<option value="@Venues.Alpaca">Azioni USA su Alpaca, in dollari</option>
|
||||
</select>
|
||||
<label for="strumenti">Strumenti, separati da virgole</label>
|
||||
<input id="strumenti" name="strumenti" autocomplete="off" spellcheck="false" maxlength="400" placeholder="BTC-EUR, ETH-EUR" required />
|
||||
<p class="hint">Simboli del mercato scelto: BTC-EUR su OKX, AAPL su Alpaca, BTCUSDT nello storico di ricerca. @Research()</p>
|
||||
<div class="row">
|
||||
<div>
|
||||
<label for="dal">Dal</label>
|
||||
<input id="dal" name="dal" type="date" value="@_from.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)" required />
|
||||
</div>
|
||||
<div>
|
||||
<label for="al">Al</label>
|
||||
<input id="al" name="al" type="date" value="@_to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)" required />
|
||||
</div>
|
||||
</div>
|
||||
<label for="capitale">Capitale iniziale, nella valuta degli strumenti</label>
|
||||
<input id="capitale" name="capitale" inputmode="decimal" autocomplete="off" value="10.000" required />
|
||||
@if (family.Parameters.Count > 0)
|
||||
{
|
||||
<fieldset>
|
||||
<legend>Griglia dei parametri</legend>
|
||||
@foreach (var p in family.Parameters)
|
||||
{
|
||||
<label for="griglia-@p.Name">@p.Label</label>
|
||||
<input id="griglia-@p.Name" name="griglia_@p.Name" autocomplete="off" spellcheck="false" maxlength="200" value="@string.Join(", ", p.Grid.Select(v => v.ToString(CultureInfo.InvariantCulture)))" />
|
||||
<p class="hint">Da @p.Min.ToString(CultureInfo.InvariantCulture) a @p.Max.ToString(CultureInfo.InvariantCulture), valori separati da virgole; ogni combinazione è una variante.</p>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
<p class="hint">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%.</p>
|
||||
<button class="btn btn-primary" type="submit">Scrivi il piano e avvia il test</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="panel" aria-labelledby="migliorie">
|
||||
<h2 id="migliorie">Migliorie in osservazione</h2>
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna miglioria in osservazione.</p>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="stime">
|
||||
<h2 id="stime">Stime di costo da confermare</h2>
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna stima da confermare.</p>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private Laboratory? _lab;
|
||||
private IReadOnlyList<Trial> _trials = [];
|
||||
private IStrategyFamily _family = StrategyCatalog.All[0];
|
||||
private bool _running;
|
||||
private string? _message;
|
||||
private DateOnly _from;
|
||||
private DateOnly _to;
|
||||
private IReadOnlyList<string> _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)}";
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/laboratorio/confronto"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@inject IClock Clock
|
||||
@using Anubis.Backtest
|
||||
@using Anubis.Strategies
|
||||
|
||||
<PageTitle>Confronto tra test · Anubis</PageTitle>
|
||||
|
||||
<p><a href="/laboratorio">← Laboratorio</a></p>
|
||||
|
||||
@if (_a is null || _b is null)
|
||||
{
|
||||
<Pending Title="Servono due test completati.">Scegli due test conclusi dall'elenco del <a href="/laboratorio">Laboratorio</a>.</Pending>
|
||||
return;
|
||||
}
|
||||
|
||||
@{
|
||||
var a = _a.Value;
|
||||
var b = _b.Value;
|
||||
var ra = a.Report;
|
||||
var rb = b.Report;
|
||||
}
|
||||
<section class="panel" aria-labelledby="confronto">
|
||||
<h2 id="confronto">Confronto tra due test</h2>
|
||||
@if (ra.DataFingerprint != rb.DataFingerprint)
|
||||
{
|
||||
<p class="notice notice-attention" role="note"><Icon Name="info" Size="16" />I due test hanno letto dati diversi (strumenti, periodo o valuta): il confronto è indicativo.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="notice notice-gain" role="note"><Icon Name="check" Size="16" />Stessi dati per entrambi: le differenze vengono dalla strategia, dalla griglia o dalle soglie.</p>
|
||||
}
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"><a href="/laboratorio/@a.Trial.Id">@Name(a)</a></th>
|
||||
<th scope="col"><a href="/laboratorio/@b.Trial.Id">@Name(b)</a></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@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))
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@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 =>
|
||||
{
|
||||
<tr><th scope="row">@label</th><td>@value(_a!.Value)</td><td>@value(_b!.Value)</td></tr>
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
|
||||
<PageTitle>Test del laboratorio · Anubis</PageTitle>
|
||||
|
||||
@if (_trial is null)
|
||||
{
|
||||
<Pending Title="Test non trovato.">Torna al <a href="/laboratorio">Laboratorio</a> per l'elenco dei test.</Pending>
|
||||
return;
|
||||
}
|
||||
|
||||
@{
|
||||
var t = _trial;
|
||||
var plan = t.Plan;
|
||||
var r = _report;
|
||||
}
|
||||
@if (!t.IsFinished)
|
||||
{
|
||||
<HeadContent><meta http-equiv="refresh" content="3" /></HeadContent>
|
||||
}
|
||||
|
||||
<p><a href="/laboratorio">← Laboratorio</a></p>
|
||||
|
||||
<section class="panel" aria-labelledby="titolo">
|
||||
<div class="panel-head">
|
||||
<h2 id="titolo">@Name(t.Strategy) su @LabText.Symbols(plan.Data.Symbols)</h2>
|
||||
@if (t.Verdict is { } verdict)
|
||||
{
|
||||
<span class="badge @(verdict == TrialVerdicts.Passed ? "badge-gain" : "badge-loss")"><Icon Name="@(verdict == TrialVerdicts.Passed ? "check" : "alert")" Size="18" />@LabText.Verdict(verdict)</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="tag">@LabText.Status(t, _progress)</span>
|
||||
}
|
||||
</div>
|
||||
<dl class="facts">
|
||||
<dt>Dati</dt>
|
||||
<dd>@LabText.Source(plan.Data), @LabText.Period(plan.Data.From, plan.Data.To)</dd>
|
||||
<dt>Varianti provate</dt>
|
||||
<dd>@t.Variants (@string.Join("; ", plan.Grid.Select(g => g.Key + " " + string.Join(", ", g.Value.Select(v => v.ToString(CultureInfo.InvariantCulture))))))</dd>
|
||||
<dt>Capitale iniziale</dt>
|
||||
<dd>@(r is null ? Format.Number(plan.InitialCapital, 2) : Format.Money(plan.InitialCapital, r.Currency))</dd>
|
||||
<dt>Piano scritto</dt>
|
||||
<dd>@Format.LongDateTime(t.CreatedAt, Shell.Zone), prima dei risultati. Impronta @Short(t.PlanHash)</dd>
|
||||
@if (t.FinishedAt is { } finished)
|
||||
{
|
||||
<dt>Concluso</dt>
|
||||
<dd>@Format.LongDateTime(finished, Shell.Zone)@(r is null ? "" : $", in {LabText.Number(r.Seconds, 1)} secondi")</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (t.Status == TrialStatuses.Failed)
|
||||
{
|
||||
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />Il test non è riuscito: @t.Error</p>
|
||||
}
|
||||
else if (!t.IsFinished)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="clock" Size="16" />@(t.Status == TrialStatuses.Planned ? "In coda: parte appena finisce il test precedente." : "In corso" + (_progress is null ? "." : ": " + _progress + ".")) La pagina si aggiorna da sola.</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (r is not null)
|
||||
{
|
||||
var c = r.Currency;
|
||||
var m = r.Metrics;
|
||||
var b = r.Benchmark;
|
||||
<section class="panel" aria-labelledby="esito">
|
||||
<h2 id="esito">Esito del protocollo</h2>
|
||||
<p>Variante scelta: <strong>@LabText.Parameters(r.Chosen)</strong>, la migliore zona della griglia e non il singolo punto migliore.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Controllo</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Soglia</th><th scope="col">Esito</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var check in r.Checks)
|
||||
{
|
||||
<tr>
|
||||
<td>@check.Name</td>
|
||||
<td class="num">@LabText.CheckValue(check, c)</td>
|
||||
<td class="num">@LabText.CheckThreshold(check, c)</td>
|
||||
<td>
|
||||
@switch (check.Passed)
|
||||
{
|
||||
case true:
|
||||
<span class="tag gain">Superato</span>
|
||||
break;
|
||||
case false:
|
||||
<span class="tag loss">Non superato</span>
|
||||
break;
|
||||
default:
|
||||
<span class="tag">Non si applica</span>
|
||||
break;
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="risultato">
|
||||
<h2 id="risultato">Risultato della variante scelta</h2>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col"></th><th scope="col" class="num">Variante scelta</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><th scope="row">Risultato netto</th><td class="num">@LabText.Money(m.NetResult, c, withSign: true)</td><td class="num">@LabText.Money(b.NetResult, c, withSign: true)</td></tr>
|
||||
<tr><th scope="row">Rendimento totale</th><td class="num">@LabText.Percent(m.TotalReturn, 1, true)</td><td class="num">@LabText.Percent(b.TotalReturn, 1, true)</td></tr>
|
||||
<tr><th scope="row">Rendimento annuo</th><td class="num">@LabText.Percent(m.AnnualReturn, 1, true)</td><td class="num">@LabText.Percent(b.AnnualReturn, 1, true)</td></tr>
|
||||
<tr><th scope="row">Volatilità annua</th><td class="num">@LabText.Percent(m.Volatility)</td><td class="num">@LabText.Percent(b.Volatility)</td></tr>
|
||||
<tr><th scope="row">Sharpe annuo</th><td class="num">@LabText.Number(m.Sharpe)</td><td class="num">@LabText.Number(b.Sharpe)</td></tr>
|
||||
<tr><th scope="row">Calo massimo</th><td class="num">@LabText.Percent(m.MaxDrawdown)</td><td class="num">@LabText.Percent(b.MaxDrawdown)</td></tr>
|
||||
<tr><th scope="row">Operazioni chiuse</th><td class="num">@m.Trades</td><td class="num">@LabText.Missing</td></tr>
|
||||
<tr><th scope="row">Operazioni in guadagno</th><td class="num">@(m.Trades == 0 ? LabText.Missing : LabText.Percent(m.WinRate, 0))</td><td class="num">@LabText.Missing</td></tr>
|
||||
<tr><th scope="row">Rapporto guadagni/perdite</th><td class="num">@(m.ProfitFactor is { } pf ? LabText.Number(pf) : m.Trades > 0 ? "nessuna perdita" : LabText.Missing)</td><td class="num">@LabText.Missing</td></tr>
|
||||
<tr><th scope="row">Guadagno e perdita medi</th><td class="num">@LabText.Money(m.AverageWin, c, true) / @LabText.Money(m.AverageLoss, c, true)</td><td class="num">@LabText.Missing</td></tr>
|
||||
<tr><th scope="row">Commissioni</th><td class="num">@LabText.Money(m.Fees, c)</td><td class="num">@LabText.Money(b.Fees, c)</td></tr>
|
||||
<tr><th scope="row">Tempo investito, in media</th><td class="num">@LabText.Percent(m.Exposure, 0)</td><td class="num">@LabText.Percent(b.Exposure, 0)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<EquityChart Points="_curve" Currency="@c" Native="true" Label="Patrimonio della variante scelta e di comprare e tenere" EquityLabel="Variante scelta" BenchmarkLabel="Comprare e tenere gli stessi strumenti" EquityColumn="Variante scelta" BenchmarkColumn="Comprare e tenere" />
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="anni">
|
||||
<h2 id="anni">Risultato per anno</h2>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Anno</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var y in m.Years)
|
||||
{
|
||||
var bh = b.Years.FirstOrDefault(x => x.Year == y.Year);
|
||||
<tr><td>@y.Year</td><td class="num">@LabText.Money(y.Result, c, true)</td><td class="num">@LabText.Percent(y.Return, 1, true)</td><td class="num">@(bh is null ? LabText.Missing : LabText.Percent(bh.Return, 1, true))</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="costi">
|
||||
<h2 id="costi">Sensibilità ai costi</h2>
|
||||
<p>Commissioni e scostamento moltiplicati: una strategia che muore con i costi doppi non passa.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Costi</th><th scope="col" class="num">Risultato netto</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Sharpe</th><th scope="col" class="num">Calo massimo</th><th scope="col" class="num">Commissioni</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var k in r.Costs)
|
||||
{
|
||||
<tr><td>@(k.Multiplier == 1m ? "realistici" : $"× {Format.Number(k.Multiplier)}")</td><td class="num">@LabText.Money(k.NetResult, c, true)</td><td class="num">@LabText.Percent(k.TotalReturn, 1, true)</td><td class="num">@LabText.Number(k.Sharpe)</td><td class="num">@LabText.Percent(k.MaxDrawdown)</td><td class="num">@LabText.Money(k.Fees, c)</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="convalide">
|
||||
<h2 id="convalide">Convalide</h2>
|
||||
<h3>Sharpe corretto per il numero di prove</h3>
|
||||
@{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); }
|
||||
<p>Deflated Sharpe Ratio <strong>@LabText.Number(d.Value)</strong>: 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).</p>
|
||||
|
||||
<h3>Probabilità di sovra-adattamento</h3>
|
||||
@if (r.Overfitting is { } pbo)
|
||||
{
|
||||
<p>PBO <strong>@LabText.Number(pbo.Probability)</strong>: 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.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Con una sola variante non c'è nulla da scegliere, quindi nulla da sovra-adattare: il controllo non si applica.</p>
|
||||
}
|
||||
|
||||
<h3>Finestre che avanzano</h3>
|
||||
@if (r.WalkForward is { } wf)
|
||||
{
|
||||
<p>Ogni finestra sceglie la variante sui dati precedenti e la giudica su quelli successivi, mai visti. Rendimento fuori campione complessivo <strong>@LabText.Percent(wf.Return, 1, true)</strong>, Sharpe @LabText.Number(wf.Sharpe * annual) all'anno; @wf.Purge sedute tolte tra addestramento e prova.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Finestra</th><th scope="col">Scelta su</th><th scope="col">Provata su</th><th scope="col">Variante</th><th scope="col" class="num">Rendimento</th><th scope="col" class="num">Sharpe</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var w in wf.Windows)
|
||||
{
|
||||
<tr><td>@w.Window</td><td class="nowrap">@LabText.Period(w.TrainFrom, w.TrainTo)</td><td class="nowrap">@LabText.Period(w.TestFrom, w.TestTo)</td><td>@LabText.Parameters(w.Chosen)</td><td class="num">@LabText.Percent(w.Return, 1, true)</td><td class="num">@LabText.Number(w.Sharpe * annual)</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Periodo troppo breve per le finestre.</p>
|
||||
}
|
||||
|
||||
<h3>K-fold purgato combinatorio</h3>
|
||||
@if (r.Combinatorial is { } cv)
|
||||
{
|
||||
<p>@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).</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Periodo troppo breve per i blocchi.</p>
|
||||
}
|
||||
|
||||
<h3>Nessuno sguardo in avanti</h3>
|
||||
<p>
|
||||
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.")
|
||||
</p>
|
||||
@if (r.LookAhead.Examples.Count > 0)
|
||||
{
|
||||
<ul>
|
||||
@foreach (var e in r.LookAhead.Examples)
|
||||
{
|
||||
<li><code>@e</code></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="griglia">
|
||||
<h2 id="griglia">Tutte le varianti</h2>
|
||||
<p>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.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Parametri</th><th scope="col" class="num">Sharpe annuo</th><th scope="col" class="num">Punteggio di zona</th><th scope="col" class="num">Risultato netto</th><th scope="col" class="num">Calo massimo</th><th scope="col" class="num">Operazioni</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var v in r.Variants)
|
||||
{
|
||||
<tr>
|
||||
<td>@LabText.Parameters(v.Parameters)@if (v.Chosen) {<span class="tag"> scelta</span>}</td>
|
||||
<td class="num">@LabText.Number(v.Sharpe * annual)</td>
|
||||
<td class="num">@LabText.Number(v.PlateauScore * annual)</td>
|
||||
<td class="num">@LabText.Money(v.NetResult, c, true)</td>
|
||||
<td class="num">@LabText.Percent(v.MaxDrawdown)</td>
|
||||
<td class="num">@v.Trades</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="limiti">
|
||||
<h2 id="limiti">Cosa questo test non considera</h2>
|
||||
<ul>
|
||||
@foreach (var l in r.Limitations)
|
||||
{
|
||||
<li>@l</li>
|
||||
}
|
||||
</ul>
|
||||
@if (r.Notes.Count > 0)
|
||||
{
|
||||
<h3>Ordini non eseguiti come chiesto</h3>
|
||||
<ul>
|
||||
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
|
||||
{
|
||||
<li>@LabText.Note(reason): @count</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<h3>Dati usati</h3>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Strumento</th><th scope="col">Origine</th><th scope="col">Periodo</th><th scope="col" class="num">Barre</th><th scope="col" class="num">Azioni societarie</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var i in r.Instruments)
|
||||
{
|
||||
<tr><td>@i.Symbol</td><td>@i.Source</td><td class="nowrap">@LabText.Day(i.First) – @LabText.Day(i.Last)</td><td class="num">@i.Bars</td><td class="num">@i.Actions</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="hint">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.</p>
|
||||
</section>
|
||||
|
||||
@if (r.Trades.Count > 0)
|
||||
{
|
||||
<section class="panel" aria-labelledby="operazioni">
|
||||
<h2 id="operazioni">Operazioni della variante scelta</h2>
|
||||
<details>
|
||||
<summary>Vedi le ultime @r.Trades.Count operazioni</summary>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Strumento</th><th scope="col">Aperta</th><th scope="col">Chiusa</th><th scope="col" class="num">Investito</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Commissioni</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var tr in r.Trades.Reverse())
|
||||
{
|
||||
<tr><td>@tr.Symbol</td><td class="nowrap">@LabText.Day(tr.Opened)</td><td class="nowrap">@(tr.Closed is { } closed ? LabText.Day(closed) : "aperta")</td><td class="num">@LabText.Money(tr.Invested, c)</td><td class="num @(tr.Result >= 0 ? "gain" : "loss")">@LabText.Money(tr.Result, c, true)</td><td class="num">@LabText.Money(tr.Fees, c)</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
@code {
|
||||
private Trial? _trial;
|
||||
private BacktestReport? _report;
|
||||
private string? _progress;
|
||||
private IReadOnlyList<Anubis.Server.EquityPoint> _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;
|
||||
}
|
||||
Reference in new issue
Block a user