Review the base strategies every three months
Every quarter the base strategies are tried again on the longer history with the slippage in force, compared with how they did live, and the report is published in the laboratory with the base rates measured again and the balance of the restrictions of 10.5. In observation the outcome replaces the old one and a strategy that passed goes to simulation after its 90 days; with capital nothing moves but the demotion condition of 12.3. A restart halfway goes on and the review concludes once; the outcome of a review survives a restart with an older build. refs #74 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
79bb194de0
commit
2257c3e16c
34 files changed
+2308
-87
No files matched your search
@@ -357,6 +357,13 @@ internal sealed partial class AnubisHost(
|
||||
|
||||
// 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);
|
||||
if (_lab is { } laboratory && _trading is { } running && _market is { } market)
|
||||
{
|
||||
var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger);
|
||||
laboratory.ReviewTrialEnded = review.ConcludeAsync;
|
||||
running.QuarterlyReview = review.RunIfDueAsync;
|
||||
}
|
||||
|
||||
// Telegram and the sign of life (SPEC 14): not in the demo, and in tests only with their fake network.
|
||||
_telegram = options.Demo || (overrides is not null && overrides.TelegramHttp is null)
|
||||
? null
|
||||
|
||||
@@ -165,6 +165,31 @@
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="panel" id="revisione" aria-labelledby="revisione-titolo">
|
||||
<h2 id="revisione-titolo">Revisione trimestrale</h2>
|
||||
<p class="hint">Ogni tre mesi le strategie di base si riprovano sui dati nuovi, con le stime di costo aggiornate, e si confrontano con quello che hanno fatto dal vivo.@(Shell.IsDemo ? "" : $" La prossima non prima del {LabText.Day(_nextReview)}.")</p>
|
||||
@if (_reviews.FirstOrDefault(r => r.Status != ReviewStatuses.Done) is { } open)
|
||||
{
|
||||
<p class="notice">@ReviewView.Running(open)</p>
|
||||
}
|
||||
@if (_reviews.Where(r => r.Report is not null).ToList() is { Count: > 0 } done)
|
||||
{
|
||||
<h3><a href="/laboratorio/revisione/@done[0].Id">@done[0].Title</a></h3>
|
||||
<ReviewReportView Review="done[0]" />
|
||||
@if (done.Count > 1)
|
||||
{
|
||||
<p>Revisioni precedenti: @foreach (var (r, i) in done.Skip(1).Select((r, i) => (r, i))) {<text>@(i == 0 ? "" : ", ")</text><a href="/laboratorio/revisione/@r.Id">@r.Title</a>}</p>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna revisione ancora.</p>
|
||||
<p>La prima arriva all'inizio del prossimo trimestre: l'esito di ogni strategia, le frequenze di base e il bilancio di cosa hanno evitato e di cosa sono costate le restrizioni.</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="migliorie">
|
||||
<h2 id="migliorie">Migliorie in osservazione</h2>
|
||||
<p class="hint">Modifiche che potrebbero migliorare il risultato o ridurre i costi. Nessuna è attiva: si calcolano accanto alle regole in vigore, su ogni segnale, e qui c'è l'effetto che avrebbero avuto. Per attivarne una servono il protocollo di validazione superato e una tua decisione.</p>
|
||||
@@ -258,6 +283,8 @@
|
||||
private IReadOnlyList<string> _research = [];
|
||||
private IReadOnlyList<CostEstimate> _costs = [];
|
||||
private IReadOnlyList<Anubis.Learning.ImprovementView> _improvements = [];
|
||||
private IReadOnlyList<Review> _reviews = [];
|
||||
private DateOnly _nextReview;
|
||||
private bool _anyLive;
|
||||
private SlippageTable _table = SlippageTable.Standard;
|
||||
|
||||
@@ -284,7 +311,9 @@
|
||||
var champion = await learning.Models.FindAsync(Anubis.Learning.ModelStatuses.Champion, ct);
|
||||
async Task<bool> HasAsync(string secret) => (await services.Secrets.StatusAsync(secret, ct)).IsSet;
|
||||
_improvements = await learning.Shadow.LoadAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync(Edgar.ContactSecret),
|
||||
learning.BaseRates.ContainsKey(StrategyNames.EquityMeanrev) && champion?.Model?.Strategies.Contains(StrategyNames.EquityMeanrev) == true, ct);
|
||||
(await learning.BaseRatesAsync(ct)).ContainsKey(StrategyNames.EquityMeanrev) && champion?.Model?.Strategies.Contains(StrategyNames.EquityMeanrev) == true, ct);
|
||||
_reviews = await QuarterlyReview.ListAsync(services.Db, ct);
|
||||
_nextReview = QuarterlyReview.NextDue(Zones.DayIn(Clock.UtcNow, Zones.Rome), await QuarterlyReview.LastQuarterAsync(services.Db, Clock, ct));
|
||||
_running = _trials.Any(t => !t.IsFinished);
|
||||
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/laboratorio/revisione/{Id:guid}"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@using Anubis.Backtest
|
||||
|
||||
<PageTitle>Revisione trimestrale · Anubis</PageTitle>
|
||||
|
||||
@if (_review is null)
|
||||
{
|
||||
<Pending Title="Revisione non trovata.">Torna al <a href="/laboratorio">Laboratorio</a> per l'elenco delle revisioni.</Pending>
|
||||
return;
|
||||
}
|
||||
|
||||
<p><a href="/laboratorio#revisione">← Laboratorio</a></p>
|
||||
|
||||
<section class="panel" aria-labelledby="titolo">
|
||||
<h2 id="titolo">Revisione del @_review.Title</h2>
|
||||
@if (_review.Report is null)
|
||||
{
|
||||
<p class="notice">@ReviewView.Running(_review)</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">Conclusa @Format.LongDateTime(_review.FinishedAt ?? _review.CreatedAt, Shell.Zone).</p>
|
||||
<ReviewReportView Review="_review" />
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private Review? _review;
|
||||
|
||||
[Parameter]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
protected override async Task LoadAsync() =>
|
||||
_review = (await QuarterlyReview.ListAsync(Host.Services!.Db, HttpContext?.RequestAborted ?? CancellationToken.None)).FirstOrDefault(r => r.Id == Id);
|
||||
}
|
||||
@@ -204,7 +204,7 @@
|
||||
var passed = s.Stage.Qualification?.Passed == true;
|
||||
<dt>@s.Name</dt>
|
||||
<dd>
|
||||
<span>@StrategiesView.ObservationReason(s.Stage)@if (report is not null) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||
<span>@StrategiesView.ObservationReason(s.Stage)@if (StrategiesView.IsPage(report)) {<text> </text><a href="@report">Rapporto</a>} else if (report is not null) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||
@if (passed && !Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/simulazione"><AntiforgeryToken /><button class="btn btn-small" type="submit">Porta in simulazione</button></form>
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
@using Anubis.Backtest
|
||||
@using Anubis.Learning
|
||||
@using Anubis.Trading
|
||||
|
||||
@{
|
||||
var r = Review.Report!;
|
||||
var rates = ReviewView.Rates(r);
|
||||
var restrictions = ReviewView.Restrictions(r);
|
||||
}
|
||||
|
||||
<p class="hint">Dati fino al @LabText.Day(Review.Through).@(r.Missing is { } missing ? $" Le crypto non sono state riprovate: {missing}." : "")</p>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<caption class="sr-only">Esito della revisione per strategia</caption>
|
||||
<thead><tr><th scope="col">Strategia</th><th scope="col">Stadio</th><th scope="col">Esito</th><th scope="col">Cosa cambia</th><th scope="col">Dal vivo</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var line in r.Strategies)
|
||||
{
|
||||
<tr>
|
||||
<td><strong>@StrategyNames.Label(line.Strategy, withMarket: true)</strong></td>
|
||||
<td>@StrategyStages.Label(line.Stage)</td>
|
||||
<td>
|
||||
<span class="tag @ReviewView.VerdictClass(line)">@ReviewView.Verdict(line)</span>
|
||||
@if (line.Verdict != ReviewVerdicts.Waiting || r.Missing is not null && line.Strategy == CryptoTrendProtocol.Strategy)
|
||||
{
|
||||
<br /><span class="note">@line.Text</span>
|
||||
}
|
||||
@foreach (var (id, i) in line.Trials.Select((id, i) => (id, i)))
|
||||
{
|
||||
<br /><a href="/laboratorio/@id">@(i == 0 ? "Test sull'universo ampio" : "Test su BTC, ETH e SOL")</a>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@ReviewView.Action(line)
|
||||
@if (line.Chosen is { } chosen)
|
||||
{
|
||||
<br /><span class="note">Variante migliore: @LabText.Parameters(chosen.Parameters), Sharpe @LabText.Number(chosen.Sharpe), calo massimo @LabText.Percent(chosen.MaxDrawdown).</span>
|
||||
}
|
||||
@if (line.InUse is { } used)
|
||||
{
|
||||
<br /><span class="note">Variante in uso: @LabText.Parameters(used.Parameters), Sharpe @LabText.Number(used.Sharpe), calo massimo @LabText.Percent(used.MaxDrawdown). Non cambia da sola.</span>
|
||||
}
|
||||
</td>
|
||||
<td>@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) {<div>@text</div>}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>Frequenze di base</h3>
|
||||
@if (rates.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna frequenza misurata.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="hint">Quante operazioni su cento chiudono in guadagno nello storico: è il termine di paragone del modello.@(r.RatesAfter is null ? " Questa volta non sono state rimisurate." : "")</p>
|
||||
<dl class="facts">
|
||||
@foreach (var rate in rates)
|
||||
{
|
||||
<dt>@rate.Name</dt>
|
||||
<dd>@(rate.Before == rate.After ? rate.After : $"da {rate.Before} a {rate.After}")</dd>
|
||||
}
|
||||
</dl>
|
||||
}
|
||||
|
||||
<h3>Bilancio delle restrizioni</h3>
|
||||
<p class="hint">Acquisti fermati da notizie e calendario e come sarebbero finiti, dal @LabText.Day(r.RestrictionsFrom) e da quando Anubis è in funzione. La riga delle trimestrali non è misurata: agisce dentro la strategia, prima del segnale.</p>
|
||||
@if (restrictions.Count == 0)
|
||||
{
|
||||
<p class="note">Nessun acquisto fermato finora.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<caption class="sr-only">Perdite evitate e guadagni persi per restrizione</caption>
|
||||
<thead><tr><th scope="col">Restrizione</th><th scope="col">Periodo</th><th scope="col" class="num">Fermati</th><th scope="col" class="num">Perdite evitate</th><th scope="col" class="num">Guadagni persi</th><th scope="col">Senza esito</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var x in restrictions)
|
||||
{
|
||||
foreach (var (label, line) in new[] { ("Dall'ultima revisione", x.Period), ("Da sempre", x.Ever) })
|
||||
{
|
||||
<tr>
|
||||
<td>@x.Name</td>
|
||||
<td>@label</td>
|
||||
<td class="num">@(line?.Stopped ?? 0)</td>
|
||||
<td class="num">@LabText.Money(line?.Avoided ?? 0m, "EUR")</td>
|
||||
<td class="num">@LabText.Money(line?.GivenUp ?? 0m, "EUR")</td>
|
||||
<td>@ReviewView.Rest(line)</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public Review Review { get; set; } = null!;
|
||||
}
|
||||
@@ -49,6 +49,7 @@ internal static class LabText
|
||||
"okx" => "OKX",
|
||||
"alpaca" => "Alpaca",
|
||||
"binance" => "Binance",
|
||||
EuroHistory.Venue => "Binance convertito in euro",
|
||||
_ => venue,
|
||||
};
|
||||
|
||||
|
||||
@@ -199,7 +199,7 @@ internal sealed record LearningView
|
||||
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||
var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false);
|
||||
var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Of(snapshot, desk.BaseRates, capitals, aside, found, events, clock.UtcNow);
|
||||
return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>The page from what was read, without touching the database.</summary>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Learning;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>A row of the balance of the restrictions: this period and since the start.</summary>
|
||||
internal sealed record ReviewRestriction(string Name, RestrictionLine? Period, RestrictionLine? Ever);
|
||||
|
||||
/// <summary>A base rate before and after a review.</summary>
|
||||
internal sealed record ReviewRate(string Name, string Before, string After);
|
||||
|
||||
/// <summary>How the quarterly review (SPEC 12.2) is written for the user.</summary>
|
||||
internal static class ReviewView
|
||||
{
|
||||
public static string Verdict(ReviewLine line) => line.Verdict switch
|
||||
{
|
||||
ReviewVerdicts.Passed => "Superata",
|
||||
ReviewVerdicts.Rejected => "Non superata",
|
||||
ReviewVerdicts.Error => "Non riuscita",
|
||||
_ => "In attesa dei dati",
|
||||
};
|
||||
|
||||
public static string? VerdictClass(ReviewLine line) => line.Verdict switch
|
||||
{
|
||||
ReviewVerdicts.Passed => "gain",
|
||||
ReviewVerdicts.Rejected or ReviewVerdicts.Error => "loss",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>What changed for the strategy, as a sentence.</summary>
|
||||
public static string Action(ReviewLine line)
|
||||
{
|
||||
var text = QuarterlyReview.ActionText(line);
|
||||
return char.ToUpperInvariant(text[0]) + text[1..];
|
||||
}
|
||||
|
||||
/// <summary>How the strategy did live, in the words of its stage.</summary>
|
||||
public static IReadOnlyList<string> Live(ReviewLine line, IReadOnlyDictionary<string, double> rates)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
if (line.Stage == StrategyStages.Observation)
|
||||
{
|
||||
lines.Add(line.Signals == 0 ? "Nessun segnale chiuso dal vivo."
|
||||
: $"{Signals(line.Signals)}, in guadagno {LabText.Percent((double)line.Won / line.Signals, 0)}" + (rates.TryGetValue(line.Strategy, out var rate) ? $" (di solito {LabText.Percent(rate, 0)})." : "."));
|
||||
return lines;
|
||||
}
|
||||
|
||||
if (line.Live is not { } f)
|
||||
{
|
||||
return ["Niente da confrontare."];
|
||||
}
|
||||
|
||||
lines.Add($"Risultato {Fraction(f.Result, sign: true)}" + (line.BacktestOverSameDays is { } b ? $"; il backtest negli stessi giorni circa {LabText.Percent(b, 1, withSign: true)}." : "."));
|
||||
lines.Add($"Calo massimo {Fraction(f.Fall)}" + (line.ExpectedFall is { } e ? $", atteso {Fraction(e)}." : "."));
|
||||
lines.Add($"Scostamento dei prezzi {Bp(f.SlippageBp)}" + (line.ExpectedSlippageBp is { } s ? $", atteso {Bp(s)}." : "."));
|
||||
lines.Add($"Operazioni chiuse {f.Trades}" + (f.OneStep is { } step ? $"; decisioni identiche al backtest del giorno dopo {Fraction(1m - step)}." : "."));
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static string Signals(int count) => count == 1 ? "1 segnale chiuso" : $"{count} segnali chiusi";
|
||||
|
||||
private static string Fraction(decimal? value, bool sign = false) => value is { } v ? LabText.Percent((double)v, 1, sign) : LabText.Missing;
|
||||
|
||||
private static string Bp(decimal? value) => value is { } v ? Format.Quantity(Math.Round(v, 1)) + " punti base" : LabText.Missing;
|
||||
|
||||
public static IReadOnlyList<ReviewRate> Rates(ReviewReport report) =>
|
||||
[.. report.RatesBefore.Keys.Union(report.RatesAfter?.Keys ?? []).Order(StringComparer.Ordinal).Select(s => new ReviewRate(StrategyNames.Label(s, withMarket: true),
|
||||
report.RatesBefore.TryGetValue(s, out var before) ? LabText.Percent(before) : LabText.Missing,
|
||||
(report.RatesAfter ?? report.RatesBefore).TryGetValue(s, out var after) ? LabText.Percent(after) : LabText.Missing))];
|
||||
|
||||
public static IReadOnlyList<ReviewRestriction> Restrictions(ReviewReport report) =>
|
||||
[.. RestrictionBalance.Codes
|
||||
.Select(c => new ReviewRestriction(RestrictionBalance.Label(c), report.Restrictions.Lines.FirstOrDefault(l => l.Code == c), report.RestrictionsEver.Lines.FirstOrDefault(l => l.Code == c)))
|
||||
.Where(r => r.Period is not null || r.Ever is not null)];
|
||||
|
||||
/// <summary>The cases of a row that gave no amount, in words.</summary>
|
||||
public static string Rest(RestrictionLine? line)
|
||||
{
|
||||
if (line is null)
|
||||
{
|
||||
return LabText.Missing;
|
||||
}
|
||||
|
||||
var parts = new List<string>();
|
||||
void Add(int count, string one, string many)
|
||||
{
|
||||
if (count > 0)
|
||||
{
|
||||
parts.Add(count == 1 ? "1 " + one : $"{count} {many}");
|
||||
}
|
||||
}
|
||||
|
||||
Add(line.Open, "ancora aperta", "ancora aperte");
|
||||
Add(line.Delayed, "solo rimandata", "solo rimandate");
|
||||
Add(line.NeverStarted, "mai partita", "mai partite");
|
||||
Add(line.Increases, "aumento senza esito", "aumenti senza esito");
|
||||
return parts.Count == 0 ? LabText.Missing : string.Join(", ", parts);
|
||||
}
|
||||
|
||||
public static string Running(Review review) => review.Status == ReviewStatuses.Preparing
|
||||
? $"La revisione del {review.Title} aspetta gli archivi dei prezzi fino al {LabText.Day(review.Through)}: ci riprovo ogni notte, fino al {QuarterlyReview.LastDay} del mese."
|
||||
: $"La revisione del {review.Title} è in corso: i test sono nell'elenco qui sotto.";
|
||||
}
|
||||
@@ -245,11 +245,15 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, IReadOn
|
||||
|
||||
return stage.StageReason switch
|
||||
{
|
||||
"backtest_not_passed" or "observation_days" or "candidate" => $"Superato il backtest: dopo {StageBook.ObservationDays} giorni di osservazione può passare in simulazione.",
|
||||
"user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.",
|
||||
var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
|
||||
/// <summary>True for a report of the laboratory, which opens in the interface.</summary>
|
||||
public static bool IsPage(string? report) => report?.StartsWith('/') == true;
|
||||
|
||||
/// <summary>The report of a strategy's backtest: a file of the repository, or a page of the laboratory after a quarterly review.</summary>
|
||||
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
|
||||
}
|
||||
Reference in new issue
Block a user