Fase 4 — Backtest e laboratorio #90
No files matched your search
@@ -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);
|
||||
|
||||
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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<JobRun>();
|
||||
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);
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static async Task<IResult> 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<string, IReadOnlyList<decimal>>(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;
|
||||
|
||||
/// <summary>Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point.</summary>
|
||||
internal static IReadOnlyList<decimal>? ParseList(string text)
|
||||
{
|
||||
var result = new List<decimal>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50".</summary>
|
||||
internal static decimal? ParseEuro(string text)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>How the laboratory pages write the numbers of a backtest, in plain Italian (SPEC 13.3).</summary>
|
||||
internal static class LabText
|
||||
{
|
||||
public const string Missing = "—";
|
||||
|
||||
/// <summary>A fraction as a percentage: 0,1234 is "12,3%".</summary>
|
||||
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)}";
|
||||
|
||||
/// <summary>Parameters as the user reads them: "fast=20;slow=100" becomes "fast 20, slow 100".</summary>
|
||||
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<string> symbols) =>
|
||||
symbols.Count <= 4 ? string.Join(", ", symbols) : string.Join(", ", symbols.Take(3)) + $" e altri {symbols.Count - 3}";
|
||||
|
||||
/// <summary>The value of a check, written in its unit.</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>What the engine did not do as asked, in words.</summary>
|
||||
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",
|
||||
};
|
||||
}
|
||||
@@ -21,8 +21,23 @@ public sealed record TrialRequest(
|
||||
decimal InitialCapital,
|
||||
IReadOnlyDictionary<string, IReadOnlyList<decimal>>? Grid = null);
|
||||
|
||||
/// <summary>A request the laboratory refuses, with the reason in Italian for the form.</summary>
|
||||
public sealed class TrialRequestException(string message) : Exception(message);
|
||||
/// <summary>A request the laboratory refuses: a short code for the address of the form, and the reason in Italian.</summary>
|
||||
public sealed class TrialRequestException(string code, string message) : Exception(message)
|
||||
{
|
||||
public string Code { get; } = code;
|
||||
}
|
||||
|
||||
/// <summary>Codes of <see cref="TrialRequestException"/>.</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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<string, IReadOnlyList<decimal>>(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"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Net;
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The Laboratorio screen (issue #36): a new test from the form, its report, the comparison.</summary>
|
||||
[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<string, string>(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<Guid> 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.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user