ci / test (postgres) (push) Failing after 6m9s
ci / test (sqlite) (push) Successful in 7m6s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Successful in 5m51s
ci / test (sqlite) (pull_request) Successful in 7m3s
ci / image (pull_request) Successful in 1m51s
One funded signal was enough to start the model for good, because the interval of a few cases had no width: it now takes a hundred, weighed among themselves. A computer always off at 03:00 never made the night of the model: a job to make up for counts from the first start that knows it, and the night waits for the bars of the absence. Stories are seen as they were when the decision was due, a report already out does not close a label, an undone promotion starts the trial again, and the trade card finds the estimate of an example born earlier. ADR 0018 point 18 has the list; each defect has its test. refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
421 lines
32 KiB
C#
421 lines
32 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Db;
|
|
using Anubis.Learning;
|
|
using Anubis.Server;
|
|
using Anubis.Strategies;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>The Apprendimento screen, the model settings and the model box of the Panoramica (SPEC 13.5, 13.6; issue #66).</summary>
|
|
[TestClass]
|
|
public sealed class LearningScreenTests
|
|
{
|
|
private static readonly CancellationToken _none = CancellationToken.None;
|
|
|
|
private static readonly DateTimeOffset Now = new(2026, 10, 9, 6, 21, 0, TimeSpan.Zero);
|
|
|
|
private static readonly Dictionary<string, double> Rates = new() { [StrategyNames.CryptoTrend] = 0.4 };
|
|
|
|
private static readonly Dictionary<string, double> Capitals = new() { [StrategyNames.CryptoTrend] = 1000 };
|
|
|
|
private static void HasAll(string page, params string[] texts)
|
|
{
|
|
foreach (var text in texts)
|
|
{
|
|
StringAssert.Contains(page, text, $"Missing \"{text}\".");
|
|
}
|
|
}
|
|
|
|
/// <summary>The numbers of appendix F.7 as in the mockup, on the page, in the Panoramica and in Operazioni; nothing can be changed.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheDemoShowsTheModelAsInTheMockup()
|
|
{
|
|
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
|
var demoRoot = server.Host.Config.Data.Root;
|
|
try
|
|
{
|
|
var page = await server.TextAsync("/apprendimento");
|
|
HasAll(page, "Il modello impara dall'esito di ogni segnale.", "In osservazione", "Sta imparando, ma non decide ancora.",
|
|
"Non potrà mai ingrandirle, né aprirne di sue.", "<strong>212</strong> <span class=\"muted\">su 300 necessari</span>", "Al ritmo attuale, tra tre e quattro settimane.",
|
|
"56%", "Tirando a caso sarebbe il 50%", "Domenica 4 ottobre, versione 3", "Prossima verifica dello sfidante", "Domenica 11 ottobre, 03:00",
|
|
"54% su 61 casi", "71% su 14 casi", "Stima perfetta", "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato.", "troppo pochi casi per contarci",
|
|
"Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "insieme a paura e avidità pesano 17 su 100.",
|
|
"In carica, versione 2", "Sfidante, versione 3", "16 agosto", "2.152", "2.332", "0,241", "0,239", "(senza filtro: +5,84", "+7,90", "+8,10", "non serve", "14 su 100",
|
|
"La versione 3 è ancora in prova.", "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100", "Fino ad allora gira in ombra accanto alla 2.",
|
|
"Nessuna anomalia", "Il mercato di oggi somiglia a quello su cui ha studiato", "Precisione sugli ultimi 60 casi: 55%, in linea con il 56% atteso",
|
|
"Ultimo controllo oggi alle 03:00. Ultimo allarme il 19 settembre, rientrato in 3 giorni", "17 ago", "5 ott", "sotto 50%", "49%",
|
|
"I segnali di trend riescono meno quando il mercato è molto agitato", "32 casi: un indizio discreto", "17 casi: troppo pochi per fidarsi", "212 casi: conclusione solida",
|
|
"27 settembre", "Prima versione, addestrata su 2.140 segnali ricostruiti dai dati storici.", "Vedi i numeri in una tabella");
|
|
Assert.IsFalse(page.Contains("/azioni/modello", StringComparison.Ordinal), "nothing to change in the demo");
|
|
HasAll(await server.TextAsync("/"), "Il modello osserva e impara, ma non decide ancora.", "su 300 necessari", "56% su dati mai visti", "domenica 11 ottobre, 03:00");
|
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%): solo osservazione, non ha cambiato la dimensione");
|
|
|
|
// The signal was born three days before the purchase, held back meanwhile: same example, same estimate.
|
|
var (db, clock) = (server.Host.Services!.Db, server.Host.Clock);
|
|
var earlier = Ids.NewId(clock);
|
|
await db.WriteAsync(async s =>
|
|
{
|
|
var at = (await s.FirstOrDefaultAsync("SELECT created_at FROM decisions WHERE stage = 'model' AND symbol = 'MSFT'", r => (DateTimeOffset?)r.Moment("created_at")))!.Value.AddDays(-3);
|
|
await s.ExecuteAsync("UPDATE decisions SET decision_id = @d, created_at = @at WHERE stage = 'model' AND symbol = 'MSFT'", _none, ("d", earlier), ("at", at));
|
|
await LearningStore.AddAsync(s, clock, new Example(Guid.Empty, StrategyNames.EquityMeanrev, "MSFT", CaseSources.Live, DateOnly.FromDateTime(at.UtcDateTime), at, "x", 0.2m, null, null,
|
|
new Dictionary<string, double>())
|
|
{ DecisionId = earlier }, _none);
|
|
}, _none);
|
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
|
|
|
|
// Born the evening before, with the simulated operation closed on the day of the purchase: still the one bought.
|
|
var opened = (await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT t.opened_at FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE i.symbol = 'MSFT' AND t.status = 'closed' ORDER BY t.opened_at DESC LIMIT 1", r => (DateTimeOffset?)r.Moment("opened_at")), _none))!.Value;
|
|
await db.WriteAsync(async s =>
|
|
{
|
|
await s.ExecuteAsync("UPDATE decisions SET created_at = @at WHERE decision_id = @d", _none, ("at", opened.AddHours(-10)), ("d", earlier));
|
|
var example = (await s.FirstOrDefaultAsync("SELECT id FROM ml_features WHERE decision_id = @d", r => (Guid?)r.Id("id"), ("d", earlier)))!.Value;
|
|
var day = DateOnly.FromDateTime(opened.UtcDateTime);
|
|
await LearningStore.AddLabelAsync(s, clock, example, new CaseLabel(false, -0.01, day.AddDays(-2), day, "x"), _none);
|
|
}, _none);
|
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
|
|
using var post = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
|
|
Assert.AreEqual("/apprendimento?errore=motore", ServerHarness.Location(post));
|
|
using var settings = await server.PostFormAsync("/impostazioni", "/azioni/modello", (LearningSettings.Aside.Key, "on"));
|
|
Assert.AreEqual("/impostazioni?errore=motore#modello", ServerHarness.Location(settings));
|
|
}
|
|
finally
|
|
{
|
|
await server.DisposeAsync();
|
|
}
|
|
|
|
TempFolder.Delete(demoRoot);
|
|
}
|
|
|
|
/// <summary>A new installation: no invented number, then the first model, the live signals, the challenger, the undo.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ThePageFollowsTheArchiveAndTheUserTakesAPromotionBack()
|
|
{
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
|
await using var keep = postgres;
|
|
await using var server = await ServerHarness.StartAsync("docker", env);
|
|
await server.SignInFirstTimeAsync();
|
|
var services = server.Host.Services!;
|
|
var (db, clock) = (services.Db, server.Host.Clock);
|
|
HasAll(await server.TextAsync("/apprendimento"), "Non ancora partito", "Non ha ancora cominciato.", "Prima verifica", "Nessun modello ancora.", "La storia comincia con il primo modello.",
|
|
"Il controllo gira ogni notte alle 03:00", "Nessuna stima ha ancora un esito.");
|
|
HasAll(await server.TextAsync("/impostazioni"), "Nessuna promozione da annullare.");
|
|
using (var none = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione"))
|
|
{
|
|
Assert.AreEqual("/apprendimento?errore=promozione", ServerHarness.Location(none));
|
|
}
|
|
|
|
HasAll(await server.TextAsync("/apprendimento?errore=promozione"), "Non c'è nessuna promozione da annullare.");
|
|
|
|
// The first model with the report of its verification.
|
|
var desk = new LearningDesk(db, clock, services.Settings);
|
|
await desk.PrepareHistoryAsync(_none);
|
|
var first = (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!;
|
|
var scores = first.Report.Attempts.Single(a => a.Chosen).Combined;
|
|
HasAll(await server.TextAsync("/apprendimento"), "In osservazione", "<strong>0</strong> <span class=\"muted\">su 300 necessari</span>", "È presto per dire quanto manca.",
|
|
"Per ora sono i casi storici che non aveva studiato", "In carica, versione 1", Format.Number(first.Examples), Format.Number((decimal)scores.Brier, 3),
|
|
"Nessuno sfidante in prova.", "Prossimo addestramento", "Come è stato scelto il modello in carica", first.Report.Reason, "Primo modello: versione 1");
|
|
Assert.AreEqual(100, first.Report.Weights.Sum(w => w.Share), "the clues add up to 100");
|
|
HasAll(await server.TextAsync("/"), "Il modello osserva e impara", "su 300 necessari");
|
|
|
|
// A challenger beside it, and signals both estimated: 120 closed in the last four weeks.
|
|
var second = await LearningCycleTests.AddModelAsync(db, clock, LearningCycleTests.Always(0.5), ModelStatuses.Challenger);
|
|
var today = Zones.DayIn(clock.UtcNow, Zones.Rome);
|
|
await db.WriteAsync(async s =>
|
|
{
|
|
for (var i = 0; i < 120; i++)
|
|
{
|
|
var day = today.AddDays(-30 + (i % 28));
|
|
var win = i % 2 == 0;
|
|
var id = (await LearningStore.AddAsync(s, clock, new Example(Guid.Empty, StrategyNames.CryptoTrend, "C" + i, CaseSources.Live, day, clock.UtcNow.AddDays(-30 + (i % 28)), "trend_entry", 0.2m, null,
|
|
null, new Dictionary<string, double> { [Clues.Strength] = 0.5 })
|
|
{ Stage = StrategyStages.Simulation, Label = new CaseLabel(win, win ? 0.02 : -0.02, day, day.AddDays(1), "x") }, _none))!.Value;
|
|
await ModelStore.AddPredictionAsync(s, clock, new PredictionRow(id, first.Id, win ? 0.47 : 0.33, 0.4, 1, true), _none);
|
|
await ModelStore.AddPredictionAsync(s, clock, new PredictionRow(id, second.Id, win ? 0.61 : 0.22, 0.4, 1, false), _none);
|
|
}
|
|
|
|
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { Health = new HealthCheck { At = clock.UtcNow, Precision = 1, Cases = 60 } }, _none);
|
|
}, _none);
|
|
var page = await server.TextAsync("/apprendimento");
|
|
HasAll(page, "<strong>120</strong> <span class=\"muted\">su 300 necessari</span>", "Sfidante, versione 2", "120 su 100", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto. Si decide ",
|
|
"Prossima verifica dello sfidante", "Al ritmo attuale, tra", "tra 45% e 50%", "Precisione sugli ultimi 60 casi: 100%, sopra il", "Nessun allarme finora", "Nessuna anomalia");
|
|
Assert.IsFalse(page.Contains("Per ora sono i casi storici", StringComparison.Ordinal), "the live bands count now");
|
|
Assert.IsFalse(page.Contains("Annulla l'ultima promozione", StringComparison.Ordinal));
|
|
|
|
// Promoted, then taken back with one click, once.
|
|
await db.WriteAsync(async s =>
|
|
{
|
|
await ModelStore.SetStatusAsync(s, clock, first.Id, ModelStatuses.Retired, _none);
|
|
await ModelStore.SetStatusAsync(s, clock, second.Id, ModelStatuses.Champion, _none);
|
|
await ModelStore.SetReplacedAsync(s, clock, second.Id, first.Id, _none);
|
|
}, _none);
|
|
HasAll(await server.TextAsync("/apprendimento"), "Annulla l'ultima promozione", "Tornerebbe in carica la versione 1.", "In carica, versione 2");
|
|
HasAll(await server.TextAsync("/impostazioni"), "Tornerebbe in carica la versione 1.");
|
|
using (var undo = await server.PostFormAsync("/impostazioni", "/azioni/modello/annulla-promozione", ("ritorno", "/impostazioni")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?ok=promozione#modello", ServerHarness.Location(undo));
|
|
}
|
|
|
|
Assert.AreEqual(first.Id, (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!.Id);
|
|
HasAll(await server.TextAsync("/apprendimento"), "In carica, versione 1", "Promozione annullata da te: torna in carica la versione 1 al posto della 2.");
|
|
using var again = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
|
|
Assert.AreEqual("/apprendimento?errore=promozione", ServerHarness.Location(again));
|
|
}
|
|
|
|
/// <summary>SPEC 13.5, 12.4: the thresholds and the set-aside from Impostazioni; shrinking less needs the phrase with real money.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheModelSettingsAreSavedAndGuardedWithRealMoney()
|
|
{
|
|
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
|
await using var keep = postgres;
|
|
await using var server = await ServerHarness.StartAsync("docker", env, marketHttp: network, trading: true);
|
|
var password = await server.SignInFirstTimeAsync();
|
|
var services = server.Host.Services!;
|
|
async Task<string> ValueAsync(SettingDefinition d) => (await services.Settings.GetAsync(d.Key, _none)).Value;
|
|
async Task PostAsync(string expected, params (string, string)[] fields)
|
|
{
|
|
using var post = await server.PostFormAsync("/impostazioni", "/azioni/modello", fields);
|
|
Assert.AreEqual("/impostazioni?" + expected + "#modello", ServerHarness.Location(post));
|
|
}
|
|
|
|
HasAll(await server.TextAsync("/impostazioni"), "Acquisto intero fino a", "Nessun acquisto da", "10 punti sotto", "Al suo posto");
|
|
await PostAsync("ok=apprendimento", (LearningSettings.Full.Key, "2"), (LearningSettings.Zero.Key, "15"), (LearningSettings.Aside.Key, "on"));
|
|
Assert.AreEqual(("2", "15", "on"), (await ValueAsync(LearningSettings.Full), await ValueAsync(LearningSettings.Zero), await ValueAsync(LearningSettings.Aside)));
|
|
HasAll(await server.TextAsync("/impostazioni?ok=apprendimento"), "Impostazioni del modello salvate", "Messo da parte: non conta");
|
|
await PostAsync("errore=impostazione", (LearningSettings.Full.Key, "0"), (LearningSettings.Zero.Key, "1"));
|
|
Assert.AreEqual("2", await ValueAsync(LearningSettings.Full), "nothing of a wrong form is saved");
|
|
|
|
// Not through the API, nor through the form of the other settings.
|
|
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
|
|
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + LearningSettings.Zero.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "20" }) })
|
|
{
|
|
request.Headers.Add(csrf!["header"], csrf["token"]);
|
|
using var put = await server.Http.SendAsync(request);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
|
|
}
|
|
|
|
using (var other = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LearningSettings.Zero.Key, ("valore", "20")))
|
|
{
|
|
StringAssert.Contains(ServerHarness.Location(other), "errore=impostazione");
|
|
}
|
|
|
|
Assert.AreEqual("15", await ValueAsync(LearningSettings.Zero));
|
|
|
|
// With real money: more shrinking is free, less is not.
|
|
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", _none, ("s", StrategyNames.CryptoTrend)), _none);
|
|
HasAll(await server.TextAsync("/impostazioni"), "per rimpicciolire meno, o mettere da parte il modello, servono la frase e la password");
|
|
await PostAsync("ok=apprendimento", (LearningSettings.Zero.Key, "10"), (LearningSettings.Aside.Key, "off"));
|
|
await PostAsync("errore=frase-rischio", (LearningSettings.Zero.Key, "15"));
|
|
await PostAsync("errore=frase-rischio", (LearningSettings.Full.Key, "5"));
|
|
await PostAsync("errore=frase-rischio", (LearningSettings.Aside.Key, "on"));
|
|
Assert.AreEqual(("2", "10", "off"), (await ValueAsync(LearningSettings.Full), await ValueAsync(LearningSettings.Zero), await ValueAsync(LearningSettings.Aside)));
|
|
await PostAsync("ok=apprendimento", (LearningSettings.Aside.Key, "on"), ("frase", StageBook.RaisePhrase), ("password", password));
|
|
Assert.AreEqual("on", await ValueAsync(LearningSettings.Aside));
|
|
}
|
|
|
|
// ---- The sentences ------------------------------------------------------------------------------------------
|
|
|
|
private static ModelRow Row(string status, int version, int examples = 500, Guid? replaced = null, IReadOnlyList<ClueWeight>? weights = null, double? gainWithout = null) => new(Guid.NewGuid(), version,
|
|
LearnerNames.Logistic, status, "test", Now.AddDays(-5), examples, 0, replaced, LearningCycleTests.Always(0.4), new ModelReport
|
|
{
|
|
Examples = examples,
|
|
Attempts = [new Attempt(LearnerNames.Logistic, new Scores(), new Scores { Cases = 100, Precision = 0.56, Brier = 0.2412, GainWith = 7.9, GainWithout = gainWithout ?? 5.84 }, true)],
|
|
Weights = weights ?? [],
|
|
});
|
|
|
|
private static LearningView View(CycleState state, bool aside = false, IReadOnlyList<SeenEstimate>? estimates = null, IReadOnlyList<ModelEvent>? events = null, params ModelRow[] models) =>
|
|
LearningView.Of(new LearningSnapshot([], estimates ?? [], models, state), Rates, Capitals, aside, new DiscoverySet(), events ?? [], Now);
|
|
|
|
private static SeenEstimate Seen(Guid model, int daysAgo, bool win, double probability, bool inCharge = true, double multiplier = 1)
|
|
{
|
|
var day = Zones.DayIn(Now, Zones.Rome).AddDays(-daysAgo);
|
|
return new SeenEstimate(model, inCharge, new Estimate(new Example(Guid.NewGuid(), StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.Live, day, Now, "x", 0.2m, null, null,
|
|
new Dictionary<string, double> { [Clues.Strength] = 0.5 })
|
|
{ Stage = StrategyStages.Simulation, Label = new CaseLabel(win, win ? 0.02 : -0.02, day, day, "x") }, probability, 0.4, multiplier));
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheStateSaysWhetherTheModelCounts()
|
|
{
|
|
var champion = Row(ModelStatuses.Champion, 1);
|
|
Assert.AreEqual(LearningStates.None, View(new CycleState()).Summary.State);
|
|
Assert.AreEqual(LearningStates.Observation, View(new CycleState(), models: champion).Summary.State);
|
|
var active = View(new CycleState { ActivatedAt = Now.AddDays(-2) }, models: champion);
|
|
Assert.AreEqual(LearningStates.Active, active.Summary.State);
|
|
StringAssert.Contains(active.Text, "Dal 7 ottobre le sue stime contano");
|
|
Assert.IsNull(active.Pace);
|
|
|
|
var health = new HealthCheck { At = Now.AddHours(-5), Precision = 0.45, Cases = 41, Aside = AsideCodes.Precision };
|
|
var alarm = new[] { new ModelEvent(ModelEvents.SetAside, 1, "Allarme", Now.AddDays(-1)) };
|
|
var aside = View(new CycleState { ActivatedAt = Now.AddDays(-20), Aside = AsideCodes.Precision, AsideAt = Now.AddDays(-1), Health = health }, events: alarm, models: champion);
|
|
Assert.AreEqual(LearningStates.Aside, aside.Summary.State);
|
|
StringAssert.Contains(aside.Text, "Precisione scesa al 45% su 41 casi. Le strategie proseguono senza di lui.");
|
|
Assert.IsTrue(aside.Anomaly);
|
|
Assert.IsTrue(aside.Checks.Any(c => c is { State: "warn", Text: "Precisione sugli ultimi 41 casi: 45%, sotto il 56% atteso" }));
|
|
Assert.IsTrue(aside.Checks.Any(c => c.Text.EndsWith("Ultimo allarme il 8 ottobre, ancora in corso", StringComparison.Ordinal)), string.Join('|', aside.Checks));
|
|
|
|
// The user's own set-aside wins over everything, even over an alarm.
|
|
Assert.AreEqual(LearningStates.Manual, View(new CycleState { Aside = AsideCodes.Precision, ActivatedAt = Now }, aside: true, models: champion).Summary.State);
|
|
Assert.AreEqual("Hai messo da parte il modello: le strategie proseguono senza di lui.", View(new CycleState(), aside: true, models: champion).Summary.Sentence);
|
|
|
|
// Back after three days.
|
|
var back = View(new CycleState { Health = health with { Aside = null, Precision = 0.55 } },
|
|
events: [new ModelEvent(ModelEvents.SetAside, 1, "a", Now.AddDays(-20)), new ModelEvent(ModelEvents.Back, 1, "b", Now.AddDays(-17))], models: champion);
|
|
StringAssert.EndsWith(back.Checks[^1].Text, "Ultimo controllo oggi alle 03:21. Ultimo allarme il 19 settembre, rientrato in 3 giorni");
|
|
Assert.AreEqual("wait", back.Checks[0].State, "too few live signals to compare the market");
|
|
|
|
// A check of another version says nothing of the one in charge now.
|
|
var changed = View(new CycleState { Health = health with { Version = 7 } }, models: champion);
|
|
StringAssert.StartsWith(changed.Checks.Single().Text, "Il modello in carica è cambiato: il primo controllo è alle 03:00.");
|
|
Assert.IsTrue(View(new CycleState { Health = health with { DriftingClues = ["Volumi scambiati"] } }, models: champion).Checks[0] is { State: "warn" });
|
|
}
|
|
|
|
/// <summary>With 300 signals it still says what is missing; the count is of the system, not of the version.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheProgressSaysWhatIsMissing()
|
|
{
|
|
var (retired, champion) = (Row(ModelStatuses.Retired, 1), Row(ModelStatuses.Champion, 2));
|
|
List<SeenEstimate> Estimates(int count, double said) => [.. Enumerable.Range(0, count).Select(i => Seen(i % 2 == 0 ? retired.Id : champion.Id, 1 + (i % 28), i % 5 < 2, said))];
|
|
var some = View(new CycleState(), estimates: Estimates(212, 0.41), models: [retired, champion]);
|
|
Assert.AreEqual(212, some.Summary.Signals);
|
|
Assert.AreEqual("Al ritmo attuale, tra una e due settimane.", some.Pace);
|
|
Assert.HasCount(0, some.Missing);
|
|
|
|
var full = View(new CycleState(), estimates: Estimates(300, 0.41), models: [retired, champion]);
|
|
Assert.AreEqual("Ha visto abbastanza casi, ma non decide ancora.", full.Title);
|
|
Assert.IsNull(full.Pace);
|
|
Assert.HasCount(1, full.Missing, "well calibrated, but no gain");
|
|
StringAssert.StartsWith(full.Missing[0], "Non è ancora provato");
|
|
var wrong = View(new CycleState(), estimates: Estimates(300, 0.62), models: [retired, champion]);
|
|
Assert.HasCount(2, wrong.Missing);
|
|
StringAssert.StartsWith(wrong.Missing[0], "Le probabilità non sono ancora ben tarate: sbagliano in media di 22,0 punti, il massimo è 5.");
|
|
|
|
Assert.AreEqual("È presto per dire quanto manca.", View(new CycleState(), estimates: [Seen(champion.Id, 3, true, 0.5)], models: champion).Pace);
|
|
Assert.AreEqual("Nelle ultime settimane nessun segnale si è concluso.", View(new CycleState(), estimates: [Seen(champion.Id, 60, true, 0.5)], models: champion).Pace);
|
|
Assert.AreEqual("Al ritmo attuale, meno di una settimana.", LearningView.PaceWords(0.4));
|
|
Assert.AreEqual("Al ritmo attuale, circa due settimane.", LearningView.PaceWords(2));
|
|
Assert.AreEqual("Al ritmo attuale, circa 5 mesi.", LearningView.PaceWords(20));
|
|
Assert.AreEqual("Al ritmo attuale, più di un anno.", LearningView.PaceWords(80));
|
|
}
|
|
|
|
/// <summary>What is shown as happened is counted, not weighed by maturation.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheBandsSayWhatReallyHappened()
|
|
{
|
|
var champion = Row(ModelStatuses.Champion, 1);
|
|
var view = View(new CycleState(), estimates: [.. Enumerable.Range(0, 20).Select(i => Seen(champion.Id, 3, i == 0, 0.41))], models: champion);
|
|
Assert.AreEqual(new LearningBand(40, 45, 20, 41, 5), view.Bands.Single());
|
|
Assert.IsFalse(view.BandsFromHistory);
|
|
}
|
|
|
|
/// <summary>What the trade card says when the model would count but is set aside.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheTradeCardSaysWhyTheModelChangedNothing()
|
|
{
|
|
string Line(string tail) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":1" + tail + "}")!;
|
|
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":true"), ": era messo da parte, non ha cambiato la dimensione");
|
|
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":false"), ": solo osservazione, non ha cambiato la dimensione");
|
|
StringAssert.EndsWith(Line(",\"counts\":true,\"aside\":false"), ": taglia piena");
|
|
string Reduced(string applied) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":" + applied + "}")!;
|
|
StringAssert.EndsWith(Reduced("0.996"), ": acquisto ridotto al 99%");
|
|
StringAssert.EndsWith(Reduced("0.004"), ": acquisto ridotto al 1%");
|
|
StringAssert.EndsWith(Reduced("0"), ": acquisto non fatto");
|
|
}
|
|
|
|
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheBandsUnderTwentyCasesAreSaidUnreliable()
|
|
{
|
|
static LearningBand B(int from, int cases, decimal observed) => new(from, from + 5, cases, from + 2.5m, observed);
|
|
Assert.IsTrue(B(40, 20, 41).Solid);
|
|
Assert.IsFalse(B(40, 19, 41).Solid);
|
|
Assert.AreEqual("Quando stima tra il 60 e il 65%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.",
|
|
LearningView.BandsWords([B(50, 61, 54), B(60, 25, 60), B(65, 14, 71)]));
|
|
Assert.AreEqual("Quando stima tra il 45 e il 50%, è andata bene il 20% delle volte: non è ancora ben tarato, in media sbaglia di 27,5 punti. Sotto il 45% ha visto solo un caso, troppo poco per contarci.",
|
|
LearningView.BandsWords([B(30, 1, 0), B(45, 30, 20)]));
|
|
StringAssert.EndsWith(LearningView.BandsWords([B(30, 30, 30), B(35, 3, 30), B(45, 30, 47)]), "Nelle fasce di mezzo con meno di 20 casi ha visto solo 3 casi, troppo pochi per contarci.");
|
|
Assert.AreEqual("Nessuna fascia ha ancora 20 casi: troppo pochi per contarci.", LearningView.BandsWords([B(30, 19, 30)]));
|
|
|
|
// The judge is the error of the criterion to start counting, as the rest of the page says it.
|
|
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 20)], 0.01), "è andata bene il 20% delle volte: è ben tarato.");
|
|
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 47)], 0.06), "non è ancora ben tarato, in media sbaglia di 6,0 punti.");
|
|
}
|
|
|
|
/// <summary>The clues after the ninth are "Tutto il resto", the whole stays 100; the sentence about the news follows the numbers.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheCluesAddUpToAHundred()
|
|
{
|
|
LearningView Of(params (string Name, int Share)[] weights) => View(new CycleState(), models: Row(ModelStatuses.Champion, 1, weights: [.. weights.Select(w => new ClueWeight(w.Name, w.Share))]));
|
|
var many = Of(("A", 20), ("B", 15), ("C", 12), ("D", 11), ("E", 10), ("F", 9), ("G", 8), ("H", 6), ("Paura o avidità", 5), ("Tono delle notizie, 3 giorni", 3), ("Numero di notizie", 1));
|
|
Assert.HasCount(10, many.Weights);
|
|
Assert.AreEqual(100, many.Weights.Sum(w => w.Share));
|
|
Assert.AreEqual(new LearningWeight("Tutto il resto", 4, true), many.Weights[^1]);
|
|
Assert.AreEqual("Le notizie contano, ma meno dei prezzi: insieme a paura e avidità pesano 9 su 100.", many.WeightsText);
|
|
Assert.AreEqual("Le notizie per ora non pesano; paura e avidità pesano 40 su 100.", Of(("A", 60), ("Paura o avidità", 40)).WeightsText);
|
|
Assert.AreEqual("Le notizie contano, più dei prezzi: insieme a paura e avidità pesano 60 su 100.", Of(("Notizia più grave", 60), ("A", 40)).WeightsText);
|
|
StringAssert.StartsWith(Of(("A", 100)).WeightsText, "Notizie, paura e avidità per ora non pesano");
|
|
StringAssert.StartsWith(Of(("A", 0)).WeightsText, "Su casi mai visti nessuna informazione");
|
|
Assert.HasCount(0, Of(("A", 0)).Weights);
|
|
}
|
|
|
|
/// <summary>The trial before and after the first threshold; the gain without the filter is said once when it is the same.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheTrialSaysWhereItIs()
|
|
{
|
|
var (champion, challenger) = (Row(ModelStatuses.Champion, 1), Row(ModelStatuses.Challenger, 2, 520, gainWithout: 6));
|
|
List<SeenEstimate> Pairs(int count, bool better) =>
|
|
[
|
|
.. Enumerable.Range(0, count).SelectMany(i =>
|
|
{
|
|
var one = Seen(champion.Id, 1 + (i % 20), i % 2 == 0, 0.5);
|
|
return new[] { one, new SeenEstimate(challenger.Id, false, one.Estimate with { Probability = (i % 2 == 0) == better ? 0.7 : 0.3 }) };
|
|
}),
|
|
];
|
|
StringAssert.StartsWith(View(new CycleState(), models: [champion, challenger]).TrialText, "Non ha ancora casi di confronto: ne servono 100.");
|
|
var few = View(new CycleState(), estimates: Pairs(14, true), models: [champion, challenger]);
|
|
Assert.AreEqual((14, 100), (few.Pairs, few.PairsNeeded));
|
|
StringAssert.StartsWith(few.TrialText, "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100");
|
|
StringAssert.StartsWith(View(new CycleState(), estimates: Pairs(1, false), models: [champion, challenger]).TrialText, "Per ora non sembra meglio, e ha solo un caso di confronto su 100");
|
|
var more = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger]);
|
|
Assert.AreEqual((130, 100), (more.Pairs, more.PairsNeeded), "passed, and not judged yet");
|
|
StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide domenica 11 ottobre alle 03:00: prende il posto della 1 se");
|
|
var judged = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger with { ThresholdDone = 100 }]);
|
|
Assert.AreEqual((130, 150), (judged.Pairs, judged.PairsNeeded));
|
|
StringAssert.StartsWith(judged.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide di nuovo a 150 casi:");
|
|
Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger with { ThresholdDone = 250 }]).PairsNeeded);
|
|
Assert.AreEqual((5.84m, 6m), (more.Champion!.GainWithout, more.Challenger!.GainWithout));
|
|
Assert.AreEqual((56, 0.241m, 7.9m, "4 ottobre"), (more.Champion.Precision, more.Champion.Error, more.Champion.Gain, more.Champion.Trained));
|
|
Assert.AreEqual("Nessuno sfidante in prova.", View(new CycleState(), models: champion).TrialTitle);
|
|
Assert.AreEqual(1, View(new CycleState(), models: [champion with { Status = ModelStatuses.Retired }, Row(ModelStatuses.Champion, 2, replaced: champion.Id)]).UndoTo);
|
|
Assert.IsNull(View(new CycleState(), models: [champion with { Status = ModelStatuses.Undone }, Row(ModelStatuses.Champion, 2, replaced: champion.Id)]).UndoTo);
|
|
}
|
|
|
|
/// <summary>The next night is the coming Sunday at 03:00 in Rome, across the change of hour and the year.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheNextCheckIsTheComingSunday()
|
|
{
|
|
string Next(DateTimeOffset at, params ModelRow[] models) => LearningView.Of(new LearningSnapshot([], [], models, new CycleState()), Rates, Capitals, false, new DiscoverySet(), [], at).Summary.NextCheck;
|
|
var champion = Row(ModelStatuses.Champion, 1);
|
|
Assert.AreEqual("domenica 11 ottobre, 03:00", Next(Now, champion));
|
|
Assert.AreEqual("domenica 11 ottobre, 03:00", Next(new DateTimeOffset(2026, 10, 11, 0, 59, 0, TimeSpan.Zero), champion), "02:59 in Rome");
|
|
Assert.AreEqual("domenica 18 ottobre, 03:00", Next(new DateTimeOffset(2026, 10, 11, 1, 1, 0, TimeSpan.Zero), champion));
|
|
Assert.AreEqual("domenica 3 gennaio, 03:00", Next(new DateTimeOffset(2026, 12, 30, 9, 0, 0, TimeSpan.Zero), champion));
|
|
Assert.AreEqual("sabato 10 ottobre, 03:00", Next(Now), "before the first model any night will do");
|
|
}
|
|
}
|