Files
Anubis/tests/Anubis.Tests/LaboratoryScreenTests.cs
T
Alby96andClaude Opus 5.5 2257c3e16c Review the base strategies every three months
Every quarter the base strategies are tried again on the longer history with
the slippage in force, compared with how they did live, and the report is
published in the laboratory with the base rates measured again and the balance
of the restrictions of 10.5. In observation the outcome replaces the old one and
a strategy that passed goes to simulation after its 90 days; with capital
nothing moves but the demotion condition of 12.3. A restart halfway goes on and
the review concludes once; the outcome of a review survives a restart with an
older build.

refs #74

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

258 lines
14 KiB
C#

using System.Net;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Server;
namespace Anubis.Tests;
/// <summary>The Laboratorio screen (issue #36): a new test from the form, its report, the comparison.</summary>
[TestClass]
public sealed class LaboratoryScreenTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheReportOpensFromTheLaboratory()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var db = server.Host.Services!.Db;
var btc = await new InstrumentCatalog(db, SystemClock.Instance).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None);
await new BarStore(db, SystemClock.Instance).UpsertDailyAsync(btc.Id,
BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)), "test", CancellationToken.None);
var empty = await server.TextAsync("/laboratorio");
StringAssert.Contains(empty, "Nessun test eseguito.");
StringAssert.Contains(empty, "Scrivi il piano e avvia il test");
StringAssert.Contains(empty, "Migliorie in osservazione");
StringAssert.Contains(empty, "Stime di costo da confermare");
// A grid value out of range goes back to the form with the reason, and nothing is planned.
using (var wrong = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields(("griglia_fast", "1, 5"))))
{
Assert.AreEqual("/laboratorio?errore=griglia&strategia=sma_cross#nuovo", ServerHarness.Location(wrong));
}
StringAssert.Contains(await server.TextAsync("/laboratorio?errore=griglia&strategia=sma_cross"), "fuori dall'intervallo del parametro");
Assert.HasCount(0, await new TrialStore(db, SystemClock.Instance).ListAsync(10, CancellationToken.None));
var first = await PlanAsync(server, Fields());
var second = await PlanAsync(server, Fields(("griglia_fast", "10"), ("griglia_slow", "30")));
await WaitAsync(db, first);
await WaitAsync(db, second);
var list = await server.TextAsync("/laboratorio");
StringAssert.Contains(list, $"href=\"/laboratorio/{first}\"");
StringAssert.Contains(list, "Completato");
StringAssert.Contains(list, "Confronta");
var report = await server.TextAsync($"/laboratorio/{first}");
foreach (var part in new[]
{
"Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)",
"Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano",
"K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera",
"esempio: correttivi e limiti di rischio non si applicano", "Impronta dei dati", "Vedi i numeri in una tabella",
})
{
StringAssert.Contains(report, part, $"Missing \"{part}\" in the report.");
}
var compare = await server.TextAsync($"/laboratorio/confronto?a={first}&b={second}");
StringAssert.Contains(compare, "Stessi dati per entrambi");
StringAssert.Contains(compare, "non si applica", "The second test has one variant: no PBO.");
StringAssert.Contains(await server.TextAsync("/laboratorio/confronto?a=nonunid&b=" + first), "Servono due test completati.");
using var missing = await server.GetAsync($"/laboratorio/{Guid.NewGuid()}");
StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato.");
}
/// <summary>SPEC 11.6: a lower slippage waits in the Laboratorio for the confirmation of the user.</summary>
/// <summary>SPEC 12.2, 13.6: the review in the laboratory, its page, and the empty state before the first.</summary>
[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<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 },
RatesAfter = new Dictionary<string, double> { [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<Guid> 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()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var db = server.Host.Services!.Db;
async Task<Guid> PendingAsync(decimal bp)
{
var id = Ids.NewId(SystemClock.Instance);
await 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, 'crypto_minor', 'pending', @p, @b, @b, @b, @b, 40, @now, @now)",
CancellationToken.None, ("id", id), ("p", 15m), ("b", bp), ("now", DateTimeOffset.UtcNow)));
return id;
}
var refused = await PendingAsync(9m);
StringAssert.Contains(await server.TextAsync("/laboratorio"), "Altre crypto: da 15 punti base a 9 punti base.");
using (var no = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/rifiuta", []))
{
Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(no));
}
using (var late = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/conferma", []))
{
Assert.AreEqual("/laboratorio?errore=stima#stime", ServerHarness.Location(late));
}
var confirmed = await PendingAsync(8m);
// Without the token of the page nothing is decided.
using (var forged = await server.Http.PostAsync(new Uri($"/azioni/stime-di-costo/{confirmed}/conferma", UriKind.Relative), new FormUrlEncodedContent([])))
{
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, forged.StatusCode);
}
using (var seen = await server.Http.PostAsync(new Uri($"/azioni/assenza/{confirmed}/vista", UriKind.Relative), new FormUrlEncodedContent([])))
{
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, seen.StatusCode);
}
using (var yes = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{confirmed}/conferma", []))
{
Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(yes));
}
var page = await server.TextAsync("/laboratorio");
StringAssert.Contains(page, "altre crypto 8 punti base");
StringAssert.Contains(page, "Confermata da te");
StringAssert.Contains(page, "Rifiutata da te");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoRunsNoTests()
{
string demoRoot;
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
demoRoot = server.Host.Config.Data.Root;
var page = await server.TextAsync("/laboratorio");
StringAssert.Contains(page, "Il laboratorio non esegue test in questa modalità.");
Assert.IsFalse(page.Contains("/azioni/laboratorio", StringComparison.Ordinal), "No form in the demo.");
using var post = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields());
Assert.AreEqual("/laboratorio?errore=motore&strategia=sma_cross#nuovo", ServerHarness.Location(post));
}
// After the server has stopped, so the demo database is closed.
TempFolder.Delete(demoRoot);
}
private static (string, string)[] Fields(params (string Name, string Value)[] overrides)
{
var fields = new Dictionary<string, string>(StringComparer.Ordinal)
{
["strategia"] = "sma_cross",
["origine"] = TrialSources.Database,
["mercato"] = Venues.Okx,
["strumenti"] = "btc-eur",
["dal"] = "2024-01-01",
["al"] = "2025-02-03",
["capitale"] = "10.000",
["griglia_fast"] = "5, 10",
["griglia_slow"] = "20, 40",
};
foreach (var (name, value) in overrides)
{
fields[name] = value;
}
return [.. fields.Select(f => (f.Key, f.Value))];
}
private static async Task<Guid> PlanAsync(ServerHarness server, (string, string)[] fields)
{
using var response = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", fields);
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode);
var location = ServerHarness.Location(response);
StringAssert.StartsWith(location, "/laboratorio/");
return Guid.Parse(location["/laboratorio/".Length..]);
}
private static async Task WaitAsync(Anubis.Db.Database db, Guid id)
{
var store = new TrialStore(db, SystemClock.Instance);
for (var i = 0; i < 600; i++)
{
var trial = await store.GetAsync(id, CancellationToken.None);
if (trial!.IsFinished)
{
Assert.AreEqual(TrialStatuses.Done, trial.Status, trial.Error);
return;
}
await Task.Delay(50);
}
Assert.Fail("The trial did not finish in 30 seconds.");
}
}