diff --git a/docs/backtests/crypto_relative_momentum.outcome.json b/docs/backtests/crypto_relative_momentum.outcome.json index 62728cc..b14024b 100644 --- a/docs/backtests/crypto_relative_momentum.outcome.json +++ b/docs/backtests/crypto_relative_momentum.outcome.json @@ -4,6 +4,8 @@ "report": "docs/backtests/crypto_relative_momentum.md", "plan_hash": "373c7434e77dacb965704c49d41dc44d5719c92c634b0c3bad78a473ccc7440d", "parameters": "lookback=20;positions=2", + "through": "2026-10-31", + "strategy_version": "1", "max_drawdown": 0.3525, "expected_slippage_bp": 11.62, "round_trip_cost": 0.006324, diff --git a/docs/backtests/crypto_trend.outcome.json b/docs/backtests/crypto_trend.outcome.json index cdc0439..a725b17 100644 --- a/docs/backtests/crypto_trend.outcome.json +++ b/docs/backtests/crypto_trend.outcome.json @@ -4,6 +4,8 @@ "report": "docs/backtests/crypto_trend.md", "plan_hash": "b5f566d59bfae84f7c0821705d243dc0707803db36f74c1eecd130fb14fed8ed", "parameters": "coin_vol=10;max_stop=20", + "through": "2026-10-31", + "strategy_version": "1", "max_drawdown": 0.3278, "expected_slippage_bp": 11.94, "round_trip_cost": 0.006388, diff --git a/docs/backtests/equity_meanrev.md b/docs/backtests/equity_meanrev.md index 0e96292..ffcc3ee 100644 --- a/docs/backtests/equity_meanrev.md +++ b/docs/backtests/equity_meanrev.md @@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. -Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento. +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia può passare in simulazione dopo almeno 90 giorni di osservazione, dalla pagina Strategie. diff --git a/docs/backtests/equity_momentum.md b/docs/backtests/equity_momentum.md index bb5b331..ebb3cce 100644 --- a/docs/backtests/equity_momentum.md +++ b/docs/backtests/equity_momentum.md @@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. -Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento. +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia può passare in simulazione dopo almeno 90 giorni di osservazione, dalla pagina Strategie. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 6ef11a3..f3c45cd 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -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 diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor index 7155806..808e4dd 100644 --- a/src/Anubis.Server/Components/Pages/Laboratorio.razor +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -165,6 +165,31 @@ } +
+

Revisione trimestrale

+

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)}.")

+ @if (_reviews.FirstOrDefault(r => r.Status != ReviewStatuses.Done) is { } open) + { +

@ReviewView.Running(open)

+ } + @if (_reviews.Where(r => r.Report is not null).ToList() is { Count: > 0 } done) + { +

@done[0].Title

+ + @if (done.Count > 1) + { +

Revisioni precedenti: @foreach (var (r, i) in done.Skip(1).Select((r, i) => (r, i))) {@(i == 0 ? "" : ", ")@r.Title}

+ } + } + else + { +
+

Nessuna revisione ancora.

+

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.

+
+ } +
+

Migliorie in osservazione

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.

@@ -258,6 +283,8 @@ private IReadOnlyList _research = []; private IReadOnlyList _costs = []; private IReadOnlyList _improvements = []; + private IReadOnlyList _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 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); diff --git a/src/Anubis.Server/Components/Pages/LaboratorioRevisione.razor b/src/Anubis.Server/Components/Pages/LaboratorioRevisione.razor new file mode 100644 index 0000000..d7eeed8 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/LaboratorioRevisione.razor @@ -0,0 +1,41 @@ +@inherits LoadedComponent +@page "/laboratorio/revisione/{Id:guid}" +@inject AnubisHost Host +@inject ShellData Shell +@using Anubis.Backtest + +Revisione trimestrale · Anubis + +@if (_review is null) +{ + Torna al Laboratorio per l'elenco delle revisioni. + return; +} + +

← Laboratorio

+ +
+

Revisione del @_review.Title

+ @if (_review.Report is null) + { +

@ReviewView.Running(_review)

+ } + else + { +

Conclusa @Format.LongDateTime(_review.FinishedAt ?? _review.CreatedAt, Shell.Zone).

+ + } +
+ +@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); +} diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index b7482cb..01aaae4 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -204,7 +204,7 @@ var passed = s.Stage.Qualification?.Passed == true;
@s.Name
- @StrategiesView.ObservationReason(s.Stage)@if (report is not null) { Rapporto: @report} + @StrategiesView.ObservationReason(s.Stage)@if (StrategiesView.IsPage(report)) { Rapporto} else if (report is not null) { Rapporto: @report} @if (passed && !Shell.IsDemo) {
diff --git a/src/Anubis.Server/Components/ReviewReportView.razor b/src/Anubis.Server/Components/ReviewReportView.razor new file mode 100644 index 0000000..abbe955 --- /dev/null +++ b/src/Anubis.Server/Components/ReviewReportView.razor @@ -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); +} + +

Dati fino al @LabText.Day(Review.Through).@(r.Missing is { } missing ? $" Le crypto non sono state riprovate: {missing}." : "")

+ +
+ + + + + @foreach (var line in r.Strategies) + { + + + + + + + + } + +
Esito della revisione per strategia
StrategiaStadioEsitoCosa cambiaDal vivo
@StrategyNames.Label(line.Strategy, withMarket: true)@StrategyStages.Label(line.Stage) + @ReviewView.Verdict(line) + @if (line.Verdict != ReviewVerdicts.Waiting || r.Missing is not null && line.Strategy == CryptoTrendProtocol.Strategy) + { +
@line.Text + } + @foreach (var (id, i) in line.Trials.Select((id, i) => (id, i))) + { +
@(i == 0 ? "Test sull'universo ampio" : "Test su BTC, ETH e SOL") + } +
+ @ReviewView.Action(line) + @if (line.Chosen is { } chosen) + { +
Variante migliore: @LabText.Parameters(chosen.Parameters), Sharpe @LabText.Number(chosen.Sharpe), calo massimo @LabText.Percent(chosen.MaxDrawdown). + } + @if (line.InUse is { } used) + { +
Variante in uso: @LabText.Parameters(used.Parameters), Sharpe @LabText.Number(used.Sharpe), calo massimo @LabText.Percent(used.MaxDrawdown). Non cambia da sola. + } +
@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) {
@text
}
+
+ +

Frequenze di base

+@if (rates.Count == 0) +{ +

Nessuna frequenza misurata.

+} +else +{ +

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." : "")

+
+ @foreach (var rate in rates) + { +
@rate.Name
+
@(rate.Before == rate.After ? rate.After : $"da {rate.Before} a {rate.After}")
+ } +
+} + +

Bilancio delle restrizioni

+

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.

+@if (restrictions.Count == 0) +{ +

Nessun acquisto fermato finora.

+} +else +{ +
+ + + + + @foreach (var x in restrictions) + { + foreach (var (label, line) in new[] { ("Dall'ultima revisione", x.Period), ("Da sempre", x.Ever) }) + { + + + + + + + + + } + } + +
Perdite evitate e guadagni persi per restrizione
RestrizionePeriodoFermatiPerdite evitateGuadagni persiSenza esito
@x.Name@label@(line?.Stopped ?? 0)@LabText.Money(line?.Avoided ?? 0m, "EUR")@LabText.Money(line?.GivenUp ?? 0m, "EUR")@ReviewView.Rest(line)
+
+} + +@code { + [Parameter, EditorRequired] + public Review Review { get; set; } = null!; +} diff --git a/src/Anubis.Server/LabText.cs b/src/Anubis.Server/LabText.cs index 02e2b19..beab12a 100644 --- a/src/Anubis.Server/LabText.cs +++ b/src/Anubis.Server/LabText.cs @@ -49,6 +49,7 @@ internal static class LabText "okx" => "OKX", "alpaca" => "Alpaca", "binance" => "Binance", + EuroHistory.Venue => "Binance convertito in euro", _ => venue, }; diff --git a/src/Anubis.Server/LearningView.cs b/src/Anubis.Server/LearningView.cs index be7b1c0..22db6c8 100644 --- a/src/Anubis.Server/LearningView.cs +++ b/src/Anubis.Server/LearningView.cs @@ -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); } /// The page from what was read, without touching the database. diff --git a/src/Anubis.Server/ReviewView.cs b/src/Anubis.Server/ReviewView.cs new file mode 100644 index 0000000..6fd598e --- /dev/null +++ b/src/Anubis.Server/ReviewView.cs @@ -0,0 +1,105 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Learning; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A row of the balance of the restrictions: this period and since the start. +internal sealed record ReviewRestriction(string Name, RestrictionLine? Period, RestrictionLine? Ever); + +/// A base rate before and after a review. +internal sealed record ReviewRate(string Name, string Before, string After); + +/// How the quarterly review (SPEC 12.2) is written for the user. +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, + }; + + /// What changed for the strategy, as a sentence. + public static string Action(ReviewLine line) + { + var text = QuarterlyReview.ActionText(line); + return char.ToUpperInvariant(text[0]) + text[1..]; + } + + /// How the strategy did live, in the words of its stage. + public static IReadOnlyList Live(ReviewLine line, IReadOnlyDictionary rates) + { + var lines = new List(); + 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 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 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)]; + + /// The cases of a row that gave no amount, in words. + public static string Rest(RestrictionLine? line) + { + if (line is null) + { + return LabText.Missing; + } + + var parts = new List(); + 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."; +} diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs index f4ea2ac..4ca2890 100644 --- a/src/Anubis.Server/StrategiesView.cs +++ b/src/Anubis.Server/StrategiesView.cs @@ -245,11 +245,15 @@ internal sealed record StrategiesView(IReadOnlyList 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) + ".", }; } - /// The report of a strategy's backtest in the repository, for the link. + /// True for a report of the laboratory, which opens in the interface. + public static bool IsPage(string? report) => report?.StartsWith('/') == true; + + /// The report of a strategy's backtest: a file of the repository, or a page of the laboratory after a quarterly review. public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report; } diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 8c1d445..0323bea 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -73,6 +73,22 @@ public sealed partial class Laboratory : IDisposable public TrialStore Trials { get; } + /// Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did. + public Func? ReviewTrialEnded { get; set; } + + /// Runs trials already planned (those of a review). + public void Enqueue(IEnumerable ids) + { + ArgumentNullException.ThrowIfNull(ids); + foreach (var id in ids) + { + _queue.Writer.TryWrite(id); + } + } + + /// Heavy work on the thread of the trials. + public Task ComputeAsync(Func work) => _worker.RunAsync(work); + /// What the running trial is doing, in words; null when it is not running here. public string? Progress(Guid id) => _progress.GetValueOrDefault(id); @@ -188,6 +204,7 @@ public sealed partial class Laboratory : IDisposable } } + await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) { try @@ -203,6 +220,22 @@ public sealed partial class Laboratory : IDisposable } } + // A review that cannot conclude now is tried again by the next night. + private async Task ReviewEndedAsync(CancellationToken cancellationToken) + { + try + { + if (ReviewTrialEnded is { } ended) + { + await ended(cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + LogQueueFailed(_logger, ex); + } + } + /// One trial: load its data, compute on the worker thread, write the report. A failure is recorded, not thrown. public async Task ProcessAsync(Guid id, CancellationToken cancellationToken) { @@ -212,9 +245,10 @@ public sealed partial class Laboratory : IDisposable } _progress[id] = "lettura dei dati"; + Trial? trial = null; try { - var trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata."); + trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata."); if (!trial.PlanIntact) { throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte."); @@ -227,7 +261,7 @@ public sealed partial class Laboratory : IDisposable } var data = await LoadAsync(_db, _clock, _researchRoot, trial.Plan.Data, cancellationToken).ConfigureAwait(false); - var prior = await Trials.PriorAsync(trial.Strategy, id, cancellationToken).ConfigureAwait(false); + var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false); var now = _clock.UtcNow; var (report, summary) = await _worker.RunAsync( () => TrialRunner.Run(id, trial.Plan, trial.PlanHash, family, data, prior, now, text => _progress[id] = text, cancellationToken)).ConfigureAwait(false); @@ -247,6 +281,11 @@ public sealed partial class Laboratory : IDisposable { _progress.TryRemove(id, out _); } + + if (trial?.ReviewId is not null) + { + await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); + } } /// diff --git a/src/Anubis/Backtest/Protocol.cs b/src/Anubis/Backtest/Protocol.cs index 0561eb4..966fb45 100644 --- a/src/Anubis/Backtest/Protocol.cs +++ b/src/Anubis/Backtest/Protocol.cs @@ -82,11 +82,12 @@ public static class EuroHistory } /// Converts every daily USDT series of the Binance archives in the store. Returns the symbols written. - public static async Task> ConvertAllAsync(ResearchStore store, IReadOnlyList eurUsd, CancellationToken cancellationToken) + public static async Task> ConvertAllAsync(ResearchStore store, IReadOnlyList eurUsd, CancellationToken cancellationToken, IReadOnlyCollection? only = null) { ArgumentNullException.ThrowIfNull(store); var written = new List(); - foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == Venues.Binance && s.Timeframe == Timeframes.Day && s.Symbol.EndsWith("USDT", StringComparison.Ordinal))) + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == Venues.Binance && s.Timeframe == Timeframes.Day && s.Symbol.EndsWith("USDT", StringComparison.Ordinal) + && only?.Contains(s.Symbol) != false)) { var bars = new List(); await foreach (var bar in store.ReadAsync(Venues.Binance, symbol, Timeframes.Day, Ever.From, Ever.To, cancellationToken).ConfigureAwait(false)) @@ -116,8 +117,8 @@ public static class EuroHistory } } -/// A trial of the protocol: which universe, its report and the daily returns of the chosen variant. -public sealed record ProtocolRun(string Name, string Description, TrialPlan Plan, BacktestReport Report, IReadOnlyList DailyReturns, decimal ExpectedSlippageBp); +/// A trial of the protocol: which universe and its report. +public sealed record ProtocolRun(string Name, string Description, TrialPlan Plan, BacktestReport Report); /// What the protocol of a strategy concluded: the outcome file and the trials behind it. public sealed record ProtocolOutcome(Qualification Qualification, IReadOnlyList Runs); @@ -153,6 +154,10 @@ public static class CryptoTrendProtocol "SUIUSDT", "ARBUSDT", "OPUSDT", "ORDIUSDT", "ONTUSDT", "IOTAUSDT", "QTUMUSDT", "ICXUSDT", "XMRUSDT", "DASHUSDT", "ZECUSDT", "TONUSDT", "TRUMPUSDT", ]; + public const string BroadName = "Universo ampio"; + + public const string NarrowName = "BTC, ETH e SOL"; + /// Length of the expected path of the outcome: one year of daily closes. public const int PathDays = 365; @@ -165,21 +170,25 @@ public static class CryptoTrendProtocol } var family = StrategyCatalog.Find(Strategy) ?? throw new InvalidOperationException("crypto_trend non è nel catalogo."); - var first = await RunOneAsync(family, "Universo ampio", $"Le 10 monete con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).", + var first = await RunOneAsync(family, BroadName, $"Le 10 monete con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).", broad, to, now, researchRoot, PriorTrials.None, progress, cancellationToken).ConfigureAwait(false); var prior = new PriorTrials(1, first.Report.Variants.Count, [.. first.Report.Variants.Select(v => v.Sharpe)]); - var second = await RunOneAsync(family, "BTC, ETH e SOL", "Solo le tre coppie in euro con la liquidità migliore.", + var second = await RunOneAsync(family, NarrowName, "Solo le tre coppie in euro con la liquidità migliore.", Narrow, to, now, researchRoot, prior, progress, cancellationToken).ConfigureAwait(false); List runs = [first, second]; return new ProtocolOutcome(QualificationOf(runs), runs); } - /// Every converted pair with bars in the period: the strategy picks its top 10 month by month, among coins that died too. + /// + /// Every pair of with bars in the period: the strategy picks its top 10 month by month, among coins + /// that died too. A series of another coin in the same folder (the bot collects some) never changes the universe. + /// public static async Task> BroadAsync(ResearchStore store, DateOnly to, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(store); var broad = new List(); - foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day)) + var known = Archives.Select(EuroHistory.SymbolOf).ToHashSet(StringComparer.Ordinal); + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day && known.Contains(s.Symbol))) { if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false)) { @@ -196,7 +205,6 @@ public static class CryptoTrendProtocol ArgumentNullException.ThrowIfNull(runs); var main = runs[0]; var passed = runs.All(r => r.Report.Passed); - var it = CultureInfo.GetCultureInfo("it-IT"); string verdict; if (passed) { @@ -204,18 +212,25 @@ public static class CryptoTrendProtocol } else { - var failures = runs.Where(r => !r.Report.Passed) - .Select(r => r.Name + ": " + string.Join("; ", r.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, it)))); - verdict = "Protocollo non superato. " + string.Join(". ", failures) + ". Resta in osservazione."; + verdict = "Protocollo non superato. " + Failures(runs) + ". Resta in osservazione."; } return Measured(main, Strategy, passed, verdict, ReportPath); } + /// The checks the runs did not pass, in words. + public static string Failures(IReadOnlyList runs) + { + ArgumentNullException.ThrowIfNull(runs); + var it = CultureInfo.GetCultureInfo("it-IT"); + return string.Join(". ", runs.Where(r => !r.Report.Passed).Select(r => r.Name + ": " + string.Join("; ", r.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, it))))); + } + /// The figures an outcome keeps of the trial it comes from (SPEC 12.3), verdict aside. internal static Qualification Measured(ProtocolRun main, string strategy, bool passed, string verdict, string report) { var fee = StrategyNames.IsCrypto(strategy) ? PaperOptions.Okx().TakerFee : 0m; + var slippage = main.Report.ExpectedSlippageBp ?? (main.Plan.Slippage ?? SlippageTable.Standard).Bp(null); return new Qualification { Passed = passed, @@ -224,10 +239,11 @@ public static class CryptoTrendProtocol PlanHash = TrialPlan.Hash(main.Plan.ToJson()), Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters, MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4), - ExpectedSlippageBp = main.ExpectedSlippageBp, - RoundTripCost = Math.Round(2m * (fee + (main.ExpectedSlippageBp / 10_000m)), 6), - ExpectedPathP5 = [.. PathBootstrap.Percentile(main.DailyReturns, PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) - .Select(x => Math.Round(x, 4))], + ExpectedSlippageBp = slippage, + RoundTripCost = Math.Round(2m * (fee + (slippage / 10_000m)), 6), + ExpectedPathP5 = main.Report.ExpectedPathP5 ?? [], + Through = main.Plan.Data.To, + StrategyVersion = main.Plan.StrategyVersion, }; } @@ -259,17 +275,7 @@ public static class CryptoTrendProtocol // The id comes from the plan, so the same plan on the same data writes the same report. var id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(hash)).AsSpan(0, 16)); var (report, _) = TrialRunner.Run(id, plan, hash, family, data, prior, now, text => progress?.Invoke(name + ": " + text), cancellationToken); - - // The chosen variant again, for its daily returns and the slippage of what it traded. - var variant = ParameterGrid.Of(family, plan.Grid).First(v => v.ToString() == report.Chosen); - var options = StrategyPipeline.For(family.Id, data, new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }, plan.ReferenceShare); - var run = BacktestEngine.Run(family.Create(variant.Parameters), data, options); - var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); - var traded = run.Trades.Sum(t => t.Invested); - var slippage = traded > 0m - ? Math.Round(run.Trades.Sum(t => t.Invested * PaperBroker.SlippageBp(specs.GetValueOrDefault(t.Symbol))) / traded, 2) - : PaperBroker.SlippageBp(null); - return new ProtocolRun(name, description, plan, report, run.DailyReturns(), slippage); + return new ProtocolRun(name, description, plan, report); } private static async Task HasBarsAsync(ResearchStore store, string symbol, DateOnly to, CancellationToken cancellationToken) @@ -378,7 +384,7 @@ public static class EquityProtocol [ "Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.", "Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.", - "Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.", + "Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia può passare in simulazione dopo almeno 90 giorni di osservazione, dalla pagina Strategie.", ]; public static Qualification Waiting(string strategy) => new() diff --git a/src/Anubis/Backtest/QuarterlyReview.cs b/src/Anubis/Backtest/QuarterlyReview.cs new file mode 100644 index 0000000..0670aef --- /dev/null +++ b/src/Anubis/Backtest/QuarterlyReview.cs @@ -0,0 +1,435 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Learning; +using Anubis.Notifications; +using Anubis.Strategies; +using Anubis.Trading; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Backtest; + +public static class ReviewStatuses +{ + /// The history is being prepared, or not all published yet. + public const string Preparing = "preparing"; + + /// The trials are in the queue of the laboratory. + public const string Running = "running"; + + public const string Done = "done"; +} + +/// The figures of a variant on the broad universe. +public sealed record ReviewVariant(string Parameters, double Sharpe, decimal NetResult, double MaxDrawdown); + +/// A strategy in the report of a review: the verdict, what it did, and how the strategy did live. +public sealed record ReviewLine +{ + public required string Strategy { get; init; } + + /// The stage when the review concluded, before what it did. + public required string Stage { get; init; } + + public required string Verdict { get; init; } + + public required string Action { get; init; } + + /// The verdict in words. + public required string Text { get; init; } + + public IReadOnlyList Trials { get; init; } = []; + + public ReviewVariant? Chosen { get; init; } + + /// The variant the strategy runs with, when it is not the chosen one. + public ReviewVariant? InUse { get; init; } + + public StageFigures? Live { get; init; } + + /// What the strategy is compared with since it has its stage (SPEC 12.3). + public decimal? ExpectedFall { get; init; } + + public decimal? ExpectedSlippageBp { get; init; } + + /// The result of the backtest over the same days, approximate: the curve of the report is sampled. + public double? BacktestOverSameDays { get; init; } + + /// In observation: the live signals closed and how many won. + public int Signals { get; init; } + + public int Won { get; init; } +} + +/// The report of a quarterly review (SPEC 12.2): what is shown in the laboratory. +public sealed record ReviewReport +{ + /// What was missing to try again the crypto strategy; null when nothing was. + public string? Missing { get; init; } + + public IReadOnlyList Strategies { get; init; } = []; + + public IReadOnlyDictionary RatesBefore { get; init; } = new Dictionary(); + + /// The base rates of SPEC 11.1 after the review; null when they were not measured again. + public IReadOnlyDictionary? RatesAfter { get; init; } + + /// The balance of the restrictions since the review before, and since the bot started (SPEC 10.5). + public DateOnly RestrictionsFrom { get; init; } + + public RestrictionReport Restrictions { get; init; } = new([]); + + public RestrictionReport RestrictionsEver { get; init; } = new([]); +} + +/// A row of quarterly_reviews. +public sealed record Review(Guid Id, string Quarter, DateOnly Through, string Status, ReviewReport? Report, DateTimeOffset CreatedAt, DateTimeOffset? FinishedAt) +{ + /// "1º trimestre 2027". + public string Title => $"{Quarter[^1]}º trimestre {Quarter[..4]}"; +} + +/// +/// The quarterly review (SPEC 12.2): every three months the base strategies are tried again on the longer history with the +/// slippage estimates in force, compared with how they did live, and the report is published in the laboratory. It updates +/// the base rates of 11.1, demotes what no longer passes (12.3) and says what the restrictions avoided and cost (10.5). +/// Every step can be repeated: a restart halfway goes on from where it was, and a review concludes once. +/// +public sealed partial class QuarterlyReview(Database db, IClock clock, Laboratory lab, StageBook stages, LearningDesk learning, string researchRoot, + Func> prepare, ILogger? logger = null) +{ + public const string StateKey = "quarterly_review"; + + /// The first day of the quarter a review may start: the archive of the last month is published in the first days. + public const int FirstDay = 5; + + /// The last day it waits for that archive. + public const int LastDay = 15; + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + private readonly ILogger _logger = logger ?? NullLogger.Instance; + + private sealed record State(string Quarter); + + public static string QuarterOf(DateOnly day) => string.Create(CultureInfo.InvariantCulture, $"{day.Year:0000}-Q{((day.Month - 1) / 3) + 1}"); + + public static DateOnly StartOf(DateOnly day) => new(day.Year, (((day.Month - 1) / 3) * 3) + 1, 1); + + /// The day the next review may start, given the quarter of the last one (null: none yet, and the first quarter is only noted). + public static DateOnly NextDue(DateOnly today, string? last) + { + var start = StartOf(today); + return last is null || last == QuarterOf(today) ? start.AddMonths(3).AddDays(FirstDay - 1) : start.AddDays(FirstDay - 1); + } + + public static bool IsDue(DateOnly today, string? last) => last is not null && last != QuarterOf(today) && today >= NextDue(today, last); + + public static Task LastQuarterAsync(Database db, IClock clock, CancellationToken cancellationToken) => LastQuarterAsync(new LearningStore(db, clock), cancellationToken); + + private static async Task LastQuarterAsync(LearningStore store, CancellationToken cancellationToken) => + (await store.StateAsync(StateKey, cancellationToken).ConfigureAwait(false))?.Quarter; + + public static async Task> ListAsync(Database db, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + return await db.ReadAsync(s => s.QueryAsync("SELECT id, quarter, through, status, report, created_at, finished_at FROM quarterly_reviews ORDER BY created_at DESC, id DESC", Read), cancellationToken) + .ConfigureAwait(false); + } + + private static Review Read(DbRow r) => new(r.Id("id"), r.Text("quarter"), BarStore.ParseDay(r.Text("through")), r.Text("status"), + r.IsNull("report") ? null : JsonSerializer.Deserialize(r.Json("report").Text, TrialPlan.Json), r.Moment("created_at"), r.MomentOrNull("finished_at")); + + /// The nightly step: concludes a review whose trials are over, and starts the one that is due. + public async Task RunIfDueAsync(CancellationToken cancellationToken) + { + await ConcludeAsync(cancellationToken).ConfigureAwait(false); + var today = Zones.DayIn(clock.UtcNow, Zones.Rome); + var quarter = QuarterOf(today); + var last = await LastQuarterAsync(learning.Store, cancellationToken).ConfigureAwait(false); + if (last is null) + { + await db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, StateKey, new State(quarter), cancellationToken), cancellationToken).ConfigureAwait(false); + return; + } + + var open = (await ListAsync(db, cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Status != ReviewStatuses.Done); + if (open?.Status == ReviewStatuses.Running || !IsDue(today, last)) + { + return; + } + + // Several quarters missed make one review, on the history there is now (SPEC 5.6). + var through = new DateOnly(today.Year, today.Month, 1).AddDays(-1); + var id = await OpenAsync(open, quarter, through, cancellationToken).ConfigureAwait(false); + var missing = await prepare(through, cancellationToken).ConfigureAwait(false); + if (missing is not null) + { + if (today <= StartOf(today).AddDays(LastDay - 1)) + { + LogWaiting(_logger, quarter, missing); + return; + } + + await PublishAsync(id, quarter, through, missing, [], cancellationToken).ConfigureAwait(false); + return; + } + + lab.Enqueue(await PlanAsync(id, through, cancellationToken).ConfigureAwait(false)); + } + + private Task OpenAsync(Review? open, string quarter, DateOnly through, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var now = clock.UtcNow; + if (open is not null) + { + await s.ExecuteAsync("UPDATE quarterly_reviews SET quarter = @q, through = @d, updated_at = @t WHERE id = @id AND status = @p", cancellationToken, + ("q", quarter), ("d", BarStore.DayText(through)), ("t", now), ("id", open.Id), ("p", ReviewStatuses.Preparing)).ConfigureAwait(false); + return open.Id; + } + + var id = Ids.NewId(clock); + await s.ExecuteAsync("INSERT INTO quarterly_reviews (id, quarter, through, status, created_at, updated_at) VALUES (@id, @q, @d, @p, @t, @t)", cancellationToken, + ("id", id), ("q", quarter), ("d", BarStore.DayText(through)), ("p", ReviewStatuses.Preparing), ("t", now)).ConfigureAwait(false); + return id; + }, cancellationToken); + + /// The plans of the two universes, written together before any result, with the slippage in force now. + private async Task> PlanAsync(Guid id, DateOnly through, CancellationToken cancellationToken) + { + var costs = await new CostBook(db, clock).TableAsync(cancellationToken).ConfigureAwait(false); + var stage = await stages.GetAsync(CryptoTrendProtocol.Strategy, cancellationToken).ConfigureAwait(false); + var qualified = stage is { Stage: not StrategyStages.Observation }; + var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), through, cancellationToken).ConfigureAwait(false); + return await db.WriteAsync(async s => + { + var ids = new List(); + foreach (var symbols in new[] { broad, CryptoTrendProtocol.Narrow }) + { + var request = new TrialRequest(CryptoTrendProtocol.Strategy, TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, through, CryptoTrendProtocol.Capital, null); + var (plan, variants) = Laboratory.BuildPlan(request, clock.UtcNow, costs); + ids.Add(await TrialStore.PlanAsync(s, clock, plan with { Priors = qualified ? ReviewPriors.Review : ReviewPriors.All }, variants, id, cancellationToken).ConfigureAwait(false)); + } + + await s.ExecuteAsync("UPDATE quarterly_reviews SET status = @r, costs = @c, started_at = @t, updated_at = @t WHERE id = @id", cancellationToken, + ("r", ReviewStatuses.Running), ("c", new DbJson(JsonSerializer.Serialize(costs, TrialPlan.Json))), ("t", clock.UtcNow), ("id", id)).ConfigureAwait(false); + return ids; + }, cancellationToken).ConfigureAwait(false); + } + + /// Publishes the review whose trials are all over. One that is done, or not there, changes nothing. + public async Task ConcludeAsync(CancellationToken cancellationToken) + { + foreach (var review in (await ListAsync(db, cancellationToken).ConfigureAwait(false)).Where(r => r.Status == ReviewStatuses.Running)) + { + var trials = await lab.Trials.OfReviewAsync(review.Id, cancellationToken).ConfigureAwait(false); + if (trials.All(t => t.IsFinished)) + { + await PublishAsync(review.Id, review.Quarter, review.Through, null, trials, cancellationToken).ConfigureAwait(false); + } + } + } + + private sealed record CryptoResult(string Verdict, string Text, Qualification? Outcome, IReadOnlyList Runs); + + private async Task PublishAsync(Guid id, string quarter, DateOnly through, string? missing, IReadOnlyList trials, CancellationToken cancellationToken) + { + var previous = (await ListAsync(db, cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Id != id && r.Status == ReviewStatuses.Done); + var now = clock.UtcNow; + var today = Zones.DayIn(now, Zones.Rome); + var from = previous?.FinishedAt ?? new DateTimeOffset(StartOf(today).AddMonths(-3).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var all = (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => StrategyPipeline.IsBase(s.Strategy)).ToList(); + var crypto = await CryptoAsync(id, quarter, missing, trials, cancellationToken).ConfigureAwait(false); + var before = await learning.BaseRatesAsync(cancellationToken).ConfigureAwait(false); + var live = (await learning.Store.AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList(); + var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false); + var report = new ReviewReport + { + Missing = missing, + RatesBefore = before, + RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)), + RestrictionsFrom = Zones.DayIn(from, Zones.Rome), + Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, cancellationToken).ConfigureAwait(false), + RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, cancellationToken).ConfigureAwait(false), + }; + var lines = new List(); + foreach (var stage in all) + { + var line = new ReviewLine + { + Strategy = stage.Strategy, + Stage = stage.Stage, + Verdict = ReviewVerdicts.Waiting, + Action = ReviewActions.None, + Text = stage.Qualification?.Verdict ?? EquityProtocol.Waiting(stage.Strategy).Verdict, + Live = await stages.FiguresAsync(stage, cancellationToken).ConfigureAwait(false), + ExpectedFall = stage.Qualification?.MaxDrawdown, + ExpectedSlippageBp = stage.Qualification?.ExpectedSlippageBp, + Signals = live.Count(e => e.Strategy == stage.Strategy && e.IsLabelled), + Won = live.Count(e => e.Strategy == stage.Strategy && e.Label is { Win: true }), + }; + lines.Add(stage.Strategy == CryptoTrendProtocol.Strategy ? Measured(line, stage, crypto, trials) : line); + } + + await db.WriteAsync(async s => + { + // The row is taken first: of two conclusions at once, the night's and the laboratory's, the second finds it done. + if (await s.ExecuteAsync("UPDATE quarterly_reviews SET status = @d, updated_at = @t WHERE id = @id AND status <> @d", cancellationToken, ("id", id), ("d", ReviewStatuses.Done), ("t", now)).ConfigureAwait(false) == 0) + { + return; + } + + for (var i = 0; i < lines.Count; i++) + { + var line = lines[i]; + var outcome = line.Strategy == CryptoTrendProtocol.Strategy ? crypto.Outcome : null; + if (outcome is not null) + { + line = lines[i] = line with { Action = await stages.ApplyReviewAsync(s, line.Strategy, outcome, cancellationToken).ConfigureAwait(false) }; + } + + await s.ExecuteAsync( + "INSERT INTO review_outcomes (id, review_id, strategy, stage, verdict, action, through, trials, qualification, data, created_at) VALUES (@id, @r, @s, @st, @v, @a, @d, @tr, @q, @data, @t)", + cancellationToken, ("id", Ids.NewId(clock)), ("r", id), ("s", line.Strategy), ("st", line.Stage), ("v", line.Verdict), ("a", line.Action), ("d", BarStore.DayText(through)), + ("tr", new DbJson(JsonSerializer.Serialize(line.Trials))), ("q", outcome is null ? null : new DbJson(JsonSerializer.Serialize(outcome, Qualification.Json))), + ("data", new DbJson(JsonSerializer.Serialize(line, TrialPlan.Json))), ("t", now)).ConfigureAwait(false); + } + + if (examples is not null) + { + await learning.ReplaceHistoryAsync(s, CryptoTrendProtocol.Strategy, examples, live, through, id, cancellationToken).ConfigureAwait(false); + } + + var published = report with { Strategies = lines }; + await s.ExecuteAsync("UPDATE quarterly_reviews SET report = @rep, finished_at = @t WHERE id = @id", cancellationToken, + ("rep", new DbJson(JsonSerializer.Serialize(published, TrialPlan.Json))), ("t", now), ("id", id)).ConfigureAwait(false); + await LearningStore.SaveStateAsync(s, clock, StateKey, new State(quarter), cancellationToken).ConfigureAwait(false); + var text = Summary(quarter, published); + await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "quarterly_review", text, new { review = id }, cancellationToken).ConfigureAwait(false); + await NotificationSender.EnqueueAsync(s, clock, "quarterly_review", text, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + LogPublished(_logger, quarter, crypto.Verdict); + } + + private async Task CryptoAsync(Guid id, string quarter, string? missing, IReadOnlyList trials, CancellationToken cancellationToken) + { + if (missing is not null) + { + return new CryptoResult(ReviewVerdicts.Waiting, $"Non riprovata, dati mancanti: {missing}. Resta valido l'esito precedente.", null, []); + } + + if (trials.Count < 2 || trials.Any(t => t.Status != TrialStatuses.Done)) + { + return new CryptoResult(ReviewVerdicts.Error, "Un test non è riuscito: resta valido l'esito precedente.", null, []); + } + + // The broad universe comes first in every outcome of the protocol. + var runs = new List(); + foreach (var trial in trials.OrderBy(t => t.Plan.Data.Symbols.SequenceEqual(CryptoTrendProtocol.Narrow))) + { + var report = BacktestReport.FromJson(await lab.Trials.ReportJsonAsync(trial.Id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Rapporto non trovato.")); + runs.Add(new ProtocolRun(runs.Count == 0 ? CryptoTrendProtocol.BroadName : CryptoTrendProtocol.NarrowName, "", trial.Plan, report)); + } + + var passed = runs.All(r => r.Report.Passed); + var title = new Review(id, quarter, default, "", null, default, null).Title; + var text = passed + ? $"Revisione del {title}: protocollo superato su entrambi gli universi." + : $"Revisione del {title}: protocollo non superato. {CryptoTrendProtocol.Failures(runs)}."; + var outcome = CryptoTrendProtocol.Measured(runs[0], CryptoTrendProtocol.Strategy, passed, text, "/laboratorio/revisione/" + id); + return new CryptoResult(passed ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, text, outcome, runs); + } + + private static ReviewLine Measured(ReviewLine line, StrategyStage stage, CryptoResult crypto, IReadOnlyList trials) + { + line = line with { Verdict = crypto.Verdict, Text = crypto.Text, Trials = [.. trials.Select(t => t.Id)] }; + if (crypto.Runs.Count == 0) + { + return line; + } + + var report = crypto.Runs[0].Report; + ReviewVariant? Variant(Func which) => report.Variants.FirstOrDefault(which) is { } v ? new ReviewVariant(v.Parameters, v.Sharpe, v.NetResult, v.MaxDrawdown) : null; + var used = stage.Stage == StrategyStages.Observation ? null : stage.Qualification?.Parameters; + var since = DateOnly.FromDateTime((stage.StageSince ?? DateTimeOffset.MaxValue).UtcDateTime); + var days = report.Curve.Where(p => p.Day >= since).ToList(); + return line with + { + Chosen = Variant(v => v.Chosen), + InUse = used is null ? null : Variant(v => v.Parameters == used && !v.Chosen), + BacktestOverSameDays = days.Count > 1 && days[0].Equity > 0m ? (double)((days[^1].Equity / days[0].Equity) - 1m) : null, + }; + } + + // The examples of the longer history, with the parameters the strategy runs with from now on. Without them the base + // rates stay those of before: the review is published all the same. + private async Task?> ExamplesAsync(DateOnly through, CryptoResult crypto, List all, CancellationToken cancellationToken) + { + if (crypto.Outcome is not { } outcome) + { + return null; + } + + try + { + var stage = all.FirstOrDefault(s => s.Strategy == CryptoTrendProtocol.Strategy); + var parameters = stage is { Stage: not StrategyStages.Observation } ? stage.Qualification?.Parameters : outcome.Parameters; + var data = await FirstModel.DataAsync(researchRoot, through, cancellationToken).ConfigureAwait(false); + return await lab.ComputeAsync(() => FirstModel.ExamplesOf(data, parameters, through, null, cancellationToken)).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogExamplesFailed(_logger, ex); + return null; + } + } + + /// The review in a few words, for the diary and the notification. + public static string Summary(string quarter, ReviewReport report) + { + ArgumentNullException.ThrowIfNull(quarter); + ArgumentNullException.ThrowIfNull(report); + var parts = report.Strategies.Select(l => $"{StrategyNames.Label(l.Strategy, withMarket: true)}: {ActionText(l)}"); + var text = $"Revisione trimestrale pronta ({quarter[^1]}º trimestre {quarter[..4]}). {string.Join("; ", parts)}."; + if (!report.Restrictions.IsEmpty) + { + text += string.Create(It, $" Le restrizioni hanno evitato perdite per {report.Restrictions.Avoided:#,0.00} € e sono costate guadagni per {report.Restrictions.GivenUp:#,0.00} €."); + } + + return text + " Il rapporto è nel Laboratorio."; + } + + /// What a review said and did of a strategy, in a few words. + public static string ActionText(ReviewLine line) + { + ArgumentNullException.ThrowIfNull(line); + return line.Verdict switch + { + ReviewVerdicts.Waiting => "non riprovata, mancano i dati", + ReviewVerdicts.Error => "un test non è riuscito, resta valido l'esito precedente", + _ => line.Action switch + { + ReviewActions.Promoted => "superata, passa in simulazione", + ReviewActions.TooEarly => $"superata, può passare in simulazione dopo {StageBook.ObservationDays} giorni di osservazione", + ReviewActions.UserChoice => "superata, resta in osservazione perché ce l'hai messa tu", + ReviewActions.Confirmed => "superata, niente cambia", + ReviewActions.Held => "non superata, resta in simulazione e non può passare ai soldi veri", + ReviewActions.Demoted => "non superata, torna in simulazione", + _ => "non superata, resta in osservazione", + }, + }; + } + + [LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} waits: {Missing}")] + private static partial void LogWaiting(ILogger logger, string quarter, string missing); + + [LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} published, crypto_trend: {Verdict}")] + private static partial void LogPublished(ILogger logger, string quarter, string verdict); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Base rates not measured again by the quarterly review")] + private static partial void LogExamplesFailed(ILogger logger, Exception exception); +} diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index eeeb31f..5a95cdb 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -82,6 +82,12 @@ public sealed record BacktestReport( DateTimeOffset ComputedAt, double Seconds) { + /// The mean slippage of what the chosen variant bought, in basis points; null for the examples. + public decimal? ExpectedSlippageBp { get; init; } + + /// The 5th percentile of the expected path (SPEC 12.3) of the chosen variant; null for the examples. + public IReadOnlyList? ExpectedPathP5 { get; init; } + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty report"); @@ -229,6 +235,18 @@ public static class TrialRunner run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal), now, watch.Elapsed.TotalSeconds); + if (StrategyPipeline.ResearchShare(family.Id) is not null) + { + var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var table = plan.Slippage ?? SlippageTable.Standard; + var traded = run.Trades.Sum(x => x.Invested); + report = report with + { + ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null), + ExpectedPathP5 = [.. PathBootstrap.Percentile(returns[chosenIndex], CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) + .Select(x => Math.Round(x, 4))], + }; + } var summary = new TrialSummary(data.Currency, chosen.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, dsr.Value, pbo?.Probability, sharpes); diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 65615fc..0b96103 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -76,6 +76,9 @@ public sealed record TrialPlan( /// The slippage in force when the plan was written (SPEC 11.6); null for the standard one. public SlippageTable? Slippage { get; init; } + /// Which tries a trial of a quarterly review counts in its DSR (); null for the user's trials. + public string? Priors { get; init; } + public static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, @@ -92,6 +95,22 @@ public sealed record TrialPlan( public static string Hash(string json) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(json))); } +/// +/// The tries the DSR of a trial of a review counts (ADR 0020). It is fixed in the plan, so a trial resumed after a restart +/// counts the same. +/// +public static class ReviewPriors +{ + /// + /// A strategy already qualified: the same grid, fixed long ago, measured again on a longer history. Only the variants of + /// the first universe count, as when it qualified; otherwise time alone would demote it. + /// + public const string Review = "review"; + + /// A strategy in observation: trying until it passes is a search, so every earlier trial counts, and those it was first turned down with. + public const string All = "all"; +} + public static class TrialStatuses { public const string Planned = "planned"; @@ -140,6 +159,9 @@ public sealed record Trial( /// The stored plan text still gives the stored hash: nobody changed it after it was written. public bool PlanIntact { get; init; } = true; + + /// The quarterly review that registered it; null for the user's. + public Guid? ReviewId { get; init; } } /// The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios. @@ -154,22 +176,34 @@ public sealed record PriorTrials(int Trials, int Variants, IReadOnlyList /// public sealed class TrialStore(Database db, IClock clock) { - private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at"; + private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at, review_id"; public async Task PlanAsync(TrialPlan plan, int variants, CancellationToken cancellationToken) { + var id = await db.WriteAsync(s => PlanAsync(s, clock, plan, variants, null, cancellationToken), cancellationToken).ConfigureAwait(false); + return (await GetAsync(id, cancellationToken).ConfigureAwait(false))!; + } + + /// The same as part of a transaction: the plans of a quarterly review are written together. + public static async Task PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(plan); var id = Ids.NewId(clock); var json = plan.ToJson(); - var now = clock.UtcNow; - await db.WriteAsync(s => s.ExecuteAsync( - "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at) " + - "VALUES (@id, @s, @v, @p, @h, @n, @st, @now)", + await s.ExecuteAsync( + "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, review_id) " + + "VALUES (@id, @s, @v, @p, @h, @n, @st, @now, @rev)", cancellationToken, ("id", id), ("s", plan.Strategy), ("v", plan.StrategyVersion), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), - ("n", variants), ("st", TrialStatuses.Planned), ("now", now)), cancellationToken).ConfigureAwait(false); - return (await GetAsync(id, cancellationToken).ConfigureAwait(false))!; + ("n", variants), ("st", TrialStatuses.Planned), ("now", clock.UtcNow), ("rev", review)).ConfigureAwait(false); + return id; } + /// The trials of a review, in the order they were planned. + public async Task> OfReviewAsync(Guid review, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE review_id = @r ORDER BY created_at, id", Read, ("r", review)), cancellationToken).ConfigureAwait(false); + public Task GetAsync(Guid id, CancellationToken cancellationToken) => db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM backtest_trials WHERE id = @id", Read, ("id", id)), cancellationToken); @@ -221,6 +255,25 @@ public sealed class TrialStore(Database db, IClock clock) return new PriorTrials(rows.Count, rows.Sum(r => r.Variants), [.. rows.SelectMany(r => r.Summary?.VariantSharpes ?? [])]); } + /// The tries a trial counts: those of , or what its review fixed in the plan. + public async Task PriorOfAsync(Trial trial, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(trial); + switch (trial.Plan.Priors) + { + case ReviewPriors.Review: + var before = (await OfReviewAsync(trial.ReviewId ?? Guid.Empty, cancellationToken).ConfigureAwait(false)) + .Where(t => t.Strategy == trial.Strategy && t.Id != trial.Id && t.Status == TrialStatuses.Done).ToList(); + return new PriorTrials(before.Count, before.Sum(t => t.Variants), [.. before.SelectMany(t => t.Summary?.VariantSharpes ?? [])]); + case ReviewPriors.All: + // The protocol that turned it down tried the same grid on both universes; its ratios are not in this register. + var all = await PriorAsync(trial.Strategy, trial.Id, cancellationToken).ConfigureAwait(false); + return all with { Trials = all.Trials + 2, Variants = all.Variants + (2 * trial.Variants) }; + default: + return await PriorAsync(trial.Strategy, trial.Id, cancellationToken).ConfigureAwait(false); + } + } + private static Trial Read(DbRow r) { var plan = r.Json("plan").Text; @@ -241,6 +294,7 @@ public sealed class TrialStore(Database db, IClock clock) r.MomentOrNull("finished_at")) { PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"), + ReviewId = r.IdOrNull("review_id"), }; } } diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index c731481..4d487c0 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -170,6 +170,7 @@ public sealed partial class MarketDataService : IDisposable public void Dispose() { _work.Dispose(); + _archives.Dispose(); News.Dispose(); _http.Dispose(); _signed.Dispose(); @@ -437,15 +438,87 @@ public sealed partial class MarketDataService : IDisposable return states.First(s => s.Source == BinanceSource).Note ?? ""; } - var importer = new BinanceImporter(new ApiHttp(_http, _clock, BinanceSource), new ResearchStore(_data!.Research), _clock); - var bars = 0; - foreach (var coin in BinanceCoins) + var bars = await ImportArchivesAsync([.. BinanceCoins.Select(c => c + "USDT")], cancellationToken).ConfigureAwait(false); + return $"archivi Binance: {BinanceCoins.Count} monete, {bars} barre giornaliere lette"; + } + + // One at a time: the collection and the quarterly review write the same files. + private readonly SemaphoreSlim _archives = new(1, 1); + + private async Task ImportArchivesAsync(IReadOnlyList symbols, CancellationToken cancellationToken) + { + await _archives.WaitAsync(cancellationToken).ConfigureAwait(false); + try { - var result = await importer.ImportAsync(coin + "USDT", "1d", 2017, 8, cancellationToken).ConfigureAwait(false); - bars += result.Bars; + var importer = new BinanceImporter(new ApiHttp(_http, _clock, BinanceSource), new ResearchStore(_data!.Research), _clock); + var bars = 0; + foreach (var symbol in symbols) + { + bars += (await importer.ImportAsync(symbol, "1d", 2017, 8, cancellationToken).ConfigureAwait(false)).Bars; + } + + return bars; + } + finally + { + _archives.Release(); + } + } + + /// + /// The history the quarterly review needs (SPEC 12.2): the archives of the protocol through , turned + /// into euro. Null when it is ready; otherwise what is missing, in words. + /// + public async Task PrepareReviewHistoryAsync(DateOnly to, CancellationToken cancellationToken) + { + if (Offline || _data is null) + { + return "la raccolta dei dati è spenta"; } - return $"archivi Binance: {BinanceCoins.Count} monete, {bars} barre giornaliere lette"; + var rates = await new FxStore(_db, _clock).ListAsync("EUR", "USD", cancellationToken).ConfigureAwait(false); + if (rates.Count == 0) + { + return "mancano i cambi della BCE"; + } + + try + { + await ImportArchivesAsync(Backtest.CryptoTrendProtocol.Archives, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is MarketDataException or HttpRequestException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + LogStepFailed(_logger, ex, BinanceSource); + return "gli archivi di Binance non si scaricano"; + } + + var store = new ResearchStore(_data.Research); + await _archives.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await Backtest.EuroHistory.ConvertAllAsync(store, rates, cancellationToken, Backtest.CryptoTrendProtocol.Archives).ConfigureAwait(false); + } + finally + { + _archives.Release(); + } + + var day = new DateTimeOffset(to.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + foreach (var symbol in Backtest.CryptoTrendProtocol.Narrow) + { + var found = false; + await foreach (var _ in store.ReadAsync(Backtest.EuroHistory.Venue, symbol, Timeframes.Day, day, day.AddDays(1), cancellationToken).ConfigureAwait(false)) + { + found = true; + } + + if (!found) + { + return $"l'archivio di Binance di {to.ToString("MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("it-IT"))} non è ancora completo"; + } + } + + return null; } private async Task RefreshCalendarAsync(CancellationToken cancellationToken) diff --git a/src/Anubis/Data/ReferenceData.cs b/src/Anubis/Data/ReferenceData.cs index 477176d..aa90045 100644 --- a/src/Anubis/Data/ReferenceData.cs +++ b/src/Anubis/Data/ReferenceData.cs @@ -41,6 +41,11 @@ public sealed class FxStore(Database db, IClock clock) public Task LatestAsync(string baseCurrency, string quote, CancellationToken cancellationToken) => RateOnAsync(baseCurrency, quote, DateOnly.MaxValue, cancellationToken); + /// Every rate of a pair, oldest first. + public async Task> ListAsync(string baseCurrency, string quote, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync("SELECT base, quote, rate_date, rate, source FROM fx_rates WHERE base = @b AND quote = @q ORDER BY rate_date", Read, ("b", baseCurrency), ("q", quote)), + cancellationToken).ConfigureAwait(false); + private static FxRate Read(DbRow r) => new(r.Text("base"), r.Text("quote"), BarStore.ParseDay(r.Text("rate_date")), r.Money("rate"), r.Text("source")); } diff --git a/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql b/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql index 0b5a094..f34a3d5 100644 --- a/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql +++ b/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql @@ -34,3 +34,38 @@ CREATE TABLE company_sectors ( created_at {timestamp} NOT NULL, updated_at {timestamp} NOT NULL ){strict}; + +-- The quarterly reviews (SPEC 12.2): one for each quarter, with the slippage estimates it counted and what it published. +CREATE TABLE quarterly_reviews ( + id {uuid} PRIMARY KEY, + quarter TEXT NOT NULL UNIQUE, + through TEXT NOT NULL, + status TEXT NOT NULL, + costs {json}, + report {json}, + started_at {timestamp}, + finished_at {timestamp}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +-- What a review said of a strategy and what it did: passed, rejected, waiting (no data), error (a trial failed). +CREATE TABLE review_outcomes ( + id {uuid} PRIMARY KEY, + review_id {uuid} NOT NULL REFERENCES quarterly_reviews (id), + strategy TEXT NOT NULL, + stage TEXT NOT NULL, + verdict TEXT NOT NULL, + action TEXT NOT NULL, + through TEXT NOT NULL, + trials {json} NOT NULL, + qualification {json}, + data {json}, + created_at {timestamp} NOT NULL, + UNIQUE (review_id, strategy) +){strict}; + +CREATE INDEX review_outcomes_strategy ON review_outcomes (strategy, created_at); + +-- The trials a review registered; empty for those asked by the user. +ALTER TABLE backtest_trials ADD COLUMN review_id {uuid}; diff --git a/src/Anubis/Learning/FirstModel.cs b/src/Anubis/Learning/FirstModel.cs index bc2b4c6..2b5849d 100644 --- a/src/Anubis/Learning/FirstModel.cs +++ b/src/Anubis/Learning/FirstModel.cs @@ -57,6 +57,14 @@ public static class FirstModel /// Rebuilds the examples of crypto_trend on the broad universe of its protocol, then trains. public static async Task BuildAsync(string researchRoot, DateOnly to, Action? progress, CancellationToken cancellationToken) + { + var data = await DataAsync(researchRoot, to, cancellationToken).ConfigureAwait(false); + var parameters = BacktestOutcomes.Find(StrategyNames.CryptoTrend)?.Parameters; + return Train(ExamplesOf(data, parameters, to, n => progress?.Invoke(string.Create(CultureInfo.InvariantCulture, $"esempi: {n}")), cancellationToken), to, cancellationToken); + } + + /// The history of the broad universe of crypto_trend. + public static async Task DataAsync(string researchRoot, DateOnly to, CancellationToken cancellationToken) { var symbols = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false); if (symbols.Count == 0) @@ -64,12 +72,15 @@ public static class FirstModel throw new InvalidOperationException("Mancano gli storici delle crypto in euro: esegui prima anubis backtest base."); } - var data = await Laboratory.LoadResearchAsync(researchRoot, new TrialData(TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, to), cancellationToken).ConfigureAwait(false); - var parameters = BacktestOutcomes.Find(StrategyNames.CryptoTrend)?.Parameters; + return await Laboratory.LoadResearchAsync(researchRoot, new TrialData(TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, to), cancellationToken).ConfigureAwait(false); + } + + /// The examples of crypto_trend on that history, with the given parameters. + public static IReadOnlyList ExamplesOf(BacktestDataset data, string? parameters, DateOnly to, Action? progress, CancellationToken cancellationToken) + { var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = CryptoTrendProtocol.Capital, From = CryptoTrendProtocol.From, To = to }); - var examples = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, parameters), data, options, - n => progress?.Invoke(string.Create(CultureInfo.InvariantCulture, $"esempi: {n}")), cancellationToken); - return Train([.. examples.Select(WithStableId)], to, cancellationToken); + var examples = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, parameters), data, options, progress, cancellationToken); + return [.. examples.Select(WithStableId)]; } public static FirstModelFile Train(IReadOnlyList examples, DateOnly through, CancellationToken cancellationToken = default) diff --git a/src/Anubis/Learning/LearningCycle.cs b/src/Anubis/Learning/LearningCycle.cs index 0cd9b13..98a15d9 100644 --- a/src/Anubis/Learning/LearningCycle.cs +++ b/src/Anubis/Learning/LearningCycle.cs @@ -139,7 +139,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, var today = Zones.DayIn(now, Zones.Rome); var labelled = snapshot.Of(champion.Id); var health = Health.Check(champion, labelled, [.. snapshot.Examples.Where(e => e.Source == CaseSources.Live)], now); - var activation = ActivationCheck.Of(snapshot.InCharge, desk.BaseRates, await CapitalsAsync(cancellationToken).ConfigureAwait(false)); + var activation = ActivationCheck.Of(snapshot.InCharge, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), await CapitalsAsync(cancellationToken).ConfigureAwait(false)); var state = snapshot.State; var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now }; if (state.ActivatedAt is null && activation.Passed) @@ -232,7 +232,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, /// The trial: a decision only when the cases have passed a new threshold (SPEC 11.4). private async Task JudgeAsync(LearningSnapshot snapshot, ModelRow champion, ModelRow challenger, DateOnly sunday, CancellationToken cancellationToken) { - var check = TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), desk.BaseRates); + var check = TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false)); var state = snapshot.State with { LastSunday = sunday }; await db.WriteAsync(async s => { @@ -262,7 +262,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, CancellationToken cancellationToken) { // A strategy without a base rate is not estimated, so it does not train either (ADR 0018). - var rates = desk.BaseRates; + var rates = await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false); var examples = snapshot.Examples.Where(e => e.IsLabelled && rates.ContainsKey(e.Strategy)).ToList(); var state = snapshot.State with { LastSunday = sunday }; var seen = state.TrainedOn > 0 ? state.TrainedOn : snapshot.Champion?.Examples ?? 0; diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs index 6179bc9..612c60e 100644 --- a/src/Anubis/Learning/LearningDesk.cs +++ b/src/Anubis/Learning/LearningDesk.cs @@ -96,11 +96,63 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor /// The file of the first model; the one built into the program unless a test gives another. public FirstModelFile? First { get; init; } = FirstModel.Embedded; - public IReadOnlyDictionary BaseRates => First?.BaseRates ?? new Dictionary(); + /// + /// The base rates in force (SPEC 11.1): those of the last quarterly review or those of the program, strategy by strategy + /// whichever were measured on the longer history. + /// + public async Task> BaseRatesAsync(CancellationToken cancellationToken) + { + var built = First?.BaseRates ?? new Dictionary(); + return await Store.StateAsync(RatesKey, cancellationToken).ConfigureAwait(false) is not { } stored ? built + : stored.Through > (First?.Through ?? DateOnly.MinValue) ? Merge(built, stored.Rates) + : Merge(stored.Rates, built); + } + + /// The rates of , and of where there is none. + public static IReadOnlyDictionary Merge(IReadOnlyDictionary older, IReadOnlyDictionary newer) + { + ArgumentNullException.ThrowIfNull(older); + ArgumentNullException.ThrowIfNull(newer); + return older.Where(p => !newer.ContainsKey(p.Key)).Concat(newer).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal); + } private const string HistoryKey = "history"; - private sealed record HistoryState(string Fingerprint); + private const string RatesKey = "base_rates"; + + // Reviewed: the strategies whose examples come from a quarterly review, and through which day. + private sealed record HistoryState(string Fingerprint, Dictionary? Reviewed = null); + + private sealed record ReviewedRates(Dictionary Rates, DateOnly Through, Guid Review); + + /// + /// The examples of a longer history take the place of the old ones of a strategy, and its base rate changes with them + /// (SPEC 11.1, 12.2): part of the transaction that publishes a review. The model in charge is not replaced. + /// + public async Task ReplaceHistoryAsync(DbSession s, string strategy, IReadOnlyList examples, IReadOnlyList live, DateOnly through, Guid review, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(examples); + ArgumentNullException.ThrowIfNull(live); + await ReplaceAsync(s, strategy, examples, live, cancellationToken).ConfigureAwait(false); + var rates = new Dictionary(Trainer.SharesOf(examples), StringComparer.Ordinal); + await LearningStore.SaveStateAsync(s, clock, RatesKey, new ReviewedRates(rates, through, review), cancellationToken).ConfigureAwait(false); + var json = await s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", HistoryKey)).ConfigureAwait(false); + var state = json is null ? new HistoryState("") : System.Text.Json.JsonSerializer.Deserialize(json)!; + var reviewed = new Dictionary(state.Reviewed ?? [], StringComparer.Ordinal) { [strategy] = through }; + await LearningStore.SaveStateAsync(s, clock, HistoryKey, state with { Reviewed = reviewed }, cancellationToken).ConfigureAwait(false); + } + + private async Task ReplaceAsync(DbSession s, string strategy, IEnumerable examples, IReadOnlyList live, CancellationToken cancellationToken) + { + await s.ExecuteAsync("DELETE FROM ml_labels WHERE feature_id IN (SELECT id FROM ml_features WHERE source = @h AND strategy = @s)", cancellationToken, ("h", CaseSources.History), ("s", strategy)) + .ConfigureAwait(false); + await s.ExecuteAsync("DELETE FROM ml_features WHERE source = @h AND strategy = @s", cancellationToken, ("h", CaseSources.History), ("s", strategy)).ConfigureAwait(false); + foreach (var example in examples.Where(e => !live.Any(l => SameOperation(l, e)))) + { + await LearningStore.AddAsync(s, clock, example, cancellationToken).ConfigureAwait(false); + } + } /// /// At the start (SPEC 11.2): the examples of the history in the program, when they changed, take the place of the old @@ -114,11 +166,15 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor } var fingerprint = FirstModel.Fingerprint(file); - if (await Store.StateAsync(HistoryKey, cancellationToken).ConfigureAwait(false) is { } state && state.Fingerprint == fingerprint) + var state = await Store.StateAsync(HistoryKey, cancellationToken).ConfigureAwait(false); + if (state?.Fingerprint == fingerprint) { return; } + // A strategy a review measured on a longer history keeps those examples. + var kept = (state?.Reviewed ?? []).Where(p => p.Value > file.Through).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal); + var live = new List(); foreach (var strategy in file.Examples.Select(e => e.Strategy).Distinct(StringComparer.Ordinal)) { @@ -127,11 +183,10 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor await db.WriteAsync(async s => { - await s.ExecuteAsync("DELETE FROM ml_labels WHERE feature_id IN (SELECT id FROM ml_features WHERE source = @h)", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false); - await s.ExecuteAsync("DELETE FROM ml_features WHERE source = @h", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false); - foreach (var example in file.Examples.Where(e => !live.Any(l => SameOperation(l, e)))) + var old = await s.QueryAsync("SELECT DISTINCT strategy FROM ml_features WHERE source = @h", r => r.Text("strategy"), ("h", CaseSources.History)).ConfigureAwait(false); + foreach (var strategy in old.Concat(file.Examples.Select(e => e.Strategy)).Distinct(StringComparer.Ordinal).Where(x => !kept.ContainsKey(x))) { - await LearningStore.AddAsync(s, clock, example, cancellationToken).ConfigureAwait(false); + await ReplaceAsync(s, strategy, file.Examples.Where(e => e.Strategy == strategy), live, cancellationToken).ConfigureAwait(false); } if (file.Model is { } model && file.Report is { } report && await s.CountAsync("SELECT COUNT(*) FROM ml_models").ConfigureAwait(false) == 0) @@ -143,7 +198,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor cancellationToken).ConfigureAwait(false); } - await LearningStore.SaveStateAsync(s, clock, HistoryKey, new HistoryState(fingerprint), cancellationToken).ConfigureAwait(false); + await LearningStore.SaveStateAsync(s, clock, HistoryKey, new HistoryState(fingerprint, kept), cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } @@ -161,7 +216,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor var (rule, aside) = await LearningSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); var state = await CycleAsync(cancellationToken).ConfigureAwait(false); return new ModelGate(await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false), - await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, BaseRates, state is { ActivatedAt: not null, Aside: null } && !aside) + await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, await BaseRatesAsync(cancellationToken).ConfigureAwait(false), state is { ActivatedAt: not null, Aside: null } && !aside) { Aside = state.Aside is not null || aside, }; diff --git a/src/Anubis/Learning/RestrictionBalance.cs b/src/Anubis/Learning/RestrictionBalance.cs new file mode 100644 index 0000000..0919bfb --- /dev/null +++ b/src/Anubis/Learning/RestrictionBalance.cs @@ -0,0 +1,139 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Db; +using Anubis.News; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Learning; + +/// An entry a rule of SPEC 10.5 stopped or put off, as the decisions recorded it. +public sealed record BlockedEntry(Guid DecisionId, string Strategy, string Symbol, string Code, bool Postponed, DateTimeOffset At); + +/// An operation really opened on an account. +public sealed record HeldTrade(string Strategy, string Symbol, DateTimeOffset OpenedAt, DateTimeOffset? ClosedAt); + +/// +/// What a row of 10.5 did: how many entries it kept out, the losses it avoided and the gains it gave up (both positive +/// euro), and the cases that say nothing: still open, never started, only put off, increases of an operation already open. +/// +public sealed record RestrictionLine(string Code, int Stopped, decimal Avoided, decimal GivenUp, int Open, int NeverStarted, int Delayed, int Increases); + +public sealed record RestrictionReport(IReadOnlyList Lines) +{ + public decimal Avoided => Lines.Sum(l => l.Avoided); + + public decimal GivenUp => Lines.Sum(l => l.GivenUp); + + public bool IsEmpty => Lines.Count == 0; +} + +/// +/// The balance of the restrictions (SPEC 10.5): an entry they stop stays among the examples with its simulated outcome, so +/// the quarterly review can say what they avoided and what they cost. The earnings row acts inside its strategy and leaves +/// no example: it is not measured. +/// +public static class RestrictionBalance +{ + /// The rows that can be measured, the strictest first. + public static readonly IReadOnlyList Codes = [NewsReasons.Severe, NewsReasons.Negative, CorrectiveReasons.CalendarEvent]; + + public static string Label(string code) => code switch + { + NewsReasons.Severe => "Evento grave confermato", + NewsReasons.Negative => "Notizia negativa confermata", + CorrectiveReasons.CalendarEvent => "Dato economico ad alto impatto", + _ => code, + }; + + /// The balance of the entries blocked; each example counts once, under its strictest row. + public static RestrictionReport Of(IReadOnlyList blocked, IReadOnlyList examples, IReadOnlyList trades, IReadOnlyDictionary capitals) + { + ArgumentNullException.ThrowIfNull(blocked); + ArgumentNullException.ThrowIfNull(examples); + ArgumentNullException.ThrowIfNull(trades); + ArgumentNullException.ThrowIfNull(capitals); + var lines = Codes.ToDictionary(c => c, c => new RestrictionLine(c, 0, 0m, 0m, 0, 0, 0, 0), StringComparer.Ordinal); + var cases = new Dictionary Blocks)>(); + foreach (var block in blocked.Where(b => lines.ContainsKey(b.Code)).OrderBy(b => b.At)) + { + var own = trades.Where(t => t.Strategy == block.Strategy && t.Symbol == block.Symbol).ToList(); + var example = examples.FirstOrDefault(e => e.DecisionId == block.DecisionId && e.Symbol == block.Symbol && e.Strategy == block.Strategy) + ?? examples.Where(e => e.Strategy == block.Strategy && e.Symbol == block.Symbol && e.At <= block.At && e.IsOpenAfter(DateOnly.FromDateTime(block.At.UtcDateTime))) + .OrderByDescending(e => e.At).FirstOrDefault(); + if (example is null || own.Any(t => t.OpenedAt < block.At && (t.ClosedAt is null || t.ClosedAt > block.At))) + { + lines[block.Code] = lines[block.Code] with { Increases = lines[block.Code].Increases + 1 }; + continue; + } + + if (!cases.TryGetValue(example.Id, out var entry)) + { + cases[example.Id] = entry = (example, []); + } + + entry.Blocks.Add(block); + } + + foreach (var (example, blocks) in cases.Values) + { + var code = Codes.First(c => blocks.Any(b => b.Code == c)); + var line = lines[code]; + var first = blocks[0].At; + var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue; + + // In observation nothing is ever bought: an entry only put off would have been made at its end. + var delayed = example.Stage == StrategyStages.Observation + ? blocks.All(b => b.Postponed) + : trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last); + if (delayed) + { + lines[code] = line with { Delayed = line.Delayed + 1 }; + } + else if (example.Label is not { } label) + { + lines[code] = line with { Open = line.Open + 1 }; + } + else if (label.Win is null || label.Result is not { } result) + { + lines[code] = line with { NeverStarted = line.NeverStarted + 1 }; + } + else + { + var amount = Math.Round((decimal)(result * (double)example.Weight * example.Multiplier * capitals.GetValueOrDefault(example.Strategy)), 2, MidpointRounding.ToEven); + lines[code] = line with { Stopped = line.Stopped + 1, Avoided = line.Avoided + Math.Max(0m, -amount), GivenUp = line.GivenUp + Math.Max(0m, amount) }; + } + } + + return new RestrictionReport([.. Codes.Select(c => lines[c]).Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]); + } + + /// The balance of the entries blocked from a moment on. + public static async Task LoadAsync(Database db, IClock clock, DateTimeOffset from, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT decision_id, strategy, symbol, outcome, reasons, created_at FROM decisions WHERE symbol IS NOT NULL AND stage IN (@c, @o) AND outcome IN (@r, @p) AND created_at >= @f ORDER BY created_at, id", + r => (Id: r.Id("decision_id"), Strategy: r.Text("strategy"), Symbol: r.Text("symbol"), Outcome: r.Text("outcome"), Reasons: r.Json("reasons").Text, At: r.Moment("created_at")), + ("c", DecisionStages.Correctives), ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed), ("f", from)), cancellationToken).ConfigureAwait(false); + var blocked = new List(); + foreach (var row in rows) + { + var codes = JsonSerializer.Deserialize>(row.Reasons) ?? []; + if (Codes.FirstOrDefault(c => codes.Contains(c, StringComparer.Ordinal)) is { } code) + { + blocked.Add(new BlockedEntry(row.Id, row.Strategy, row.Symbol, code, row.Outcome == DecisionOutcomes.Postponed, row.At)); + } + } + + if (blocked.Count == 0) + { + return new RestrictionReport([]); + } + + var trades = await db.ReadAsync(s => s.QueryAsync("SELECT t.strategy, i.symbol, t.opened_at, t.closed_at FROM trades t JOIN instruments i ON i.id = t.instrument_id", + r => new HeldTrade(r.Text("strategy"), r.Text("symbol"), r.Moment("opened_at"), r.MomentOrNull("closed_at"))), cancellationToken).ConfigureAwait(false); + var examples = (await new LearningStore(db, clock).AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList(); + return Of(blocked, examples, trades, await LearningCycle.CapitalsAsync(db, clock, cancellationToken).ConfigureAwait(false)); + } +} diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 14d77de..393477b 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -1331,20 +1331,23 @@ public sealed partial class LiveEngine : IDisposable private static string OrderWords(Planned order, string symbol) => (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); - private Task CloseAsync(Planned order, string status, string? reason, Guid? execution, string? diary, CancellationToken cancellationToken) => - _db.WriteAsync(async s => + private async Task CloseAsync(Planned order, string status, string? reason, Guid? execution, string? diary, CancellationToken cancellationToken) + { + var symbol = (await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol; + await _db.WriteAsync(async s => { var now = _clock.UtcNow; await s.ExecuteAsync("UPDATE planned_orders SET status = @st, outcome = @o, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, ("st", status), ("o", reason), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false); - await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, null, DecisionStages.Order, + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, symbol, DecisionStages.Order, status == PlannedStates.Submitted ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, reason is null ? [] : [reason], new Dictionary { ["planned"] = order.Id, ["execution"] = execution, ["side"] = Wire.Text(order.Side) }, now), cancellationToken).ConfigureAwait(false); if (diary is not null) { await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, reason ?? LiveReasons.Recovered, diary, new { planned = order.Id }, cancellationToken).ConfigureAwait(false); } - }, cancellationToken); + }, cancellationToken).ConfigureAwait(false); + } // ---- Books, data and history ------------------------------------------------------------------------------ diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 820229b..2f43894 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -54,6 +54,22 @@ public sealed record Qualification /// public string? Parameters { get; init; } + /// The last day of the history it was measured on; null in the outcomes written before the quarterly reviews. + public DateOnly? Through { get; init; } + + /// The version of the rules it was measured with. + public string? StrategyVersion { get; init; } + + /// + /// True when this outcome, stored by a quarterly review, stays in force against , the one built + /// into the program: same rules, measured on a later history (SPEC 12.2). + /// + public bool Outlives(Qualification other) + { + ArgumentNullException.ThrowIfNull(other); + return Through is { } mine && mine > (other.Through ?? DateOnly.MinValue) && StrategyVersion is { } version && (other.StrategyVersion ?? version) == version; + } + /// Largest fall of the backtest, as a fraction of the capital used: 0.18 is −18%. public decimal MaxDrawdown { get; init; } @@ -111,6 +127,50 @@ public sealed record Requirement(string Key, string Label, string Value, string /// A condition of automatic demotion in progress (SPEC 12.3). public sealed record DemotionCondition(string Key, string Message); +/// What a quarterly review says of a strategy (SPEC 12.2). +public static class ReviewVerdicts +{ + public const string Passed = "passed"; + public const string Rejected = "rejected"; + + /// It could not be tried again: no data, or no history yet. + public const string Waiting = "waiting"; + + /// A trial did not finish. + public const string Error = "error"; +} + +/// What a quarterly review did to a strategy. +public static class ReviewActions +{ + /// In observation, not passed: it stays there. + public const string Stays = "stays"; + + /// In observation, passed, but not 90 days yet. + public const string TooEarly = "too_early"; + + /// In observation by the user's choice: only they take it out. + public const string UserChoice = "user_choice"; + + /// From observation to simulation. + public const string Promoted = "promoted"; + + /// With capital, passed: nothing changes. + public const string Confirmed = "confirmed"; + + /// In simulation, not passed: it cannot go to real money until a review passes. + public const string Held = "held"; + + /// With real money, not passed: back to simulation at the hourly check. + public const string Demoted = "demoted"; + + /// Nothing was tried. + public const string None = "none"; +} + +/// A strategy since its stage began: result and largest fall as fractions, slippage, closed trades, share of one-step differences. +public sealed record StageFigures(DateTimeOffset Since, decimal? Result, decimal? Fall, decimal? SlippageBp, int Trades, decimal? OneStep); + /// What the user confirms with the procedure of SPEC 12.4. public sealed record LiveConfirmation(string Strategy, Guid LiveAccountId, string Phrase, string Password, string? Code, string By); @@ -231,8 +291,8 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, var json = new DbJson(JsonSerializer.Serialize(qualification, Qualification.Json)); await db.WriteAsync(async s => { - var current = await s.FirstOrDefaultAsync("SELECT stage, stage_since FROM strategy_state WHERE strategy = @s", - r => (Stage: r.Text("stage"), Since: r.MomentOrNull("stage_since")), ("s", strategy)).ConfigureAwait(false); + var current = await s.FirstOrDefaultAsync("SELECT stage, qualification FROM strategy_state WHERE strategy = @s", + r => (Stage: r.Text("stage"), Stored: r.TextOrNull("qualification")), ("s", strategy)).ConfigureAwait(false); // With real money in play the figures a strategy qualified with do not move (SPEC 12.3): a new build cannot // change the thresholds of its demotion. It gets the new outcome when it is back in simulation. if (current == default || StrategyStages.IsLive(current.Stage)) @@ -240,6 +300,12 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return; } + // A quarterly review measured it on a later history (SPEC 12.2): the outcome of the program is the older one. + if (current.Stored is { } stored && JsonSerializer.Deserialize(stored, Qualification.Json) is { } reviewed && reviewed.Outlives(qualification)) + { + return; + } + await s.ExecuteAsync("UPDATE strategy_state SET qualification = @q, updated_at = @t WHERE strategy = @s", cancellationToken, ("q", json), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); var moved = await s.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) > 0; @@ -248,15 +314,16 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return; } - // A candidate (SPEC 8.4) has no capital and no order code: whatever its outcome, it stays in observation. - if (qualification.Passed && !StrategyNames.IsCandidate(strategy)) + // Only the first start moves a strategy by itself (SPEC 12.3): one that passes later needs its 90 days like any + // other. A candidate (SPEC 8.4) has no capital and no order code: whatever its outcome, it stays in observation. + if (qualification.Passed && current.Stored is null && !StrategyNames.IsCandidate(strategy)) { await MoveCoreAsync(s, strategy, current.Stage, StrategyStages.Simulation, "backtest_passed", "primo avvio", cancellationToken).ConfigureAwait(false); } else { await s.ExecuteAsync("UPDATE strategy_state SET stage_reason = @r, stage_since = COALESCE(stage_since, @t), updated_at = @t WHERE strategy = @s", cancellationToken, - ("r", qualification.Passed ? "candidate" : "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + ("r", !qualification.Passed ? "backtest_not_passed" : StrategyNames.IsCandidate(strategy) ? "candidate" : "observation_days"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); } @@ -352,7 +419,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, var oneStep = await OneStepAsync(strategy, since, cancellationToken).ConfigureAwait(false); list.Add(new("one_step", "Coerenza con il backtest (confronto a un passo)", oneStep is { } share ? Format.Percent(share * 100m, 1) : "da misurare", "sotto il 2%", oneStep is { } d && d < MaxOneStepDifference)); - var slippage = await SlippageAsync(stage.AccountId, since, cancellationToken).ConfigureAwait(false); + var slippage = await SlippageAsync(stage.AccountId, strategy, since, cancellationToken).ConfigureAwait(false); var simulator = await EnvironmentOfAsync(stage.AccountId, cancellationToken).ConfigureAwait(false) == TradingEnvironments.Simulation; var expected = q?.ExpectedSlippageBp ?? 0m; list.Add(new("slippage", "Prezzi ottenuti rispetto al previsto", @@ -366,7 +433,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, var incidents = await CriticalIncidentsAsync(now - TimeSpan.FromDays(IncidentDays), cancellationToken).ConfigureAwait(false); list.Add(new("incidents", "Incidenti critici negli ultimi 30 giorni", incidents.ToString(Italian), "nessuno", incidents == 0)); - var demotions = StrategyStages.IsLive(stage.Stage) ? await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false) : []; + var demotions = await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false); list.Add(new("demotion", "Condizioni di retrocessione in corso", demotions.Count == 0 ? "nessuna" : string.Join("; ", demotions.Select(d => d.Message)), "nessuna", demotions.Count == 0)); return list; @@ -520,7 +587,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, /// Automatic demotion (SPEC 12.3): like a revocation, with an alert and a risk event. public Task DemoteAsync(string strategy, string reason, CancellationToken cancellationToken) => - LeaveLiveAsync(strategy, "automatico", reason, automatic: true, cancellationToken); + LeaveLiveAsync(strategy, AutomaticBy, reason, automatic: true, cancellationToken); /// Demotes every strategy with real money that has a condition of SPEC 12.3 in progress. Returns those demoted. public async Task> CheckDemotionsAsync(CancellationToken cancellationToken) @@ -565,16 +632,21 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return released; } - /// The conditions of automatic demotion of SPEC 12.3 in progress for a strategy with real money. + /// The conditions of automatic demotion of SPEC 12.3 in progress, on the account that takes the orders: they demote a strategy with real money and keep one in simulation from advancing. public async Task> DemotionConditionsAsync(StrategyStage stage, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(stage); var list = new List(); - if (stage.LiveAccountId is not { } account || stage.Qualification is not { } q) + if (stage.OrdersAccount is not { } account || stage.Qualification is not { } q) { return list; } + if (await ReviewVerdictAsync(stage.Strategy, cancellationToken).ConfigureAwait(false) is { Verdict: ReviewVerdicts.Rejected, Through: var reviewed } && !(q.Through > reviewed)) + { + list.Add(new(ReviewReason, $"l'ultima revisione trimestrale (dati fino al {reviewed.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}) non è stata superata")); + } + var since = stage.StageSince ?? clock.UtcNow; var points = await db.ReadAsync(s => s.QueryAsync( "SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND taken_at >= @f ORDER BY taken_at", @@ -602,9 +674,10 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, .Select(g => g.Last().Index).ToList(); var start = points[0].Index; var below = 0; - for (var day = daily.Count - 1; day >= 1 && day - 1 < q.ExpectedPathP5.Count; day--) + for (var day = daily.Count - 1; day >= 1 && q.ExpectedPathP5.Count > 0; day--) { - if ((double)((daily[day] / start) - 1m) < q.ExpectedPathP5[day - 1]) + // After the year the path covers, its last value holds. + if ((double)((daily[day] / start) - 1m) < q.ExpectedPathP5[Math.Min(day, q.ExpectedPathP5.Count) - 1]) { below++; } @@ -620,7 +693,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, } } - var slippage = await SlippageAsync(account, since, cancellationToken).ConfigureAwait(false); + var slippage = await SlippageAsync(account, stage.Strategy, since, cancellationToken).ConfigureAwait(false); if (slippage is { } bp && q.ExpectedSlippageBp > 0m && bp > 3m * q.ExpectedSlippageBp) { list.Add(new("slippage", $"scostamento medio {Format.Quantity(Math.Round(bp, 1))} punti base, oltre il triplo del previsto")); @@ -629,6 +702,97 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return list; } + /// The key of the condition of the quarterly review (SPEC 12.3). + public const string ReviewReason = "review"; + + /// Why a strategy was demoted, in words. + public static string DemotionText(string reason) => reason switch + { + "drawdown" => "calo oltre 1,5 volte quello del backtest", + "expected_path" => "20 sedute di fila sotto il percorso atteso", + "slippage" => "scostamento dei prezzi oltre il triplo del previsto", + ReviewReason => "revisione trimestrale non superata", + _ => reason, + }; + + /// The last review that said something of a strategy: one that waited for data, or failed, leaves the one before in force. + public Task<(string Verdict, DateOnly Through)?> ReviewVerdictAsync(string strategy, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT verdict, through FROM review_outcomes WHERE strategy = @s AND verdict IN (@p, @r) ORDER BY through DESC, created_at DESC LIMIT 1", + r => ((string, DateOnly)?)(r.Text("verdict"), Anubis.Data.BarStore.ParseDay(r.Text("through"))), ("s", strategy), ("p", ReviewVerdicts.Passed), ("r", ReviewVerdicts.Rejected)), cancellationToken); + + /// + /// What a quarterly review does to a strategy, inside its transaction (SPEC 12.2, 12.3). In observation the new outcome + /// takes the place of the old one, and one that passed after its 90 days goes to simulation, unless the user put it + /// there. With capital nothing moves here: not its parameters nor the figures it is compared with. The answer is one of + /// . + /// + public async Task ApplyReviewAsync(DbSession s, string strategy, Qualification outcome, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(outcome); + var stage = await s.FirstOrDefaultAsync(Select + " WHERE strategy = @s", Read, ("s", strategy)).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + if (stage.Stage != StrategyStages.Observation) + { + return outcome.Passed ? ReviewActions.Confirmed : StrategyStages.IsLive(stage.Stage) ? ReviewActions.Demoted : ReviewActions.Held; + } + + await s.ExecuteAsync("UPDATE strategy_state SET qualification = @q, updated_at = @t WHERE strategy = @s", cancellationToken, + ("q", new DbJson(JsonSerializer.Serialize(outcome, Qualification.Json))), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + if (!outcome.Passed || StrategyNames.IsCandidate(strategy)) + { + return ReviewActions.Stays; + } + + var last = await s.FirstOrDefaultAsync("SELECT reason FROM strategy_stage_history WHERE strategy = @s ORDER BY created_at DESC, id DESC LIMIT 1", r => r.TextOrNull("reason"), ("s", strategy)) + .ConfigureAwait(false); + if (last is not null && !last.EndsWith(" · " + AutomaticBy, StringComparison.Ordinal)) + { + return ReviewActions.UserChoice; + } + + if (ObservedDays(stage) < ObservationDays) + { + return ReviewActions.TooEarly; + } + + await MoveCoreAsync(s, strategy, stage.Stage, StrategyStages.Simulation, "quarterly_review", AutomaticBy, cancellationToken).ConfigureAwait(false); + return ReviewActions.Promoted; + } + + /// How a strategy has done since its stage began, for the quarterly review (SPEC 12.2). + public async Task FiguresAsync(StrategyStage stage, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(stage); + var now = clock.UtcNow; + var since = stage.StageSince ?? now; + if (stage.OrdersAccount is not { } account) + { + return new StageFigures(since, null, null, null, 0, await OneStepAsync(stage.Strategy, since, cancellationToken).ConfigureAwait(false)); + } + + var points = await db.ReadAsync(s => s.QueryAsync( + "SELECT twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND taken_at >= @f ORDER BY taken_at", + r => r.MoneyOrNull("twr_index") ?? 1m, ("a", account), ("s", stage.Strategy), ("f", since)), cancellationToken).ConfigureAwait(false); + decimal? result = null, fall = null; + if (points.Count > 1 && points[0] > 0m) + { + result = (points[^1] / points[0]) - 1m; + var peak = points[0]; + fall = 0m; + foreach (var p in points) + { + peak = Math.Max(peak, p); + fall = Math.Max(fall.Value, peak > 0m ? 1m - (p / peak) : 0m); + } + } + + return new StageFigures(since, result, fall, await SlippageAsync(account, stage.Strategy, since, cancellationToken).ConfigureAwait(false), + (await ClosedTradesAsync(stage.Strategy, account, since, cancellationToken).ConfigureAwait(false)).Count, + await OneStepAsync(stage.Strategy, since, cancellationToken).ConfigureAwait(false)); + } + + private const string AutomaticBy = "automatico"; + private async Task LeaveLiveAsync(string strategy, string by, string reason, bool automatic, CancellationToken cancellationToken) { var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); @@ -651,7 +815,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, await LogChangeAsync(s, strategy, stage.Stage, StrategyStages.Simulation, by, cancellationToken).ConfigureAwait(false); if (automatic) { - var message = $"{StrategyNames.Label(strategy, withMarket: true)} torna in simulazione ({reason})" + + var message = $"{StrategyNames.Label(strategy, withMarket: true)} torna in simulazione ({DemotionText(reason)})" + (open ? ": le posizioni reali restano in sola uscita finché non sono a zero." : "."); await s.ExecuteAsync("INSERT INTO risk_events (id, occurred_at, kind, severity, message, data, created_at, world) VALUES (@id, @t, @k, @sev, @m, @d, @t, @w)", cancellationToken, ("id", Ids.NewId(clock)), ("t", now), ("k", "demotion"), ("sev", RiskSeverities.High), ("m", message), @@ -729,15 +893,17 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, return outcomes.Count == 0 ? null : outcomes.Count(o => o == DecisionOutcomes.Different) / (decimal)outcomes.Count; } - private async Task SlippageAsync(Guid? account, DateTimeOffset since, CancellationToken cancellationToken) + // The strategy's own executions; a stop that jumped a gap is not slippage (as in CostBook.FillsAsync). + private async Task SlippageAsync(Guid? account, string strategy, DateTimeOffset since, CancellationToken cancellationToken) { if (account is not { } a) { return null; } - var values = await db.ReadAsync(s => s.QueryAsync("SELECT slippage_bp FROM fills WHERE account_id = @a AND executed_at >= @f AND slippage_bp IS NOT NULL", - r => r.Money("slippage_bp"), ("a", a), ("f", since)), cancellationToken).ConfigureAwait(false); + var values = await db.ReadAsync(s => s.QueryAsync("SELECT f.slippage_bp FROM fills f LEFT JOIN orders o ON o.id = f.order_id " + + "WHERE f.account_id = @a AND f.strategy = @s AND f.executed_at >= @f AND f.slippage_bp IS NOT NULL AND (o.purpose IS NULL OR o.purpose <> @stop)", + r => r.Money("slippage_bp"), ("a", a), ("s", strategy), ("f", since), ("stop", Wire.Text(OrderPurpose.Stop))), cancellationToken).ConfigureAwait(false); return values.Count == 0 ? null : values.Average(); } diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 3e88533..3d04369 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -240,6 +240,9 @@ public sealed partial class TradingService : IDisposable private readonly SettingsStore? _settings; + /// The quarterly review (SPEC 12.2), the last step of the night; null where there is no laboratory. + public Func? QuarterlyReview { get; set; } + /// Learning beside the decisions (SPEC 11). public Anubis.Learning.LearningDesk Learning { get; } @@ -635,6 +638,7 @@ public sealed partial class TradingService : IDisposable await GuardAsync("settori delle società", () => SectorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("migliorie in osservazione", () => MeasureShadowAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("scoperte", () => DiscoverAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("revisione trimestrale", () => QuarterlyReview?.Invoke(cancellationToken) ?? Task.CompletedTask, cancellationToken).ConfigureAwait(false); } } diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs index 1ca654f..24212f7 100644 --- a/tests/Anubis.Tests/LaboratoryScreenTests.cs +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -69,6 +69,71 @@ public sealed class LaboratoryScreenTests } /// SPEC 11.6: a lower slippage waits in the Laboratorio for the confirmation of the user. + /// SPEC 12.2, 13.6: the review in the laboratory, its page, and the empty state before the first. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheQuarterlyReviewIsShownInTheLaboratory() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var keep = postgres; + await using var server = await ServerHarness.StartAsync("docker", env); + await server.SignInFirstTimeAsync(); + var empty = await server.TextAsync("/laboratorio"); + StringAssert.Contains(empty, "Revisione trimestrale"); + StringAssert.Contains(empty, "Nessuna revisione ancora."); + StringAssert.Contains(empty, "La prossima non prima del 05/"); + + var services = server.Host.Services!; + var (db, clock) = (services.Db, server.Host.Clock); + var trial = Guid.NewGuid(); + var report = new ReviewReport + { + Strategies = + [ + new ReviewLine + { + Strategy = Anubis.Trading.StrategyNames.CryptoTrend, Stage = Anubis.Trading.StrategyStages.Simulation, Verdict = Anubis.Trading.ReviewVerdicts.Rejected, Action = Anubis.Trading.ReviewActions.Held, + Text = "Universo ampio: calo massimo 38,2%, oltre il 25%.", Trials = [trial], Chosen = new ReviewVariant("coin_vol=10;max_stop=20", 1.21, 5_000m, 0.382), InUse = new ReviewVariant("coin_vol=15;max_stop=20", 1.1, 4_000m, 0.35), + Live = new Anubis.Trading.StageFigures(clock.UtcNow, 0.031m, 0.05m, 6.2m, 4, 0.1m), ExpectedFall = 0.32m, ExpectedSlippageBp = 7m, BacktestOverSameDays = 0.025, + }, + new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMomentum, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", Signals = 10, Won = 6 }, + ], + RatesBefore = new Dictionary { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 }, + RatesAfter = new Dictionary { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.398 }, + RestrictionsFrom = new DateOnly(2026, 10, 1), + Restrictions = new Anubis.Learning.RestrictionReport([]), + RestrictionsEver = new Anubis.Learning.RestrictionReport([new Anubis.Learning.RestrictionLine(Anubis.News.NewsReasons.Severe, 3, 120.5m, 33.25m, 1, 0, 2, 0)]), + }; + async Task AddAsync(string quarter, string status, ReviewReport? body, int minutes) + { + var id = Guid.NewGuid(); + await db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO quarterly_reviews (id, quarter, through, status, report, created_at, updated_at, finished_at) VALUES (@id, @q, '2026-12-31', @s, @r, @t, @t, @t)", CancellationToken.None, + ("id", id), ("q", quarter), ("s", status), ("r", body is null ? null : new Anubis.Db.DbJson(System.Text.Json.JsonSerializer.Serialize(body, TrialPlan.Json))), ("t", clock.UtcNow.AddMinutes(minutes))), CancellationToken.None); + return id; + } + + var first = await AddAsync("2026-Q4", ReviewStatuses.Done, report with { Missing = "mancano i cambi della BCE" }, 0); + var id = await AddAsync("2027-Q1", ReviewStatuses.Done, report, 1); + var page = await server.TextAsync("/laboratorio"); + foreach (var part in new[] + { + "1º trimestre 2027", "Non superata", "Non superata, resta in simulazione e non può passare ai soldi veri", $"href=\"/laboratorio/{trial}\"", "calo massimo 38,2%, oltre il 25%", "Variante in uso: coin_vol 15", + "Non cambia da sola", "Risultato +3,1%; il backtest negli stessi giorni circa +2,5%.", "Scostamento dei prezzi 6,2 punti base, atteso 7 punti base.", "decisioni identiche al backtest del giorno dopo 90,0%", + "In attesa dei dati", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}", + }) + { + StringAssert.Contains(page, part, $"Missing \"{part}\"."); + } + + StringAssert.Contains(await server.TextAsync($"/laboratorio/revisione/{first}"), "Le crypto non sono state riprovate: mancano i cambi della BCE."); + var running = await AddAsync("2027-Q2", ReviewStatuses.Running, null, 2); + StringAssert.Contains(await server.TextAsync("/laboratorio"), "La revisione del 2º trimestre 2027 è in corso"); + StringAssert.Contains(await server.TextAsync($"/laboratorio/revisione/{running}"), "è in corso"); + StringAssert.Contains(await server.TextAsync($"/laboratorio/revisione/{Guid.NewGuid()}"), "Revisione non trovata."); + Assert.AreNotEqual(first, id); + } + [TestMethod] [TestCategory(Category.Integration)] public async Task ALowerCostIsConfirmedFromTheLaboratory() diff --git a/tests/Anubis.Tests/NewsRulesTests.cs b/tests/Anubis.Tests/NewsRulesTests.cs index dddc545..e93c07f 100644 --- a/tests/Anubis.Tests/NewsRulesTests.cs +++ b/tests/Anubis.Tests/NewsRulesTests.cs @@ -273,6 +273,32 @@ public sealed class NewsRulesTests Assert.IsTrue(first.Count > 0 && first.All(f => f == new DateTimeOffset(2026, 9, 1, 0, 5, 0, TimeSpan.Zero)), "The time it was first due is kept for the price check."); } + /// A rule that appears after the decision and lasts past the deadline drops the purchase when it is due: the row says of which symbol (SPEC 10.5). + [TestMethod] + [TestCategory(Category.Integration)] + public async Task APurchaseDroppedWhenItIsDueKeepsItsSymbol() + { + var day = new DateOnly(2026, 9, 1); + await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)).ConfigureAwait(false); + live.UseGate(new LateGate(new EntryHold(NewsReasons.Severe, new DateTimeOffset(2026, 9, 3, 0, 0, 0, TimeSpan.Zero), "fatto"))); + await live.DayAsync(day).ConfigureAwait(false); + var rows = await live.Rig.QueryAsync("SELECT symbol, stage, outcome, reasons FROM decisions WHERE stage = @o", r => (Symbol: r.TextOrNull("symbol"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons")), + ("o", DecisionStages.Order)).ConfigureAwait(false); + CollectionAssert.AreEquivalent(new[] { "ETH-EUR", "SOL-EUR" }, rows.Where(r => r.Outcome == DecisionOutcomes.Refused && r.Reasons.Contains(NewsReasons.Severe, StringComparison.Ordinal)).Select(r => r.Symbol).ToList()); + var balance = await Anubis.Learning.RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none).ConfigureAwait(false); + Assert.AreEqual(2, balance.Lines.Single().Open); + } + + // Says nothing at the decision, then holds each purchase. + private sealed class LateGate(EntryHold hold) : IEntryGate + { + private readonly HashSet _asked = []; + + public Task HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(_asked.Add(spec.Symbol) ? null : at < hold.Until ? hold : null); + + public Task KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(null); + } + /// /// The close of 1 September plans a mean reversion purchase of BBB (AbsenceTests). With its earnings on 3 September, /// before the open, the strategy stays out; with the fourth row of 10.5 switched off it buys as before. diff --git a/tests/Anubis.Tests/QuarterlyReviewTests.cs b/tests/Anubis.Tests/QuarterlyReviewTests.cs new file mode 100644 index 0000000..95b18c1 --- /dev/null +++ b/tests/Anubis.Tests/QuarterlyReviewTests.cs @@ -0,0 +1,655 @@ +using System.Text.Json; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Learning; +using Anubis.News; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The quarterly review of SPEC 12.2 and the balance of the restrictions of 10.5 (issue #74). +[TestClass] +public sealed class QuarterlyReviewTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateOnly Through = new(2026, 12, 31); + private const string Crypto = StrategyNames.CryptoTrend; + + private static DateTimeOffset At(int year, int month, int day) => new(year, month, day, 2, 10, 0, TimeSpan.Zero); + + // ---- The rig ---------------------------------------------------------------------------------------------------- + + private static async Task WriteHistoryAsync(string folder) + { + var store = new ResearchStore(folder); + var seed = 21u; + foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" }) + { + var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), + (decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList(); + await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false); + } + } + + // A report of the protocol on those coins, whose verdict each test chooses. + private static readonly Lazy> _report = new(async () => + { + var folder = TempFolder.Create("review-report"); + try + { + await WriteHistoryAsync(folder).ConfigureAwait(false); + var (plan, _) = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through, + CryptoTrendProtocol.Capital, null), At(2027, 1, 5)); + var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false); + return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5)).Report; + } + finally + { + TempFolder.Delete(folder); + } + }); + + private sealed class ReviewRig : IAsyncDisposable + { + public required LiveRig Live { get; init; } + + public required string Folder { get; init; } + + public required Laboratory Lab { get; set; } + + public required QuarterlyReview Review { get; set; } + + public string? Missing { get; set; } + + public List Prepared { get; } = []; + + public Database Db => Live.Rig.Db; + + public ManualClock Clock => Live.Rig.Clock; + + public static async Task CreateAsync(string stage = StrategyStages.Observation, DateOnly? since = null, Qualification? qualification = null, bool history = true) + { + var from = since ?? new DateOnly(2026, 9, 1); + var live = await LiveRig.CreateAsync(from, from.AddDays(5), stage: stage).ConfigureAwait(false); + live.UseFirst(Rates(new DateOnly(2026, 10, 31))); + var folder = TempFolder.Create("review"); + if (history) + { + await WriteHistoryAsync(folder).ConfigureAwait(false); + } + + await live.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(qualification ?? Old(false), Qualification.Json)))), _none) + .ConfigureAwait(false); + var rig = new ReviewRig { Live = live, Folder = folder, Lab = null!, Review = null! }; + rig.Start(); + return rig; + } + + /// A new process on the same database. + public void Start() + { + Lab?.Dispose(); + Lab = new Laboratory(Db, Clock, Folder); + Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) => + { + Prepared.Add(to); + return Task.FromResult(Missing); + }); + Lab.ReviewTrialEnded = Review.ConcludeAsync; + } + + public async Task NightAsync(DateTimeOffset at) + { + Clock.Set(at); + await Review.RunIfDueAsync(_none).ConfigureAwait(false); + } + + /// The baseline in December, then the review of January. + public async Task OpenAsync() + { + await NightAsync(At(2026, 12, 10)).ConfigureAwait(false); + await NightAsync(At(2027, 1, 5)).ConfigureAwait(false); + return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single(); + } + + /// The whole review, its trials ended with the given verdict. + public async Task ReviewAsync(bool passed, Func? change = null) + { + var review = await OpenAsync().ConfigureAwait(false); + await EndAsync(review, passed, change).ConfigureAwait(false); + await Review.ConcludeAsync(_none).ConfigureAwait(false); + return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single(r => r.Id == review.Id); + } + + public async Task EndAsync(Review review, bool passed, Func? change = null) + { + var report = await _report.Value.ConfigureAwait(false); + report = report with + { + Passed = passed, + Checks = [.. report.Checks.Select((c, i) => c with { Passed = passed || i > 0, Value = c.Value ?? 0 })], + }; + report = change?.Invoke(report) ?? report; + foreach (var trial in await Lab.Trials.OfReviewAsync(review.Id, _none).ConfigureAwait(false)) + { + Assert.IsTrue(await Lab.Trials.StartAsync(trial.Id, _none).ConfigureAwait(false)); + var summary = new TrialSummary("EUR", report.Chosen, 1m, 0.1, 1, 0.1, 10, 0.95, 0.1, [.. report.Variants.Select(v => v.Sharpe)]); + await Lab.Trials.FinishAsync(trial.Id, "x", summary, (report with { TrialId = trial.Id }).ToJson(), passed, _none).ConfigureAwait(false); + } + } + + public async Task StageAsync() => (await Live.Stages.GetAsync(Crypto, _none).ConfigureAwait(false))!; + + public Task CountAsync(string sql) => Db.ReadAsync(async s => (int)await s.CountAsync(sql).ConfigureAwait(false), _none); + + public async ValueTask DisposeAsync() + { + Lab.Dispose(); + await Live.DisposeAsync().ConfigureAwait(false); + TempFolder.Delete(Folder); + } + } + + private static Qualification Old(bool passed) => new() + { + Passed = passed, + Verdict = passed ? "superato" : "non superato", + Report = CryptoTrendProtocol.ReportPath, + Parameters = "coin_vol=10;max_stop=20", + MaxDrawdown = 0.2m, + ExpectedSlippageBp = 7m, + Through = new DateOnly(2026, 10, 31), + StrategyVersion = "1", + }; + + private static FirstModelFile Rates(DateOnly through, double rate = 0.4) => new() { BaseRates = new Dictionary { [Crypto] = rate }, Through = through }; + + // ---- When ------------------------------------------------------------------------------------------------------- + + [TestMethod] + [TestCategory(Category.Unit)] + public void AReviewIsDueOnceAQuarterFromTheFifthDay() + { + Assert.AreEqual("2026-Q4", QuarterlyReview.QuarterOf(new DateOnly(2026, 12, 31))); + Assert.AreEqual("2027-Q1", QuarterlyReview.QuarterOf(new DateOnly(2027, 1, 1))); + Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 20), null), "the first quarter is only noted"); + Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 4), "2026-Q4")); + Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2026-Q4")); + Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 3, 31), "2026-Q4")); + Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2027-Q1")); + Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 8, 1), "2026-Q4"), "several quarters missed"); + Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), "2026-Q4")); + Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), null)); + Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2027, 2, 1), "2026-Q4"), "already due"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ItWaitsForTheArchiveUntilTheFifteenthThenPublishesWithoutIt() + { + await using var rig = await ReviewRig.CreateAsync(history: false); + rig.Missing = "gli archivi di Binance non si scaricano"; + await rig.NightAsync(At(2027, 1, 20)); + Assert.IsEmpty(rig.Prepared, "the first night only notes the quarter"); + await rig.NightAsync(At(2027, 4, 4)); + Assert.IsEmpty(rig.Prepared); + await rig.NightAsync(At(2027, 4, 5)); + await rig.NightAsync(At(2027, 4, 15)); + CollectionAssert.AreEqual(new[] { new DateOnly(2027, 3, 31), new DateOnly(2027, 3, 31) }, rig.Prepared); + var waiting = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); + Assert.AreEqual(ReviewStatuses.Preparing, waiting.Status); + Assert.AreEqual(0, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); + + await rig.NightAsync(At(2027, 4, 16)); + var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); + Assert.AreEqual((waiting.Id, ReviewStatuses.Done, "2027-Q2"), (done.Id, done.Status, done.Quarter)); + var line = done.Report!.Strategies.Single(); + Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (line.Verdict, line.Action)); + Assert.Contains("dati mancanti: gli archivi di Binance non si scaricano", line.Text); + Assert.IsNull(done.Report.RatesAfter); + Assert.IsEmpty(await rig.Lab.Trials.ListAsync(10, _none)); + Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict, "the outcome before stays"); + Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none)); + + // The same quarter never twice; three quarters off make one review. + await rig.NightAsync(At(2027, 4, 20)); + Assert.HasCount(4, rig.Prepared.Append(default).ToList()); + rig.Missing = "mancano i cambi della BCE"; + await rig.NightAsync(At(2028, 2, 20)); + await rig.NightAsync(At(2028, 2, 21)); + var all = await QuarterlyReview.ListAsync(rig.Db, _none); + CollectionAssert.AreEqual(new[] { "2028-Q1", "2027-Q2" }, all.Select(r => r.Quarter).ToList()); + Assert.AreEqual(new DateOnly(2028, 1, 31), all[0].Through); + Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); + } + + // ---- The run ---------------------------------------------------------------------------------------------------- + + /// The real trials, with a restart in the middle: each trial counts once, the review concludes once. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ARestartHalfwayGoesOnAndTheReviewConcludesOnce() + { + await using var rig = await ReviewRig.CreateAsync(); + await rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, @tier, @st, 5, 12, 12, 10, 14, 40, @t, @t)", _none, + ("id", Ids.NewId(rig.Clock)), ("tier", SlippageTiers.All[0]), ("st", CostStatuses.Applied), ("t", rig.Clock.UtcNow)), _none); + var review = await rig.OpenAsync(); + Assert.AreEqual(ReviewStatuses.Running, review.Status); + Assert.AreEqual(Through, review.Through); + var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none); + Assert.HasCount(2, trials); + Assert.HasCount(4, trials[0].Plan.Data.Symbols); + CollectionAssert.AreEqual(CryptoTrendProtocol.Narrow.ToList(), trials[1].Plan.Data.Symbols.ToList()); + Assert.IsTrue(trials.All(t => t is { Status: TrialStatuses.Planned, Plan.Priors: ReviewPriors.All, Plan.Slippage: not null } && t.Plan.Slippage.Of(SlippageTiers.All[0]) == 12m && t.Plan.Data.From == CryptoTrendProtocol.From)); + + // The same night again plans nothing more. + await rig.NightAsync(At(2027, 1, 6)); + Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none)); + + // The process dies with the first trial done and the second running. + await rig.Lab.ProcessAsync(trials[0].Id, _none); + Assert.AreEqual(TrialStatuses.Done, (await rig.Lab.Trials.GetAsync(trials[0].Id, _none))!.Status); + Assert.IsTrue(await rig.Lab.Trials.StartAsync(trials[1].Id, _none)); + rig.Start(); + using var stop = new CancellationTokenSource(); + var run = rig.Lab.RunAsync(stop.Token); + Review done; + for (var deadline = DateTime.UtcNow.AddMinutes(4); ; await Task.Delay(100)) + { + done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); + if (done.Status == ReviewStatuses.Done || DateTime.UtcNow > deadline) + { + break; + } + } + + Assert.AreEqual(ReviewStatuses.Done, done.Status); + await Task.WhenAll(rig.Review.ConcludeAsync(_none), rig.Review.ConcludeAsync(_none)); + await stop.CancelAsync(); + try + { + await run; + } + catch (OperationCanceledException) + { + } + + Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none)); + Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM review_outcomes")); + Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); + Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review'")); + var reports = new List(); + foreach (var t in trials) + { + reports.Add(BacktestReport.FromJson((await rig.Lab.Trials.ReportJsonAsync(t.Id, _none))!)); + } + + var n = reports[0].Variants.Count; + Assert.AreEqual(3 * n, reports[0].TrialsCounted, "in observation: its own and those of the protocol that turned it down"); + Assert.AreEqual(4 * n, reports[1].TrialsCounted); + var line = done.Report!.Strategies.Single(); + Assert.AreEqual(reports.All(r => r.Passed) ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, line.Verdict); + CollectionAssert.AreEqual(trials.Select(t => t.Id).ToList(), line.Trials.ToList()); + Assert.AreEqual(reports[0].Chosen, line.Chosen!.Parameters); + + // The outcome of the strategy and the base rates come from the longer history. + var q = (await rig.StageAsync()).Qualification!; + Assert.AreEqual((Through, "/laboratorio/revisione/" + done.Id, reports[0].Chosen), (q.Through, q.Report, q.Parameters)); + Assert.AreEqual(reports[0].ExpectedSlippageBp, q.ExpectedSlippageBp); + var rates = await rig.Live.Learning.BaseRatesAsync(_none); + Assert.AreEqual(0.4, done.Report.RatesBefore[Crypto]); + Assert.AreEqual(done.Report.RatesAfter![Crypto], rates[Crypto]); + var history = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList(); + Assert.IsNotEmpty(history); + Assert.AreEqual(Trainer.SharesOf(history)[Crypto], rates[Crypto], 1e-12); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ATrialThatFailsLeavesTheOutcomeInForce() + { + await using var rig = await ReviewRig.CreateAsync(); + var review = await rig.OpenAsync(); + var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none); + await rig.Lab.Trials.FailAsync(trials[0].Id, "guasto", _none); + await rig.Review.ConcludeAsync(_none); + Assert.AreEqual(ReviewStatuses.Running, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status, "one is still to run"); + await rig.Lab.Trials.FailAsync(trials[1].Id, "guasto", _none); + await rig.Review.ConcludeAsync(_none); + var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); + Assert.AreEqual((ReviewVerdicts.Error, ReviewActions.None), (done.Report!.Strategies.Single().Verdict, done.Report.Strategies.Single().Action)); + Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict); + Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none)); + } + + // ---- What it does to a strategy --------------------------------------------------------------------------------- + + [TestMethod] + [TestCategory(Category.Integration)] + [DataRow("2026-11-01", false, ReviewActions.TooEarly)] + [DataRow("2026-09-01", false, ReviewActions.Promoted)] + [DataRow("2026-09-01", true, ReviewActions.UserChoice)] + public async Task AStrategyInObservationThatPassesGoesToSimulationAfterNinetyDays(string since, bool byUser, string action) + { + await using var rig = await ReviewRig.CreateAsync(since: DateOnly.Parse(since, System.Globalization.CultureInfo.InvariantCulture)); + if (byUser) + { + await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, 'simulation', 'observation', 'user · utente', @t)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", Crypto), ("t", rig.Clock.UtcNow)), _none); + } + + var review = await rig.ReviewAsync(passed: true); + Assert.AreEqual((ReviewVerdicts.Passed, action), (review.Report!.Strategies.Single().Verdict, review.Report.Strategies.Single().Action)); + var stage = await rig.StageAsync(); + Assert.AreEqual(action == ReviewActions.Promoted ? StrategyStages.Simulation : StrategyStages.Observation, stage.Stage); + Assert.IsTrue(stage.Qualification!.Passed); + Assert.AreEqual(Through, stage.Qualification.Through); + Assert.AreEqual(action == ReviewActions.Promoted ? 1 : 0, await rig.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE reason LIKE 'quarterly_review%'")); + StringAssert.Contains((await NewsRulesTests.DiaryAsync(rig.Db)).Single(m => m.StartsWith("Revisione trimestrale pronta", StringComparison.Ordinal)), + QuarterlyReview.ActionText(review.Report.Strategies.Single())); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStrategyInObservationThatDoesNotPassStaysWithTheNewVerdict() + { + await using var rig = await ReviewRig.CreateAsync(); + var review = await rig.ReviewAsync(passed: false); + Assert.AreEqual(ReviewActions.Stays, review.Report!.Strategies.Single().Action); + var stage = await rig.StageAsync(); + Assert.AreEqual(StrategyStages.Observation, stage.Stage); + Assert.StartsWith("Revisione del 1º trimestre 2027: protocollo non superato. Universo ampio:", stage.Qualification!.Verdict); + Assert.IsFalse(stage.Qualification.Verdict.Contains("Resta in osservazione", StringComparison.Ordinal)); + + // A restart with the older outcome of the program does not bring it back; a newer one, or new rules, do. + await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false), _none); + await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { Through = null, StrategyVersion = null }, _none); + Assert.AreEqual(Through, (await rig.StageAsync()).Qualification!.Through); + await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { StrategyVersion = "2", Verdict = "regole nuove" }, _none); + Assert.AreEqual("regole nuove", (await rig.StageAsync()).Qualification!.Verdict); + Assert.AreEqual(StrategyStages.Observation, (await rig.StageAsync()).Stage, "only the first start moves a strategy by itself"); + await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false) with { Through = Through.AddMonths(3), Verdict = "storico più lungo" }, _none); + Assert.AreEqual("storico più lungo", (await rig.StageAsync()).Qualification!.Verdict); + + // An outcome written before the reviews still reads. + var old = JsonSerializer.Deserialize("""{"passed":true,"verdict":"x","report":"y"}""", Qualification.Json)!; + Assert.IsNull(old.Through); + Assert.IsFalse(old.Outlives(Old(false))); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStrategyInSimulationKeepsItsFiguresAndCannotAdvanceUntilAReviewPasses() + { + await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); + async Task DemotionAsync() => (await rig.Live.Stages.RequirementsAsync(Crypto, _none)).Single(r => r.Key == "demotion"); + Assert.IsTrue((await DemotionAsync()).Met); + var review = await rig.ReviewAsync(passed: false, r => r with { Variants = [.. r.Variants.Select((v, i) => v with { Parameters = i == 0 && !v.Chosen ? "coin_vol=10;max_stop=20" : v.Parameters })] }); + var line = review.Report!.Strategies.Single(); + Assert.AreEqual((StrategyStages.Simulation, ReviewActions.Held), (line.Stage, line.Action)); + Assert.IsTrue((await rig.Lab.Trials.OfReviewAsync(review.Id, _none)).All(t => t.Plan.Priors == ReviewPriors.Review), "already qualified: the same grid measured again"); + var stage = await rig.StageAsync(); + Assert.AreEqual(StrategyStages.Simulation, stage.Stage); + Assert.AreEqual(JsonSerializer.Serialize(Old(true), Qualification.Json), JsonSerializer.Serialize(stage.Qualification, Qualification.Json)); + Assert.Contains("non è stata superata", (await DemotionAsync()).Value); + Assert.IsFalse((await DemotionAsync()).Met); + Assert.IsEmpty(await rig.Live.Stages.CheckDemotionsAsync(_none), "nothing to demote in simulation"); + + // The next one that waits for data leaves it in force; one that passes clears it. + await NextAsync(rig, ReviewVerdicts.Waiting, new DateOnly(2027, 3, 31)); + Assert.IsFalse((await DemotionAsync()).Met); + await NextAsync(rig, ReviewVerdicts.Passed, new DateOnly(2027, 6, 30)); + Assert.IsTrue((await DemotionAsync()).Met); + } + + internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s => + { + var id = Ids.NewId(clock); + await s.ExecuteAsync("INSERT INTO quarterly_reviews (id, quarter, through, status, created_at, updated_at) VALUES (@id, @q, @d, 'done', @t, @t)", _none, + ("id", id), ("q", "x" + through.ToString("yyyyMM", System.Globalization.CultureInfo.InvariantCulture)), ("d", BarStore.DayText(through)), ("t", clock.UtcNow)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO review_outcomes (id, review_id, strategy, stage, verdict, action, through, trials, data, created_at) VALUES (@id, @r, @s, 'x', @v, 'none', @d, @j, @o, @t)", _none, + ("id", Ids.NewId(clock)), ("r", id), ("s", Crypto), ("v", verdict), ("d", BarStore.DayText(through)), ("j", new DbJson("[]")), ("o", new DbJson("{}")), ("t", clock.UtcNow)).ConfigureAwait(false); + }, _none); + + private static Task NextAsync(ReviewRig rig, string verdict, DateOnly through) => NextAsync(rig.Db, rig.Clock, verdict, through); + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheStockStrategiesWaitAndTheCandidatesAreLeftOut() + { + await using var rig = await ReviewRig.CreateAsync(); + foreach (var (name, stage) in new[] { (StrategyNames.EquityMomentum, StrategyStages.Observation), (StrategyNames.Candidates[0].Name, StrategyStages.Observation) }) + { + await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 0, @t)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", name), ("a", rig.Live.Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow)), _none); + } + + var review = await rig.ReviewAsync(passed: false); + CollectionAssert.AreEquivalent(new[] { Crypto, StrategyNames.EquityMomentum }, review.Report!.Strategies.Select(l => l.Strategy).ToList()); + var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum); + Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action)); + Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none)); + } + + // ---- Base rates ------------------------------------------------------------------------------------------------- + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheBaseRatesOfAReviewSurviveARestartAndGiveWayToANewerProgram() + { + await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); + var file = FirstModel.Train(LearningModelTests.Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), _none); + rig.Live.UseFirst(file); + rig.Start(); + await rig.Live.Learning.PrepareHistoryAsync(_none); + var champion = await rig.Live.Learning.Models.FindAsync(ModelStatuses.Champion, _none); + await LearningStoreAddLiveAsync(rig); + var review = await rig.ReviewAsync(passed: true); + var rate = review.Report!.RatesAfter![Crypto]; + Assert.AreNotEqual(file.BaseRates[Crypto], rate); + var examples = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList(); + Assert.IsTrue(examples.All(e => e.Strategy == Crypto && e.Day <= Through)); + Assert.IsFalse(examples.Any(e => e.Symbol == "BTCEUR" && e.Day == _liveDay), "the same operation is there as a live one"); + + // A restart with the same program, or an older one, changes nothing. + foreach (var first in new[] { file, FirstModel.Train(LearningModelTests.Cases(310, x => Odds.Probability(x[1])), new DateOnly(2026, 11, 30), _none) }) + { + var desk = new LearningDesk(rig.Db, rig.Clock) { First = first }; + await desk.PrepareHistoryAsync(_none); + Assert.AreEqual(rate, (await desk.BaseRatesAsync(_none))[Crypto]); + Assert.AreEqual(examples.Count, await desk.Store.CountAsync(CaseSources.History, _none)); + Assert.AreEqual(champion!.Id, (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!.Id, "the model is not replaced"); + } + + // One built on a longer history wins; a strategy only a review measured keeps its rate. + var newer = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(LearningModelTests.Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), _none) }; + await newer.PrepareHistoryAsync(_none); + Assert.AreEqual(newer.First.BaseRates[Crypto], (await newer.BaseRatesAsync(_none))[Crypto]); + Assert.AreEqual(320, await newer.Store.CountAsync(CaseSources.History, _none)); + Assert.AreEqual(0.3, LearningDesk.Merge(new Dictionary { ["a"] = 0.3, ["b"] = 0.2 }, new Dictionary { ["b"] = 0.5 })["a"]); + } + + private static DateOnly _liveDay; + + // A live example equal to one the history will give. + private static async Task LearningStoreAddLiveAsync(ReviewRig rig) + { + var data = await FirstModel.DataAsync(rig.Folder, Through, _none); + var same = FirstModel.ExamplesOf(data, Old(true).Parameters, Through, null, _none).First(e => e.Symbol == "BTCEUR"); + _liveDay = same.Day; + await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, same with { Id = Guid.Empty, Symbol = "BTC-EUR", Source = CaseSources.Live, Stage = StrategyStages.Simulation }, _none), _none); + } + + // ---- Priors, universe, archives --------------------------------------------------------------------------------- + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AQualifiedStrategyCountsTheSameTriesAtEveryReviewAndOneInObservationMore() + { + await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); + var review = await rig.ReviewAsync(passed: true); + async Task> CountsAsync(Guid id) + { + var counts = new List(); + foreach (var t in await rig.Lab.Trials.OfReviewAsync(id, _none)) + { + // As each one was run: what came later does not exist yet. + counts.Add((await rig.Lab.Trials.PriorOfAsync(t, _none)).Trials); + } + + return counts; + } + + CollectionAssert.AreEqual(new[] { 1, 1 }, await CountsAsync(review.Id), "the other of the same review, never the past"); + await rig.NightAsync(At(2027, 4, 5)); + var second = (await QuarterlyReview.ListAsync(rig.Db, _none))[0]; + CollectionAssert.AreEqual(new[] { 0, 0 }, await CountsAsync(second.Id)); + await rig.EndAsync(second, passed: false); + await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none); + await rig.Review.ConcludeAsync(_none); + await rig.NightAsync(At(2027, 7, 5)); + var third = (await QuarterlyReview.ListAsync(rig.Db, _none))[0]; + CollectionAssert.AreEqual(new[] { 6, 6 }, await CountsAsync(third.Id), "four in the register and two of the protocol"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ASeriesOutsideTheArchivesNeverChangesTheUniverse() + { + var folder = TempFolder.Create("review-universe"); + try + { + await WriteHistoryAsync(folder); + var store = new ResearchStore(folder); + var bars = new List { new(new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero), 1m, 1m, 1m, 1m, 1m) }; + foreach (var other in new[] { "ICP", "APT" }) + { + await store.WriteAsync(EuroHistory.Venue, other + "EUR", Timeframes.Day, bars, _none); + await store.WriteAsync(Venues.Binance, other + "USDT", Timeframes.Day, bars, _none); + } + + await store.WriteAsync(Venues.Binance, "BTCUSDT", Timeframes.Day, bars, _none); + CollectionAssert.AreEqual(new[] { "BTCEUR", "ETHEUR", "SOLEUR", "XRPEUR" }, (await CryptoTrendProtocol.BroadAsync(store, Through, _none)).Order(StringComparer.Ordinal).ToList()); + var rates = new List { new("EUR", "USD", new DateOnly(2026, 11, 30), 1.1m, "ecb") }; + CollectionAssert.AreEqual(new[] { "BTCEUR" }, (await EuroHistory.ConvertAllAsync(store, rates, _none, CryptoTrendProtocol.Archives)).ToList()); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TheReportOfABaseStrategyKeepsItsExpectedPathAndSlippage() + { + var report = await _report.Value; + Assert.IsTrue(report.ExpectedSlippageBp > 0m); + Assert.HasCount(CryptoTrendProtocol.PathDays, report.ExpectedPathP5!); + var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through, + CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan; + Assert.IsFalse(plan.ToJson().Contains("priors", StringComparison.OrdinalIgnoreCase), "a plan that is not of a review keeps its text, and its hash"); + Assert.AreNotEqual(TrialPlan.Hash(plan.ToJson()), TrialPlan.Hash((plan with { Priors = ReviewPriors.All }).ToJson())); + } + + // ---- The balance of the restrictions ---------------------------------------------------------------------------- + + private static readonly DateTimeOffset _t0 = new(2027, 1, 10, 0, 5, 0, TimeSpan.Zero); + + private static Example Case(string symbol, bool? win, double? result, int? closedIn, double multiplier = 1, string stage = StrategyStages.Simulation, bool labelled = true) => + new(Guid.NewGuid(), Crypto, symbol, CaseSources.Live, new DateOnly(2027, 1, 9), _t0, "trend_entry", 0.2m, null, null, new Dictionary()) + { + Stage = stage, + DecisionId = Guid.NewGuid(), + Multiplier = multiplier, + Label = labelled ? new CaseLabel(win, result, new DateOnly(2027, 1, 10), closedIn is { } d ? new DateOnly(2027, 1, 10).AddDays(d) : null, "x") : null, + }; + + private static BlockedEntry Block(Example e, string code, bool postponed = false, int minutes = 0) => new(e.DecisionId!.Value, Crypto, e.Symbol, code, postponed, e.At.AddMinutes(minutes)); + + private static readonly Dictionary _capital = new() { [Crypto] = 4_000 }; + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheBalanceSaysWhatWasAvoidedAndWhatItCost() + { + var lost = Case("AAA", false, -0.1, 5); + var won = Case("BBB", true, 0.05, 5, multiplier: 0.5); + var open = Case("CCC", null, null, null, labelled: false); + var never = Case("DDD", null, null, null); + var later = Case("EEE", false, -0.2, 5); + var held = Case("FFF", false, -0.2, 5); + var r = RestrictionBalance.Of( + [ + Block(lost, NewsReasons.Severe), Block(won, NewsReasons.Severe), Block(open, NewsReasons.Severe), Block(never, NewsReasons.Severe), + Block(later, CorrectiveReasons.CalendarEvent, postponed: true), Block(held, NewsReasons.Negative), + new BlockedEntry(Guid.NewGuid(), Crypto, "GGG", NewsReasons.Negative, false, _t0), Block(lost, "altro"), + ], + [lost, won, open, never, later, held], + [new HeldTrade(Crypto, "EEE", _t0.AddMinutes(40), null), new HeldTrade(Crypto, "FFF", _t0.AddDays(-3), null)], _capital); + var severe = r.Lines.Single(l => l.Code == NewsReasons.Severe); + Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 80m, 20m, 1, 1, 0, 0), severe); + Assert.AreEqual(1, r.Lines.Single(l => l.Code == CorrectiveReasons.CalendarEvent).Delayed, "bought at the end of the window"); + Assert.AreEqual(2, r.Lines.Single(l => l.Code == NewsReasons.Negative).Increases, "one already open, one without an example"); + Assert.AreEqual((80m, 20m), (r.Avoided, r.GivenUp)); + Assert.IsTrue(RestrictionBalance.Of([], [lost], [], _capital).IsEmpty, "a row switched off blocks nothing"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ARepeatedBlockIsOneCaseUnderItsStrictestRow() + { + var e = Case("AAA", false, -0.033333, 9); + var again = Block(e, NewsReasons.Severe, minutes: 24 * 60) with { DecisionId = Guid.NewGuid() }; + var r = RestrictionBalance.Of([Block(e, CorrectiveReasons.CalendarEvent, postponed: true), again], [e], [], _capital); + var line = r.Lines.Single(); + Assert.AreEqual((NewsReasons.Severe, 1, 26.67m), (line.Code, line.Stopped, line.Avoided)); + + // After the simulated close a new block of the same instrument is no longer that example. + var late = again with { At = _t0.AddDays(20) }; + Assert.AreEqual(1, RestrictionBalance.Of([late], [e], [], _capital).Lines.Single().Increases); + + // In observation nothing is bought: an entry only put off is one made later, one stopped is out. + var seen = Case("BBB", false, -0.1, 5, stage: StrategyStages.Observation); + Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, CorrectiveReasons.CalendarEvent, postponed: true)], [seen], [], _capital).Lines.Single().Delayed); + Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped); + } + + /// The decisions of the live engine, as they are written, give the balance. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ThePurchasesTheEngineHeldBackAreInTheBalance() + { + var day = new DateOnly(2026, 9, 1); + await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)); + live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock)); + await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9, + "CoinDesk", trusted: true); + await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero), + 3, -0.8, "CoinDesk", trusted: true); + await live.DayAsync(day); + var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList(); + Assert.HasCount(2, cases); + var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none); + Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open); + Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open); + + foreach (var e in cases) + { + var loses = e.Symbol == "ETH-EUR"; + await live.Rig.Db.WriteAsync(s => LearningStore.AddLabelAsync(s, live.Rig.Clock, e.Id, new CaseLabel(!loses, loses ? -0.1 : 0.04, e.Day.AddDays(1), e.Day.AddDays(9), "x"), _none), _none); + } + + var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto]; + var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none); + decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2); + Assert.IsGreaterThan(0m, r.Avoided); + Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m); + Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m); + Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, live.Rig.Clock.UtcNow.AddDays(1), _none)).IsEmpty); + } +} diff --git a/tests/Anubis.Tests/ReferenceSourcesTests.cs b/tests/Anubis.Tests/ReferenceSourcesTests.cs index b9ad7e4..cb8fd86 100644 --- a/tests/Anubis.Tests/ReferenceSourcesTests.cs +++ b/tests/Anubis.Tests/ReferenceSourcesTests.cs @@ -2,9 +2,12 @@ using System.IO.Compression; using System.Net; using System.Security.Cryptography; using System.Text; +using Anubis.Backtest; using Anubis.Brokers; using Anubis.Core; using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; namespace Anubis.Tests; @@ -283,6 +286,54 @@ public sealed class ReferenceSourcesTests } } + // Answers with a pause, and counts the requests open at once. + private sealed class SlowHttp(Func answer) : HttpMessageHandler + { + private int _open; + + public int MostOpen { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + MostOpen = Math.Max(MostOpen, Interlocked.Increment(ref _open)); + await Task.Delay(1, cancellationToken).ConfigureAwait(false); + Interlocked.Decrement(ref _open); + return answer(request.RequestUri!) is { } body ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) } : new HttpResponseMessage(HttpStatusCode.NotFound); + } + } + + /// The history of the quarterly review (SPEC 12.2): archives one at a time, in euro, and what is missing in words. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheHistoryOfTheReviewIsPreparedOnceAtATime() + { + var folder = TempFolder.Create("review-archives"); + try + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new FastClock(new DateTimeOffset(2017, 10, 15, 0, 0, 0, TimeSpan.Zero)); + var august = Zip("BTCUSDT-1d-2017-08.csv", Fixture.Text("free/binance-BTCUSDT-1d-2017-08.csv")); + var http = new SlowHttp(u => !u.ToString().Contains("2017-08", StringComparison.Ordinal) || !CryptoTrendProtocol.Narrow.Any(s => u.ToString().Contains(s[..3] + "USDT", StringComparison.Ordinal)) ? null + : u.ToString().EndsWith("CHECKSUM", StringComparison.Ordinal) ? Encoding.UTF8.GetBytes(Convert.ToHexStringLower(SHA256.HashData(august)) + " x.zip") : august); + var bus = new EventBus(); + using var market = new MarketDataService(test.Db, clock, bus, new SettingsStore(test.Db, clock, bus), new SecretStore(test.Db, clock, new byte[32]), new DataDirectory(folder), http); + var to = new DateOnly(2017, 8, 21); + Assert.AreEqual("mancano i cambi della BCE", await market.PrepareReviewHistoryAsync(to, CancellationToken.None).ConfigureAwait(false)); + await new FxStore(test.Db, clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2017, 8, 16), 1.17m, "ecb"), new FxRate("EUR", "USD", new DateOnly(2017, 8, 18), 1.17m, "ecb")], CancellationToken.None) + .ConfigureAwait(false); + var both = await Task.WhenAll(market.PrepareReviewHistoryAsync(to, CancellationToken.None), market.PrepareReviewHistoryAsync(to, CancellationToken.None)).ConfigureAwait(false); + CollectionAssert.AreEqual(new string?[] { null, null }, both); + Assert.AreEqual(1, http.MostOpen, "one import at a time"); + Assert.AreEqual("l'archivio di Binance di settembre 2017 non è ancora completo", await market.PrepareReviewHistoryAsync(new DateOnly(2017, 9, 30), CancellationToken.None).ConfigureAwait(false)); + using var offline = new MarketDataService(test.Db, clock, bus, new SettingsStore(test.Db, clock, bus), new SecretStore(test.Db, clock, new byte[32]), new DataDirectory(folder), http, offline: true); + Assert.AreEqual("la raccolta dei dati è spenta", await offline.PrepareReviewHistoryAsync(to, CancellationToken.None).ConfigureAwait(false)); + } + finally + { + TempFolder.Delete(folder); + } + } + [TestMethod] [TestCategory(Category.Integration)] public async Task CsvImporterFollowsTheMappingAndReportsWhatItCouldNotRead() diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs index 782b204..681ec81 100644 --- a/tests/Anubis.Tests/RiskEngineTests.cs +++ b/tests/Anubis.Tests/RiskEngineTests.cs @@ -589,6 +589,82 @@ public sealed class RiskEngineTests Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); } + private static async Task ReducedAsync(Setup s, Func? change = null) + { + var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)"); + await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + await RequirementsMetAsync(s); + await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none); + if (change is not null) + { + var q = change((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Qualification!); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(q, Qualification.Json)))), _none); + } + + return live; + } + + /// SPEC 12.3: a review not passed with the costs in force takes the strategy back to simulation, once; one that waits does not. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AReviewNotPassedDemotesAStrategyWithRealMoneyOnce() + { + await using var s = await CreateAsync(Consent()); + await ReducedAsync(s); + foreach (var verdict in new[] { ReviewVerdicts.Waiting, ReviewVerdicts.Error }) + { + await QuarterlyReviewTests.NextAsync(s.Rig.Db, s.Rig.Clock, verdict, new DateOnly(2026, verdict == ReviewVerdicts.Waiting ? 9 : 10, 30)); + } + + Assert.IsEmpty(await s.Stages.CheckDemotionsAsync(_none)); + await QuarterlyReviewTests.NextAsync(s.Rig.Db, s.Rig.Clock, ReviewVerdicts.Rejected, new DateOnly(2026, 12, 31)); + Assert.HasCount(1, await s.Stages.CheckDemotionsAsync(_none)); + Assert.IsEmpty(await s.Stages.CheckDemotionsAsync(_none)); + var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual((StrategyStages.Simulation, false), (stage.Stage, stage.ExitOnly), "no real position to close"); + Assert.HasCount(1, await EventsAsync(s.Rig, "demotion")); + Assert.HasCount(1, (await NewsRulesTests.DiaryAsync(s.Rig.Db)).Where(d => d.Contains("torna in simulazione (revisione trimestrale non superata)", StringComparison.Ordinal)).ToList()); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT message FROM notifications WHERE message LIKE '%revisione trimestrale non superata%'", r => r.Text("message"))); + } + + /// SPEC 12.3: past the year the expected path covers, its last value holds; the slippage is the strategy's own, stops aside. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemotionConditionsHoldAfterAYearAndLookAtTheStrategyAlone() + { + await using var s = await CreateAsync(Consent()); + var live = await ReducedAsync(s, q => q with { ExpectedPathP5 = [.. Enumerable.Range(0, 365).Select(i => -0.05)], MaxDrawdown = 0.9m }); + var since = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.StageSince!.Value; + for (var day = 0; day <= 400; day++) + { + var index = day < 380 ? 1m : 0.9m; + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync( + "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index) " + + "VALUES (@id, @t, 'strategy', @a, 'crypto_trend', @e, @e, 0, 0, @t, 'real', 'EUR', 2500, @x, 1)", _none, + ("id", Ids.NewId(s.Rig.Clock)), ("t", since.AddDays(day)), ("a", live.AccountId), ("e", 2_500m * index), ("x", index)), _none); + } + + var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual("expected_path", (await s.Stages.DemotionConditionsAsync(stage, _none)).Single().Key); + + async Task FillAsync(string strategy, OrderPurpose purpose, decimal bp) + { + var order = Ids.NewId(s.Rig.Clock); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("INSERT INTO orders (id, account_id, instrument_id, strategy, side, order_type, quantity, status, client_order_id, purpose, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, 'buy', 'market', 0.0001, 'filled', @c, @p, @t, @t)", _none, ("id", order), ("a", live.AccountId), ("i", s.Btc.Id), ("s", strategy), + ("c", "T" + order.ToString("N")[..20]), ("p", Wire.Text(purpose)), ("t", s.Rig.Clock.UtcNow)), _none); + await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(live, s.Btc, strategy, OrderSide.Buy, 0.0001m, 60_000m) with { OrderId = order, ReferencePrice = 60_000m / (1m + (bp / 10_000m)) }, _none); + } + + await FillAsync(StrategyNames.CryptoTrend, OrderPurpose.Entry, 6m); + await FillAsync(StrategyNames.CryptoTrend, OrderPurpose.Stop, 400m); + await FillAsync("sma_cross", OrderPurpose.Entry, 400m); + Assert.AreEqual(6m, Math.Round((await s.Stages.FiguresAsync(stage, _none)).SlippageBp!.Value, 2)); + Assert.IsFalse((await s.Stages.DemotionConditionsAsync(stage, _none)).Any(c => c.Key == "slippage")); + await FillAsync(StrategyNames.CryptoTrend, OrderPurpose.Entry, 40m); + Assert.IsTrue((await s.Stages.DemotionConditionsAsync(stage, _none)).Any(c => c.Key == "slippage"), "23 points against 5 expected"); + } + [TestMethod] [TestCategory(Category.Integration)] public async Task TheTwinIsPhotographedButLeftOutOfTheTotals() diff --git a/tests/Anubis.Tests/StrategyScreensTests.cs b/tests/Anubis.Tests/StrategyScreensTests.cs index ed1416e..c2565b3 100644 --- a/tests/Anubis.Tests/StrategyScreensTests.cs +++ b/tests/Anubis.Tests/StrategyScreensTests.cs @@ -101,6 +101,16 @@ public sealed class StrategyScreensTests using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione"); Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused)); Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage); + + // The outcome of a quarterly review is a page of the laboratory; the one of the program a file of the repository. + StringAssert.Contains(page, "docs/backtests/crypto_trend.md"); + var review = Guid.NewGuid(); + var measured = new Qualification { Passed = true, Verdict = "superata", Report = "/laboratorio/revisione/" + review }; + await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q WHERE strategy = 'crypto_trend'", CancellationToken.None, + ("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(measured, Qualification.Json)))), CancellationToken.None); + var after = await server.TextAsync("/strategie"); + StringAssert.Contains(after, $"Rapporto"); + StringAssert.Contains(after, "dopo 90 giorni di osservazione può passare in simulazione"); } [TestMethod]