Files
Anubis/src/Anubis.Server/Components/Pages/LaboratorioProva.razor
T
Alby96andClaude Opus 5.5 3543f29aba Judge the variant in use and count the shadow cases for what they are
The quarterly review judged the best variant of the grid instead of the one
that trades: the plan now fixes the variant in use and the protocol measures
that one, while the tries are still those of the grid. A failure while the
history is prepared is a reason in the report and no longer stops the review,
and a strategy whose protocol does not exist says so when its data are there.

The volatility improvement compared books of different days and stages: the
book keeps its stage and its previous day, and a case without a book valid on
its day is left out. Fewer than six months give no interval, the others use
the clustered error with the Student t.

The restriction balance counts a case in the period in which its outcome
became known, so no case is lost or counted twice between two reviews.

The contact given to the SEC travels only on the client that never follows a
redirect, so it cannot reach another site.

refs #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:26:06 +01:00

343 lines
19 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@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;
var variant = r.Judged is null ? "Variante scelta" : "Variante in uso";
var ofVariant = r.Judged is null ? "della variante scelta" : "della variante in uso";
<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>
@if (r.Judged is { } judged)
{
<p>Il giudizio è sulla variante in uso: <strong>@LabText.Parameters(judged)</strong>.@(r.Variants.Any(v => v.OutsideGrid) ? " Non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più." : "")</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 @ofVariant</h2>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col"></th><th scope="col" class="num">@variant</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 {ofVariant} e di comprare e tenere")" EquityLabel="@variant" BenchmarkLabel="Comprare e tenere gli stessi strumenti" EquityColumn="@variant" 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 @ofVariant (@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>}@if (v.Parameters == r.Judged) {<span class="tag"> in uso</span>}</td>
<td class="num">@LabText.Number(v.Sharpe * annual)</td>
<td class="num">@(v.OutsideGrid ? LabText.Missing : 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>Decisioni e 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;
}