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
@@ -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