From f69943f70aeb6231e0879c9508f98be5bf64d31d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 12:44:37 +0100 Subject: [PATCH] Show what the model knows on its own screen and let the user set it aside The Apprendimento screen says in plain words whether the model counts, how well its probabilities hold, which clues it weighs, how the challenger is doing and what it has learned. Thresholds, set-aside and the undo of a promotion live in Impostazioni; anything that shrinks less with real money asks for the phrase. The new tests also caught a wrong column name that broke the Panoramica as soon as the first model existed. refs #66 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/adr/0018-scelte-fase-8.md | 9 + src/Anubis.Server/Assets/app.css | 93 +++ .../Components/CalibrationChart.razor | 86 +++ src/Anubis.Server/Components/Icon.razor | 3 + .../Components/Pages/Apprendimento.razor | 303 +++++++++- .../Components/Pages/Impostazioni.razor | 69 ++- .../Components/Pages/Panoramica.razor | 18 +- .../Components/WeeklyPrecision.razor | 61 ++ src/Anubis.Server/Endpoints.cs | 6 + src/Anubis.Server/Forms.cs | 62 ++ src/Anubis.Server/LearningView.cs | 545 ++++++++++++++++++ src/Anubis.Server/PanoramaView.cs | 10 +- src/Anubis.Server/ReasonTexts.cs | 2 +- src/Anubis/Demo/Data/aggregates.json | 35 +- src/Anubis/Demo/DemoMode.cs | 18 +- src/Anubis/Learning/LearningSettings.cs | 9 + src/Anubis/Learning/ModelStore.cs | 11 + tests/Anubis.Tests/LearningCycleTests.cs | 2 +- tests/Anubis.Tests/LearningScreenTests.cs | 359 ++++++++++++ tests/Anubis.Tests/OverviewScreenTests.cs | 2 +- tools/Anubis.Tasks/Program.cs | 2 +- 22 files changed, 1680 insertions(+), 27 deletions(-) create mode 100644 src/Anubis.Server/Components/CalibrationChart.razor create mode 100644 src/Anubis.Server/Components/WeeklyPrecision.razor create mode 100644 src/Anubis.Server/LearningView.cs create mode 100644 tests/Anubis.Tests/LearningScreenTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index 4e5be10..fad0d07 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 ` (Windows) o `sh ./tasks.sh - `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker. - `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository. - `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso. -- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. +- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie, Apprendimento e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. - `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea. - `desktop-win` (Fase 10): non ancora disponibile. - `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose. diff --git a/docs/adr/0018-scelte-fase-8.md b/docs/adr/0018-scelte-fase-8.md index 1f5b25c..ccb3269 100644 --- a/docs/adr/0018-scelte-fase-8.md +++ b/docs/adr/0018-scelte-fase-8.md @@ -72,3 +72,12 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d **13. Impatto delle notizie.** Per tipo di evento (parole chiave dei casi gravi, poi il tipo detto dal modello linguistico), il rendimento medio a 1 e a 5 chiusure dalla prima chiusura dopo la pubblicazione, sugli strumenti collegati. Solo informativa. **14. Scoperte.** Le domande sono fisse nel codice (agitazione dei prezzi, fase del mercato, ampiezza, volumi, notizie molto negative, paura e avidità estreme, VIX, giorno della settimana), per strategia: il bot non ne cerca altre. L’errore conta come un caso solo ciò che è deciso nello stesso mese. Sotto i 100 casi basta che la differenza superi 1,96 errori e il giudizio dice da solo quanto vale; da 100 in su la soglia si alza con il numero di domande fatte. “Non conta” si dice solo con almeno 100 casi. + +**15. Schermata Apprendimento** (mockup 06). +- I numeri del confronto tra modello in carica e sfidante sono quelli della verifica fatta all’addestramento, sui casi che il modello non aveva studiato. La precisione della Panoramica è la stessa. +- Il grafico delle probabilità mostra i segnali dal vivo appena una fascia ne ha almeno 20; fino ad allora mostra la verifica sui casi storici e lo dice. Una fascia sotto i 20 casi è dichiarata inaffidabile una per una. +- I grafici sono SVG e CSS fatti in casa, con le stesse cifre in una tabella (13.4); niente JavaScript. +- Il sottotitolo del mockup sta sotto la testata, come in Notizie: la riga con data e ora della testata è comune a tutte le schermate. +- L’operazione MSFT dei dati dimostrativi mostra la stima (61%, contro il 48% abituale): l’appendice F.7 non dà la frequenza di base, il 48% è quello della scoperta sui rimbalzi. + +**16. Impostazioni del modello.** Soglie e messa da parte si cambiano solo dalla pagina Impostazioni, non dall’API generica. Rimpicciolire meno, o mettere da parte il modello, aumenta l’esposizione: con una strategia su soldi veri servono la frase e la password di 12.4. Rimpicciolire di più, o rimetterlo al suo posto, è libero. diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 200b139..d0a4a01 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -681,7 +681,90 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .source-list li > span:first-child { display: inline-flex; } .source-list .muted { text-align: right; } +/* ---- Apprendimento (mockup 06) ---- */ +.learning-head { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); } +.learning-state { display: flex; flex-direction: column; align-items: flex-start; gap: 14px; } +.learning-state h2 { font-size: 26px; line-height: 34px; letter-spacing: -0.015em; } +.learning-text { color: var(--text-2); font-size: 15px; line-height: 23px; max-width: 62ch; } +.learning-progress { width: 100%; max-width: 560px; } +.learning-progress .usage { height: 8px; border-radius: 4px; } +.state-badge { display: inline-flex; align-items: center; gap: 8px; padding: 4px 12px; border-radius: 999px; background: var(--surface-2); color: var(--text); font-weight: 600; font-size: 13.5px; } +.state-badge.on { background: var(--gain-bg); color: var(--gain); } +.state-badge.warn { background: var(--attention-bg); color: var(--attention); } +.learning-facts { margin: 0; display: flex; flex-direction: column; justify-content: center; } +.learning-facts > div { padding: 14px 0; border-bottom: 1px solid var(--rule); } +.learning-facts > div:last-child { border-bottom: 0; } +.learning-facts dt { color: var(--text-3); font-size: 13.5px; } +.learning-facts dd { margin: 0; } +.learning-facts dd strong { font-size: 16px; line-height: 24px; font-weight: 650; } +.learning-facts .learning-precision { font-size: 30px; line-height: 38px; font-weight: 650; letter-spacing: -0.02em; } +.learning-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: stretch; } +.learning-row-wide { grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); } +.learning-row .panel { padding: 24px 26px; display: flex; flex-direction: column; min-width: 0; } +.learning-row .panel > h2 { margin-bottom: 4px; } +.learning-open { align-items: start; gap: 28px; } +.calibration { display: flex; flex-direction: column; margin-top: 12px; flex: 1; } +.calibration-title, .calibration-foot { color: var(--text-2); font-size: 14px; } +.calibration-foot { text-align: center; margin-right: 20%; } +.calibration-box { position: relative; display: grid; grid-template-columns: 56px minmax(0, 1fr); height: 250px; margin: 14px 20% 0 0; } +.calibration .chart-axis { display: block; } +.calibration .base { stroke: var(--control); stroke-width: 1; } +.calibration-x { position: relative; height: 30px; margin: 8px 20% 0 56px; color: var(--text-3); font-size: 13px; } +.calibration-x span { position: absolute; transform: translateX(-50%); } +.calibration .legend { margin-top: 20px; } +.calibration-text { color: var(--text-2); margin-top: 12px; } +.point-label { position: absolute; white-space: nowrap; font-size: 13.5px; font-weight: 650; pointer-events: none; } +.point-label.below { transform: translate(12px, 8px); } +.point-label.above { transform: translate(-100%, -24px); margin-left: -8px; } +.point-label.under { transform: translate(-50%, 10px); } +.hover-dot:hover { z-index: 2; } +.hover-dot.quiet { opacity: 0; } +.hover-dot.quiet:hover { opacity: 1; } +.hover-box { display: none; position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%); padding: 6px 10px; border-radius: 8px; background: var(--text); color: var(--surface); font-size: 13px; line-height: 18px; white-space: nowrap; font-weight: 500; } +.hover-dot:hover .hover-box { display: block; } +.weights { list-style: none; margin: 12px 0 0; padding: 0; } +.weights li { display: grid; grid-template-columns: minmax(0, 215px) minmax(0, 1fr) 30px; gap: 16px; align-items: center; min-height: 31px; } +.weights strong { text-align: right; font-variant-numeric: tabular-nums; font-weight: 650; } +.weight-bar span { display: block; height: 11px; border-radius: 0 4px 4px 0; background: var(--text-2); min-width: 2px; } +.weights .rest > span:first-child { color: var(--text-3); } +.weights .rest .weight-bar span { background: var(--bench); } +.weights-text { margin-top: auto; padding-top: 18px; } +.versions { margin-top: 8px; } +.versions thead td { border-bottom: 1px solid var(--rule); } +.versions thead th { color: var(--text); font-weight: 650; font-size: 13.5px; border-bottom-color: var(--rule); } +.versions th[scope="row"] { font-weight: 400; text-align: left; font-size: 13.5px; color: var(--text-2); } +@media (min-width: 761px) { .versions thead th { white-space: nowrap; } } +.learning-row .aside { margin-top: 16px; } +.learning-row .aside strong { color: var(--text); } +.learning-row .panel > .chart-table, .learning-row .panel > form { margin-top: 14px; } +.learning-watch .panel-head { margin-bottom: 8px; } +.learning-watch .aside { margin-top: auto; } +.status-pill.gain { color: var(--gain); } +.watch-list { list-style: none; margin: 0 0 14px; padding: 0; } +.watch-list li { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid var(--rule-inner); color: var(--text-2); } +.watch-list .icon { margin-top: 2px; color: var(--text-3); } +.watch-list .ok .icon { color: var(--gain); } +.watch-list .warn, .watch-list .warn .icon { color: var(--attention); } +.weekly { margin: 0 0 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); } +.weekly-box { display: grid; grid-template-columns: minmax(0, 1fr) 76px; height: 84px; margin: 12px 0 4px 6px; } +.weekly svg .bench { fill: none; stroke: var(--bench); stroke-width: 1; } +.weekly svg .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; } +.weekly .end-dot { width: 12px; height: 12px; margin: -6px 0 0 -6px; } +.weekly-side { position: relative; font-size: 13px; } +.weekly-side strong, .weekly-side span { position: absolute; left: 14px; line-height: 15px; white-space: nowrap; } +.weekly-side strong { transform: translateY(-60%); font-weight: 650; } +.weekly-side span { color: var(--text-3); transform: translateY(-20%); font-size: 12.5px; } +.weekly-x { display: flex; justify-content: space-between; margin: 10px 76px 0 6px; } +.found { list-style: none; margin: 0; padding: 0; } +.found li { display: flex; flex-direction: column; gap: 5px; padding: 14px 0; border-bottom: 1px solid var(--rule); } +.found li:last-child { border-bottom: 0; } +.found strong { font-weight: 650; } +.found-detail { color: var(--text-2); } +.found .attention { font-size: 13px; } +.learning-open .plain h3 { margin: 18px 0 4px; } + @media (max-width: 1180px) { + .learning-row, .learning-row-wide { grid-template-columns: minmax(0, 1fr); } .overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .overview-row-wide, .journal-columns, .news-columns { grid-template-columns: minmax(0, 1fr); } } @@ -787,4 +870,14 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .news-panel > .panel-head .segmented { display: flex; width: 100%; } .news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; } .news-columns, .news-side { gap: 14px; } + .learning-head { grid-template-columns: minmax(0, 1fr); } + .learning-state h2 { font-size: 22px; line-height: 28px; } + .learning-row { gap: 14px; } + .learning-row .panel { padding: 18px; } + .calibration-box { margin-right: 0; grid-template-columns: 42px minmax(0, 1fr); } + .calibration-x { margin-right: 0; margin-left: 42px; } + .calibration-foot { margin-right: 0; } + .calibration .legend { flex-direction: row; } + .weights li { grid-template-columns: minmax(0, 150px) minmax(0, 1fr) 26px; gap: 10px; } + .chart-table summary { min-height: 44px; display: flex; align-items: center; } } diff --git a/src/Anubis.Server/Components/CalibrationChart.razor b/src/Anubis.Server/Components/CalibrationChart.razor new file mode 100644 index 0000000..0a4a5df --- /dev/null +++ b/src/Anubis.Server/Components/CalibrationChart.razor @@ -0,0 +1,86 @@ +@* How often it went well against what the model said (SPEC 13.4, mockup 06): one scale, 2 px lines, faint grid, the + perfect estimate beside it, direct labels on the fullest band and on the last one, a box on hover and the table. + As in EquityChart the lines are SVG stretched to the box; texts and points are HTML placed in percent. *@ +@if (Bands.Count > 0) +{ + var loX = Bands.Min(b => b.From) / 10 * 10; + var hiX = (Bands.Max(b => b.To) + 9) / 10 * 10; + var loY = Math.Min(loX, (int)Math.Floor(Bands.Min(b => b.Observed)) / 10 * 10) - 5m; + var hiY = Math.Max(hiX, Bands.Max(b => b.Observed)) + 4m; + var step = hiX - loX > 60 ? 20 : 10; + var fullest = Bands.MaxBy(b => b.Cases)!; + var last = Bands[^1]; + decimal X(decimal v) => (v - loX) / (hiX - loX) * 1000m; + decimal Y(decimal v) => (hiY - v) / (hiY - loY) * 1000m; +
+ +
+ +
+ + @foreach (var b in Bands) + { + Tra @(b.From)% e @(b.To)%
@Format.Number(b.Observed)% su @b.Cases casi
+ } + @Label(fullest) + @if (last != fullest) + { + @Label(last) + } +
+
+ + +
+ Il modello + Stima perfetta +
+

@Text

+
+ Vedi i numeri in una tabella +
+ + + + @foreach (var b in Bands) + { + + } + +
Quando il modello diceCasiÈ andata beneAffidabilità
tra @(b.From)% e @(b.To)%@b.Cases@Format.Number(b.Observed)%@(b.Solid ? "conta" : "troppo pochi casi per contarci")
+
+
+
+} + +@code { + [Parameter, EditorRequired] + public IReadOnlyList Bands { get; set; } = []; + + [Parameter] + public string Text { get; set; } = ""; + + private static string Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {(b.Cases == 1 ? "un caso" : b.Cases + " casi")}"; + + private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture); + + private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%"; +} diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor index 5267197..c721f51 100644 --- a/src/Anubis.Server/Components/Icon.razor +++ b/src/Anubis.Server/Components/Icon.razor @@ -89,6 +89,9 @@ case "tick": break; + case "eye": + + break; case "logout": break; diff --git a/src/Anubis.Server/Components/Pages/Apprendimento.razor b/src/Anubis.Server/Components/Pages/Apprendimento.razor index 7dd9820..0db2a83 100644 --- a/src/Anubis.Server/Components/Pages/Apprendimento.razor +++ b/src/Anubis.Server/Components/Pages/Apprendimento.razor @@ -1,5 +1,306 @@ +@inherits LoadedComponent @page "/apprendimento" +@inject AnubisHost Host +@inject ShellData Shell +@using Anubis.Learning Apprendimento · Anubis -Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti. +@{ + var v = _view; + var s = v.Summary; + var c = _currency; +} +

Il modello impara dall'esito di ogni segnale.

+@if (Ok == "promozione") +{ +

Promozione annullata: è tornata in carica la versione precedente.

+} +else if (Errore is not null) +{ +

@(Errore == "motore" ? "Nella modalità dimostrativa non si cambia nulla." : "Non c'è nessuna promozione da annullare.")

+} + +
+
+ @Badge(s.State) +

@v.Title

+

@v.Text

+ @if (s.State != LearningStates.None) + { +
+ @if (s.Signals < s.Needed) + { +
Segnali già valutati@s.Signals su @s.Needed necessari
+ } + else + { +
Segnali già valutati@Format.Number(s.Signals) (ne servivano @s.Needed)
+ } + + @if (v.Pace is { } pace) + { + @pace + } +
+ } + @if (v.Missing.Count > 0) + { +
    + @foreach (var m in v.Missing) + { +
  • @m
  • + } +
+ } + @if (s.State == LearningStates.Manual) + { +

Vai a Impostazioni

+ } +
+
+
+
Previsioni azzeccate su casi mai visti
+
@(s.Precision is { } precision ? precision + "%" : "—")
+
@(s.Precision is null ? "Si misura al primo addestramento" : "Tirando a caso sarebbe il 50%")
+
+
Ultimo addestramento
@Capital(v.LastTraining)
+
@s.NextLabel
@Capital(s.NextCheck)
+
+
+ +
+
+

Ci si può fidare delle sue probabilità?

+ @if (v.Bands.Count == 0) + { +

@v.BandsText Qui vedrai quante volte va bene davvero quando il modello dice che una cosa è probabile.

+ } + else + { +

Più i punti stanno sulla linea, più la stima corrisponde ai fatti.@(v.BandsFromHistory ? " Per ora sono i casi storici che non aveva studiato: quelli dal vivo sono ancora troppo pochi." : "")

+ + } +
+
+

Cosa guarda di più

+ @if (v.Champion is null) + { +

Si vedrà con il primo modello.

+ } + else + { +

Quanto pesa ogni informazione nelle sue stime, su 100.

+ @if (v.Weights.Count > 0) + { + var most = v.Weights.Max(w => w.Share); +
    + @foreach (var w in v.Weights) + { +
  • @w.Name@w.Share
  • + } +
+ } +

@v.WeightsText

+ } +
+
+ +
+
+

Il modello in carica e lo sfidante

+

Lo sfidante gira in ombra accanto al modello in carica. Ne prende il posto solo se è chiaramente migliore.

+ @if (v.Champion is { } now) + { + var other = v.Challenger; + var same = other is null || other.GainWithout == now.GainWithout; +
+ + @if (other is not null){} + + @if (other is not null){} + @if (other is not null){} + @if (other is not null){} + @if (other is not null){} + + @if (other is not null){} + @if (other is not null) + { + + } + +
In carica, versione @now.VersionSfidante, versione @other.Version
Addestrato@now.Trained@other.Trained
Casi studiati@Format.Number(now.Examples)@Format.Number(other.Examples)
Previsioni azzeccate su casi mai visti@Share(now.Precision)@Share(other.Precision)
Errore sulle probabilità (più basso è meglio)@Error(now.Error)@Error(other.Error)
Guadagno medio per operazione se filtrasse lui @if (same && now.GainWithout is { } without){(senza filtro: @Shell.Money(without, c, withSign: true))}@Gain(now, same, c)@Gain(other, same, c)
Casi di confronto direttonon serve@v.Pairs su @v.PairsNeeded
+
+ } +

@v.TrialTitle @v.TrialText

+ @if (v.Choice is { } choice) + { +
+ Come è stato scelto il modello in carica +

@choice Sono tutte prove su casi che il modello non aveva studiato; contano anche quelle scartate.

+
+ + + + @foreach (var a in v.Attempts) + { + + } + +
Tipo di modelloPrevisioni azzeccateErroreGuadagno per operazioneEsito
@a.Learner@Share(a.Precision)@Error(a.Error)@Shell.Money(a.Gain, c, withSign: true)@(a.Chosen ? "scelto" : "non scelto")
+
+
+ } + @if (v.UndoTo is { } back && !Shell.IsDemo) + { +
+ + + Tornerebbe in carica la versione @back. + + } +
+
+
+

Sorveglianza

+ @if (v.Checked) + { + @(v.Anomaly ? "Anomalia" : "Nessuna anomalia") + } +
+ @if (!v.Checked) + { +

Il controllo gira ogni notte alle 03:00: confronta le stime con gli esiti e il mercato di oggi con quello su cui ha studiato.

+ } + else + { +
    + @foreach (var check in v.Checks) + { +
  • "tick", "warn" => "alert", _ => "clock" })" Size="16" />@check.Text
  • + } +
+ + } +

Se la precisione cala, il modello viene messo da parte da solo e le strategie proseguono senza di lui.

+
+
+ +
+
+

Cosa ha imparato finora

+ @if (v.Found.Count == 0) + { +

Ancora niente: le relazioni tra indizi ed esiti si cercano ogni notte, quando i casi bastano per un confronto.

+ } + else + { +
    + @foreach (var d in v.Found) + { +
  • + @d.Title + @d.Detail + @if (d.Cases < 20){}@(d.Cases == 1 ? "Un caso" : Format.Number(d.Cases) + " casi"): @d.Trust +
  • + } +
+ } + @if (v.News.Count > 0) + { +

Cosa succede ai prezzi dopo una notizia

+

Rendimento medio dalla prima chiusura dopo la notizia. È solo un'informazione: non cambia nessuna regola.

+
+ + + + @foreach (var n in v.News) + { + + } + +
Tipo di notiziaDopo 1 giornoDopo 5 giorniCasi
@NewsEventNames.Label(n.Kind)@Move(n.OneDay)@Move(n.FiveDays)@n.Cases: @n.Trust
+
+ } +
+
+

Storia

+ @if (v.Story.Count == 0) + { +

La storia comincia con il primo modello.

+ } + else + { +
+ @foreach (var e in v.Story.Take(LearningView.StoryRows)) + { +
@e.When
@e.Text
+ } +
+ @if (v.Story.Count > LearningView.StoryRows) + { +
+ Mostra i @(v.Story.Count - LearningView.StoryRows) eventi precedenti +
+ @foreach (var e in v.Story.Skip(LearningView.StoryRows)) + { +
@e.When
@e.Text
+ } +
+
+ } + } +
+
+ +@code { + private LearningView _view = null!; + private string _currency = "EUR"; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "ok")] + public string? Ok { get; set; } + + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + _currency = Shell.Effective((await Host.Services!.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); + _view = await LearningView.LoadAsync(Host, Shell, ct); + } + + private string Gain(LearningVersion version, bool same, string currency) => version.Gain is not { } gain ? "—" + : Shell.Money(gain, currency, withSign: true) + (same || version.GainWithout is not { } without ? "" : $" (senza: {Shell.Money(without, currency, withSign: true)})"); + + private static string Badge(string state) => state switch + { + LearningStates.None => "Non ancora partito", + LearningStates.Active => "Attivo", + LearningStates.Aside => "Messo da parte", + LearningStates.Manual => "Messo da parte da te", + _ => "In osservazione", + }; + + private static string BadgeIcon(string state) => state switch + { + LearningStates.None => "clock", + LearningStates.Active => "check", + LearningStates.Aside => "alert", + LearningStates.Manual => "pause", + _ => "eye", + }; + + private static string Share(int? points) => points is { } p ? p + "%" : "—"; + + private static string Error(decimal? value) => value is { } e ? Format.Number(e, 3) : "—"; + + private static string Move(double value) => Format.Percent((decimal)Math.Round(value * 100, 2), 2, withSign: true); + + private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..]; + + private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture); +} diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index dbdbabd..8b932a8 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -31,6 +31,8 @@ "fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.", "chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.", "chiave-tolta" => "Chiave tolta.", + "apprendimento" => "Impostazioni del modello salvate: valgono dalla prossima decisione.", + "promozione" => "Promozione annullata: è tornata in carica la versione precedente.", _ => "Fatto.", })

@@ -41,7 +43,7 @@ }
@@ -405,6 +407,55 @@
+
+

Modello

+

Il modello non compra mai e non ingrandisce niente: quando avrà superato le sue prove potrà solo rimpicciolire, o non fare, un acquisto che giudica debole. Quanto debole lo decidi qui, in punti di probabilità sotto la frequenza con cui la strategia guadagna di solito. Cosa sta facendo

+
+ + @foreach (var m in _model) + { + var definition = SettingsStore.Definition(m.Key); + + } + @if (!Shell.IsDemo) + { + @if (_anyLive) + { +

Una strategia usa soldi veri: per rimpicciolire meno, o mettere da parte il modello, servono la frase e la password.

+ + + + } + + } + +

Ultima promozione

+ @if (_undoTo is { } undo) + { +
+ + + + Tornerebbe in carica la versione @undo. + + } + else + { +

Nessuna promozione da annullare.

+ } +
+

Sicurezza

@if (Shell.IsDemo) @@ -536,6 +587,8 @@ private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private readonly List _newsRules = []; + private readonly List _model = []; + private int? _undoTo; private readonly Dictionary _llm = []; private IReadOnlyList _newsSources = []; private readonly Dictionary _dataKeys = []; @@ -573,6 +626,12 @@ _newsRules.Add(await services.Settings.GetAsync(rule.Key, ct)); } + foreach (var setting in Anubis.Learning.LearningSettings.All) + { + _model.Add(await services.Settings.GetAsync(setting.Key, ct)); + } + + _undoTo = Shell.IsDemo ? null : await new Anubis.Learning.ModelStore(services.Db).UndoToAsync(ct); foreach (var setting in Anubis.News.NewsModelSettings.All) { _llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct); @@ -656,6 +715,7 @@ "fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.", "chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.", "chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.", + "promozione" => "Non c'è nessuna promozione da annullare.", "tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.", "modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.", @@ -705,6 +765,13 @@ ; } + private static string ModelLabel(string key) => key == Anubis.Learning.LearningSettings.Full.Key ? "Acquisto intero fino a" + : key == Anubis.Learning.LearningSettings.Zero.Key ? "Nessun acquisto da" : "Il modello"; + + private static string ModelChoice(string key, string choice) => key == Anubis.Learning.LearningSettings.Aside.Key + ? choice == "on" ? "Messo da parte: non conta" : "Al suo posto" + : choice == "0" ? "Solo alla frequenza di sempre o sopra" : choice + " punti sotto"; + private static string ProviderName(string provider) => provider switch { Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)", diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 93cc807..6d4538b 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -364,19 +364,23 @@

Apprendimento

Dettaglio
- @if (p.Learning is not { } m) + @{ var m = p.Learning; } +

@m.Sentence

+ @if (m.State == LearningStates.Observation) { -

L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.

- } - else - { -

Il modello osserva e impara, ma non decide ancora.

Segnali già valutati@m.Signals su @m.Needed necessari
+ } + @if (m.State == LearningStates.None) + { +

@m.NextLabel: @m.NextCheck.

+ } + else + {
-
Previsioni azzeccate
@m.Precision% su dati mai visti
+
Previsioni azzeccate
@(m.Precision is { } hit ? $"{hit}% su dati mai visti" : "non ancora misurate")
Ultimo addestramento
@m.Trained
Prossima verifica
@m.NextCheck
diff --git a/src/Anubis.Server/Components/WeeklyPrecision.razor b/src/Anubis.Server/Components/WeeklyPrecision.razor new file mode 100644 index 0000000..59f313b --- /dev/null +++ b/src/Anubis.Server/Components/WeeklyPrecision.razor @@ -0,0 +1,61 @@ +@* The precision of the model week by week with the alarm line (SPEC 13.6, mockup 06). Weeks without enough cases leave no + point; the days on the axis keep the distance between the others. *@ +@if (Weeks.Count >= 2) +{ + var alarm = (decimal)(Anubis.Learning.Health.Alarm * 100); + var lo = Math.Min(Weeks.Min(w => w.Precision), alarm) - 4m; + var hi = Math.Max(Weeks.Max(w => w.Precision), alarm) + 4m; + var (first, last) = (Weeks[0], Weeks[^1]); + var lowest = Weeks.MinBy(w => w.Precision)!; + decimal X(LearningWeek w) => (w.Monday.DayNumber - first.Monday.DayNumber) * 1000m / (last.Monday.DayNumber - first.Monday.DayNumber); + decimal Y(decimal v) => (hi - v) / (hi - lo) * 1000m; +
+
Precisione settimana per settimana
+
+
+ + @foreach (var w in Weeks) + { + Settimana del @Day(w.Monday)
@w.Precision%
+ } + @if (lowest != last) + { + @lowest.Precision% + } +
+ +
+ +
+ Vedi i numeri in una tabella +
+ + + + @foreach (var w in Weeks.Reverse()) + { + + } + +
Settimana dal lunedìPrecisione
@Format.LongDate(w.Monday)@w.Precision%
+
+
+
+} + +@code { + [Parameter, EditorRequired] + public IReadOnlyList Weeks { get; set; } = []; + + private static string Day(DateOnly day) => day.ToString("d MMM", CultureInfo.GetCultureInfo("it-IT")); + + private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture); + + private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%"; +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 7ecb803..1aef93a 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -140,6 +140,12 @@ internal static partial class Endpoints return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri."); } + // The same for what lets the model shrink less. + if (Anubis.Learning.LearningSettings.All.Any(d => d.Key == key)) + { + return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri."); + } + return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false); }); diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 808001b..af8c6bc 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -42,6 +42,8 @@ internal static partial class Forms signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync); signed.MapPost("/laboratorio", PlanTrialAsync); signed.MapPost("/stime-di-costo/{id:guid}/{choice}", DecideCostAsync); + signed.MapPost("/modello", SetModelAsync); + signed.MapPost("/modello/annulla-promozione", UndoPromotionAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); signed.MapPost("/rischio/{key}", SetRiskSettingAsync); @@ -783,6 +785,66 @@ internal static partial class Forms return Results.Redirect(done ? "/laboratorio#stime" : "/laboratorio?errore=stima#stime"); } + /// + /// The thresholds of the multiplier and the manual set-aside (SPEC 13.5), all at once. A choice that lets operations be + /// bigger while a strategy has real money needs the phrase and the password, like a risk limit (SPEC 12.4). + /// + private static async Task SetModelAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (host.IsDemo || host.Services is not { } services) + { + return Results.Redirect(back + "?errore=motore#modello"); + } + + var current = new Dictionary(StringComparer.Ordinal); + var next = new Dictionary(StringComparer.Ordinal); + foreach (var definition in Anubis.Learning.LearningSettings.All) + { + var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false); + current[definition.Key] = value.Value; + var chosen = form[definition.Key].ToString(); + if (value.ReadOnly || chosen.Length == 0) + { + next[definition.Key] = value.Value; + continue; + } + + if (!definition.Allowed!.Contains(chosen, StringComparer.Ordinal)) + { + return Results.Redirect(back + "?errore=impostazione#modello"); + } + + next[definition.Key] = chosen; + } + + if (Anubis.Learning.LearningSettings.Raised(k => current[k], k => next[k]) && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal) + { + return Results.Redirect(back + "?errore=" + refusal + "#modello"); + } + + var by = context.User.Identity?.Name ?? "utente"; + foreach (var (key, value) in next.Where(n => n.Value != current[n.Key])) + { + await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false); + } + + return Results.Redirect(back + "?ok=apprendimento#modello"); + } + + /// One click takes back the last promotion (SPEC 11.4). + private static async Task UndoPromotionAsync(IFormCollection form, AnubisHost host, CancellationToken ct) + { + var (page, anchor) = Back(form, "/apprendimento") == "/impostazioni" ? ("/impostazioni", "#modello") : ("/apprendimento", ""); + if (host.IsDemo || host.Services is not { } services) + { + return Results.Redirect(page + "?errore=motore" + anchor); + } + + var done = await Anubis.Learning.LearningCycle.UndoPromotionAsync(services.Db, host.Clock, ct).ConfigureAwait(false); + return Results.Redirect(page + (done ? "?ok=promozione" : "?errore=promozione") + anchor); + } + private static DateOnly? ParseDay(string text) => DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null; diff --git a/src/Anubis.Server/LearningView.cs b/src/Anubis.Server/LearningView.cs new file mode 100644 index 0000000..54e0400 --- /dev/null +++ b/src/Anubis.Server/LearningView.cs @@ -0,0 +1,545 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Learning; + +namespace Anubis.Server; + +/// What the model is doing, for the badge and the sentences at the top. +internal static class LearningStates +{ + /// No model yet: the night after the first start prepares it. + public const string None = "none"; + + public const string Observation = "observation"; + public const string Active = "active"; + + /// Set aside on its own by the nightly check. + public const string Aside = "aside"; + + /// Set aside by the user. + public const string Manual = "manual"; +} + +/// A band of estimates: percentages as they are read, the point at the mean estimate. +public sealed record LearningBand(int From, int To, int Cases, decimal Estimated, decimal Observed) +{ + public bool Solid => Cases >= Judge.BandMin; +} + +internal sealed record LearningWeight(string Name, int Share, bool Rest); + +/// A column of the comparison between the model in charge and the one on trial. +internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout); + +/// What was tried when a model was trained, the chosen one included. +internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen); + +public sealed record LearningWeek(DateOnly Monday, int Precision); + +/// A line of "Sorveglianza": is ok, warn or wait. +internal sealed record LearningCheck(string State, string Text); + +internal sealed record LearningStory(string When, string Text); + +/// The model box of the Panoramica: the same state in few words. +internal sealed record LearningSummary(string State, int Signals, int Needed, int? Precision, string Trained, string NextLabel, string NextCheck) +{ + public string Sentence => State switch + { + LearningStates.None => "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.", + LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.", + LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.", + LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.", + _ => "Il modello osserva e impara, ma non decide ancora.", + }; +} + +/// +/// The Apprendimento screen (SPEC 13.6, mockup 06): what the model is doing, whether its probabilities can be trusted, +/// what it looks at, the model in charge against the challenger, the watch, the discoveries and the history. In demo mode +/// the numbers of appendix F.7 come from the aggregates. +/// +internal sealed record LearningView +{ + /// The clues named one by one; the others are "Tutto il resto". + public const int NamedWeights = 9; + + public const int StoryRows = 12; + + private const string Fear = "Paura o avidità"; + + /// The pace is measured on the last four weeks, and needs at least one. + private const int PaceDays = 28; + + private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT"); + + private static readonly string[] _numbers = ["zero", "una", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici"]; + + public required LearningSummary Summary { get; init; } + + public required string Title { get; init; } + + public required string Text { get; init; } + + public string? Pace { get; init; } + + /// With 300 signals done, what still stops it from counting. + public IReadOnlyList Missing { get; init; } = []; + + /// "domenica 4 ottobre, versione 3". + public required string LastTraining { get; init; } + + public IReadOnlyList Bands { get; init; } = []; + + /// The sentence under the calibration chart. + public string BandsText { get; init; } = ""; + + /// True when the bands are those of the verification on the history, because the live ones are still too few. + public bool BandsFromHistory { get; init; } + + public IReadOnlyList Weights { get; init; } = []; + + public string WeightsText { get; init; } = ""; + + public LearningVersion? Champion { get; init; } + + public LearningVersion? Challenger { get; init; } + + /// The signals both estimated, with their outcome, and how many the next decision needs. + public int Pairs { get; init; } + + public int PairsNeeded { get; init; } + + public string TrialTitle { get; init; } = ""; + + public string TrialText { get; init; } = ""; + + /// How the model in charge was chosen, with everything that was tried. + public string? Choice { get; init; } + + public IReadOnlyList Attempts { get; init; } = []; + + /// Set when the last promotion can be taken back: the version that would return. + public int? UndoTo { get; init; } + + public bool Anomaly { get; init; } + + public bool Checked { get; init; } + + public IReadOnlyList Checks { get; init; } = []; + + public IReadOnlyList Weeks { get; init; } = []; + + public IReadOnlyList Found { get; init; } = []; + + public IReadOnlyList News { get; init; } = []; + + public IReadOnlyList Story { get; init; } = []; + + // ---- Panoramica --------------------------------------------------------------------------------------------- + + /// The few numbers of the Panoramica. + public static async Task SummaryAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(shell); + using var aggregates = shell.Aggregates(); + if (aggregates is not null) + { + return DemoSummary(aggregates.RootElement.GetProperty("apprendimento")); + } + + var services = host.Services!; + var desk = new LearningDesk(services.Db, host.Clock, services.Settings); + var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false); + var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false); + var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); + return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow); + } + + private static LearningSummary Summarise(IReadOnlyList models, int evaluated, CycleState state, bool aside, DateTimeOffset now) + { + var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion); + var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger); + var last = models.LastOrDefault(m => m.Version is not null); + var status = champion is null ? LearningStates.None + : aside ? LearningStates.Manual + : state.Aside is not null ? LearningStates.Aside + : state.ActivatedAt is not null ? LearningStates.Active + : LearningStates.Observation; + return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : Format.Day(DayOf(last.TrainedAt)), + champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null)); + } + + private static LearningSummary DemoSummary(JsonElement demo) => new(demo.GetProperty("stato").GetString()!, demo.GetProperty("segnali").GetInt32(), demo.GetProperty("necessari").GetInt32(), + demo.GetProperty("precisione_pct").GetInt32(), demo.GetProperty("ultimo_addestramento").GetString()!, "Prossima verifica dello sfidante", demo.GetProperty("prossima_verifica").GetString()!); + + // ---- Page --------------------------------------------------------------------------------------------------- + + public static async Task LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(shell); + using var aggregates = shell.Aggregates(); + if (aggregates is not null) + { + return Demo(aggregates.RootElement.GetProperty("apprendimento")); + } + + var services = host.Services!; + var clock = host.Clock; + var desk = new LearningDesk(services.Db, clock, services.Settings); + var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false); + var capitals = await LearningCycle.CapitalsAsync(services.Db, clock, cancellationToken).ConfigureAwait(false); + 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); + } + + /// The page from what was read, without touching the database. + public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary baseRates, IReadOnlyDictionary capitals, bool aside, DiscoverySet discoveries, + IReadOnlyList events, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(snapshot); + ArgumentNullException.ThrowIfNull(discoveries); + ArgumentNullException.ThrowIfNull(events); + var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State); + var inCharge = snapshot.InCharge; + var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now); + var activation = ActivationCheck.Of(inCharge, baseRates, capitals); + var last = snapshot.Models.LastOrDefault(m => m.Version is not null); + var (title, text) = Words(summary, state, now); + + var live = activation.Scores.Bands; + var history = !live.Any(b => b.Cases >= Judge.BandMin); + var verified = Verified(champion); + var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList(); + var view = new LearningView + { + Summary = summary, + Title = title, + Text = text, + Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null, + Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [], + LastTraining = last is null ? "mai" : $"{Format.Day(DayOf(last.TrainedAt))}, versione {last.Version}", + Bands = bands, + BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands), + BandsFromHistory = history && bands.Count > 0, + Champion = Column(champion, now), + Challenger = Column(challenger, now), + Choice = champion?.Report.Reason is { Length: > 0 } reason ? reason : null, + Attempts = champion is null ? [] : + [ + .. champion.Report.Attempts.Select(a => + new LearningAttempt(LearnerNames.Label(a.Learner), Points(a.Combined.Precision), Round(a.Combined.Brier, 3), Round(a.Combined.GainWith, 2), a.Chosen)), + ], + UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null, + Anomaly = state.Aside is not null, + Checked = state.Health is not null, + Found = discoveries.Found, + News = discoveries.News, + Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))], + }; + view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []); + if (champion is not null) + { + view = view with + { + Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Points(w.Precision)!.Value))], + Checks = state.Health is { } health ? ChecksOf(health, snapshot, champion, verified, events, now) : [], + }; + } + + return champion is not null && challenger is not null + ? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), champion.Version, challenger.Version) + : view with + { + TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.", + TrialText = champion is null ? "" : $"Il prossimo si addestra {At(summary.NextCheck)}, se nel frattempo ci sono casi nuovi.", + }; + } + + private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now) + { + const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero."; + const string Limits = "Non potrà mai ingrandirle, né aprirne di sue."; + const string Alone = "Le strategie proseguono senza di lui."; + return summary.State switch + { + LearningStates.None => ("Non ha ancora cominciato.", $"{How} La prima verifica, {At(summary.NextCheck)}, prepara il primo modello dai dati storici; da lì parte in osservazione."), + LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.", + $"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."), + LearningStates.Aside => ("Per ora è messo da parte.", + $"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."), + LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione. Si riattiva da Impostazioni."), + _ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.", + $"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"), + _ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"), + }; + } + + /// How long the missing signals take at the pace of the last four weeks. + public static string? PaceText(IReadOnlyList inCharge, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(inCharge); + var missing = ActivationCheck.Needed - inCharge.Count; + if (missing <= 0) + { + return null; + } + + var today = DayOf(now); + if (inCharge.Count == 0 || (today.DayNumber - inCharge.Min(e => e.Case.Label!.ClosedDay!.Value).DayNumber) is not (>= 7 and var seen)) + { + return "È presto per dire quanto manca."; + } + + var days = Math.Min(PaceDays, seen); + var recent = inCharge.Count(e => e.Case.Label!.ClosedDay!.Value > today.AddDays(-days)); + return recent == 0 ? "Nelle ultime settimane nessun segnale si è concluso." : PaceWords(missing * days / 7.0 / recent); + } + + /// "Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing. + public static string PaceWords(double weeks) + { + if (weeks <= 1) + { + return "Al ritmo attuale, meno di una settimana."; + } + + if (weeks > 52) + { + return "Al ritmo attuale, più di un anno."; + } + + if (weeks > 12) + { + return string.Create(_it, $"Al ritmo attuale, circa {Math.Round(weeks / 4.345):0} mesi."); + } + + var (low, high) = ((int)Math.Floor(weeks), (int)Math.Ceiling(weeks)); + return low == high ? $"Al ritmo attuale, circa {_numbers[low]} settimane." : $"Al ritmo attuale, tra {_numbers[low]} e {_numbers[high]} settimane."; + } + + private static List Missings(ActivationCheck check) + { + var missing = new List(); + if (!check.Calibrated) + { + missing.Add(check.CalibrationError is { } error + ? string.Create(_it, $"Le probabilità non sono ancora ben tarate: sbagliano in media di {error * 100:0.0} punti, il massimo è {ActivationCheck.MaxCalibrationError * 100:0}.") + : $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi."); + } + + if (!check.Improves) + { + missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso."); + } + + return missing; + } + + // ---- Calibration and clues ---------------------------------------------------------------------------------- + + private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1)); + + /// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not count. + public static string BandsWords(IReadOnlyList bands) + { + ArgumentNullException.ThrowIfNull(bands); + var solid = bands.Where(b => b.Solid).ToList(); + if (solid.Count == 0) + { + return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci."; + } + + var error = solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases); + var best = solid[^1]; + var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " + + (error < (decimal)ActivationCheck.MaxCalibrationError * 100 ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti."); + var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList(); + var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList(); + var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases); + static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : cases.ToString(_it) + " casi, troppo pochi")} per contarci."; + return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") + + (between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : ""); + } + + private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights) + { + var rest = weights.Skip(NamedWeights).Sum(w => w.Share); + var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList(); + if (rest > 0) + { + rows.Add(new LearningWeight("Tutto il resto", rest, true)); + } + + var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share); + var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share); + var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime." + : news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono." + : news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100." + : $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100."; + return view with { Weights = rows, WeightsText = text }; + } + + // ---- Versions ----------------------------------------------------------------------------------------------- + + /// The scores of a model on the cases it had not studied, from the verification of its training. + private static Scores? Verified(ModelRow? model) => model?.Report.Attempts.FirstOrDefault(a => a.Chosen)?.Combined; + + private static LearningVersion? Column(ModelRow? model, DateTimeOffset now) => model?.Version is not { } version ? null + : Verified(model) is { Cases: > 0 } s + ? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2)) + : new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null); + + private static LearningView WithTrial(LearningView view, TrialCheck check, int? champion, int? challenger) + { + var next = TrialCheck.Thresholds.FirstOrDefault(t => t > check.Pairs, TrialCheck.Thresholds[^1]); + var first = TrialCheck.Thresholds[0]; + var thresholds = string.Join(", ", TrialCheck.Thresholds.SkipLast(1)) + " e " + TrialCheck.Thresholds[^1]; + var text = check.Pairs switch + { + 0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.", + _ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " + + $"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.", + _ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. Si decide solo quando i casi superano {thresholds}: " + + $"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.", + }; + return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text }; + } + + // ---- Watch -------------------------------------------------------------------------------------------------- + + private static List ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList events, DateTimeOffset now) + { + var known = champion.Model is { } model ? snapshot.Examples.Count(e => e.Source == CaseSources.Live && model.Strategies.Contains(e.Strategy)) : 0; + var checks = new List + { + health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it)) + : known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}") + : new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"), + PrecisionCheck(Points(health.Precision), health.Cases, Points(verified?.Precision)), + }; + if (health.ErrorDrift) + { + checks.Add(new("warn", "I suoi errori sono aumentati negli ultimi casi")); + } + + checks.Add(new("wait", $"Ultimo controllo {Moment(health.At, now)}. {AlarmText(events, now)}")); + return checks; + } + + private static LearningCheck PrecisionCheck(int? precision, int cases, int? expected) + { + if (precision is not { } seen || cases < Health.MinCases) + { + return new("wait", cases == 0 ? $"Nessun segnale concluso: la precisione si giudica da {Health.MinCases} casi" : $"Segnali conclusi: {cases}. La precisione si giudica da {Health.MinCases} casi"); + } + + var against = expected is not { } e ? "" : Math.Abs(seen - e) <= 5 ? $", in linea con il {e}% atteso" : seen < e ? $", sotto il {e}% atteso" : $", sopra il {e}% atteso"; + return new(seen < Health.Alarm * 100 ? "warn" : "ok", $"Precisione sugli ultimi {cases} casi: {seen}%{against}"); + } + + private static string AlarmText(IReadOnlyList events, DateTimeOffset now) + { + if (events.LastOrDefault(e => e.Kind == ModelEvents.SetAside) is not { } alarm) + { + return "Nessun allarme finora"; + } + + var back = events.FirstOrDefault(e => e.Kind == ModelEvents.Back && e.At >= alarm.At); + var days = back is null ? 0 : Math.Max(1, (int)Math.Round((back.At - alarm.At).TotalDays)); + return $"Ultimo allarme il {DayText(DayOf(alarm.At), now)}, {(back is null ? "ancora in corso" : days == 1 ? "rientrato in un giorno" : $"rientrato in {days} giorni")}"; + } + + // ---- Demo --------------------------------------------------------------------------------------------------- + + private static LearningView Demo(JsonElement demo) + { + static decimal Amount(JsonElement e, string name) => decimal.Parse(e.GetProperty(name).GetString()!, CultureInfo.InvariantCulture); + LearningVersion Version(string name) + { + var v = demo.GetProperty(name); + return new LearningVersion(v.GetProperty("versione").GetInt32(), v.GetProperty("addestrato").GetString()!, v.GetProperty("casi").GetInt32(), v.GetProperty("precisione_pct").GetInt32(), + Amount(v, "errore"), Amount(v, "guadagno"), Amount(demo, "guadagno_senza_filtro")); + } + + var summary = DemoSummary(demo); + var champion = Version("in_carica"); + var challenger = Version("sfidante"); + var watch = demo.GetProperty("sorveglianza"); + var (title, text) = Words(summary, new CycleState(), DateTimeOffset.MinValue); + var view = new LearningView + { + Summary = summary, + Title = title, + Text = text, + Pace = PaceWords(demo.GetProperty("settimane_mancanti").GetDouble()), + LastTraining = $"{summary.Trained}, versione {challenger.Version}", + Bands = + [ + .. demo.GetProperty("fasce").EnumerateArray().Select(b => (From: b.GetProperty("da").GetInt32(), To: b.GetProperty("a").GetInt32(), Band: b)) + .Select(b => new LearningBand(b.From, b.To, b.Band.GetProperty("casi").GetInt32(), (b.From + b.To) / 2m, b.Band.GetProperty("pct").GetInt32())), + ], + BandsText = demo.GetProperty("fasce_testo").GetString()!, + Champion = champion, + Challenger = challenger, + Checked = true, + Checks = + [ + new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"), + PrecisionCheck(watch.GetProperty("precisione_pct").GetInt32(), watch.GetProperty("casi").GetInt32(), champion.Precision), + new("wait", watch.GetProperty("controllo").GetString()!), + ], + Weeks = [.. watch.GetProperty("settimane").EnumerateArray().Select(w => new LearningWeek(DateOnly.Parse(w.GetProperty("lunedi").GetString()!, CultureInfo.InvariantCulture), w.GetProperty("pct").GetInt32()))], + Found = [.. demo.GetProperty("scoperte").EnumerateArray().Select(d => new Discovery(d.GetProperty("titolo").GetString()!, d.GetProperty("dettaglio").GetString()!, d.GetProperty("casi").GetInt32()))], + Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))], + }; + var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList(); + return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), champion.Version, challenger.Version); + } + + // ---- Words -------------------------------------------------------------------------------------------------- + + /// The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model. + private static string NextText(DateTimeOffset now, bool sunday) + { + var local = TimeZoneInfo.ConvertTime(now, Zones.Rome); + var today = DateOnly.FromDateTime(local.DateTime); + var day = local.Hour < 3 ? today : today.AddDays(1); + if (sunday) + { + day = day.AddDays((7 - (int)day.DayOfWeek) % 7); + } + + return Format.Day(day) + ", 03:00"; + } + + /// "domenica 11 ottobre alle 03:00" from the short form. + private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal); + + /// "oggi alle 03:00", "il 4 ottobre alle 03:00". + private static string Moment(DateTimeOffset at, DateTimeOffset now) + { + var time = TimeZoneInfo.ConvertTime(at, Zones.Rome).ToString("HH:mm", CultureInfo.InvariantCulture); + return (DayOf(now).DayNumber - DayOf(at).DayNumber) switch + { + 0 => $"oggi alle {time}", + 1 => $"ieri alle {time}", + _ => $"il {DayText(DayOf(at), now)} alle {time}", + }; + } + + private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome); + + /// "4 ottobre", with the year when it is another one. + private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day); + + private static int? Points(double? share) => share is { } s ? (int)Math.Round(s * 100, MidpointRounding.AwayFromZero) : null; + + private static decimal Round(double value, int decimals) => Math.Round((decimal)value, decimals, MidpointRounding.AwayFromZero); +} diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs index 8ef47e4..4693515 100644 --- a/src/Anubis.Server/PanoramaView.cs +++ b/src/Anubis.Server/PanoramaView.cs @@ -14,8 +14,6 @@ internal sealed record AccountTrend(decimal Month, IReadOnlyList Points internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active); /// The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check. -internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck); - /// One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far. internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null); @@ -39,7 +37,7 @@ internal sealed record PanoramaView( IReadOnlyList? DemoLast, string? NextDecision, IReadOnlyList? News, - PanoramaLearning? Learning, + LearningSummary Learning, DateTimeOffset? FractionStops) { private static readonly CultureInfo _it = CultureInfo.InvariantCulture; @@ -93,12 +91,13 @@ internal sealed record PanoramaView( // The daily stops of the fractions come back with the orders after the open (SPEC 7.2). DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen); + var learning = await LearningView.SummaryAsync(host, shell, cancellationToken).ConfigureAwait(false); using var aggregates = shell.Aggregates(); if (aggregates is null) { var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false); return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), - services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), null, fractions); + services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions); } var root = aggregates.RootElement; @@ -108,9 +107,6 @@ internal sealed record PanoramaView( var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList(); var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!, n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList(); - var model = root.GetProperty("apprendimento"); - var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(), - model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!); // The 30-day results of appendix F.2: the generated daily series of each account only ends on its total. var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!, diff --git a/src/Anubis.Server/ReasonTexts.cs b/src/Anubis.Server/ReasonTexts.cs index f5bc486..f82621c 100644 --- a/src/Anubis.Server/ReasonTexts.cs +++ b/src/Anubis.Server/ReasonTexts.cs @@ -80,7 +80,7 @@ internal static class ReasonTexts return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto"; } - return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": in osservazione, non cambia niente"; + return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": solo osservazione, non ha cambiato la dimensione"; } // "(chiesti 0,05, passati 0,03)" when the stage shrank the order. diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json index c997edb..eb0b652 100644 --- a/src/Anubis/Demo/Data/aggregates.json +++ b/src/Anubis/Demo/Data/aggregates.json @@ -76,7 +76,40 @@ }, "apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56, - "ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00" + "ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00", + "settimane_mancanti": 3.5, "confronti": 14, "guadagno_senza_filtro": "5.84", + "in_carica": { "versione": 2, "addestrato": "16 agosto", "casi": 2152, "precisione_pct": 56, "errore": "0.241", "guadagno": "7.90" }, + "sfidante": { "versione": 3, "addestrato": "4 ottobre", "casi": 2332, "precisione_pct": 57, "errore": "0.239", "guadagno": "8.10" }, + "fasce": [ + { "da": 40, "a": 45, "casi": 22, "pct": 41 }, { "da": 45, "a": 50, "casi": 40, "pct": 45 }, { "da": 50, "a": 55, "casi": 61, "pct": 54 }, + { "da": 55, "a": 60, "casi": 50, "pct": 58 }, { "da": 60, "a": 65, "casi": 25, "pct": 60 }, { "da": 65, "a": 70, "casi": 14, "pct": 71 } + ], + "fasce_testo": "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.", + "indizi": [ + { "nome": "Forza della tendenza", "peso": 22 }, { "nome": "Agitazione recente dei prezzi", "peso": 17 }, { "nome": "Fase generale del mercato", "peso": 14 }, + { "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Tono delle notizie, 3 giorni", "peso": 9 }, { "nome": "Paura o avidità", "peso": 8 }, + { "nome": "Volumi scambiati", "peso": 7 }, { "nome": "Scommesse a leva sulle crypto", "peso": 5 }, { "nome": "Giorno della settimana", "peso": 3 }, + { "nome": "Altro", "peso": 4 } + ], + "sorveglianza": { + "precisione_pct": 55, "casi": 60, "controllo": "Ultimo controllo oggi alle 03:00. Ultimo allarme il 19 settembre, rientrato in 3 giorni", + "settimane": [ + { "lunedi": "2026-08-17", "pct": 53 }, { "lunedi": "2026-08-24", "pct": 54 }, { "lunedi": "2026-08-31", "pct": 55 }, { "lunedi": "2026-09-07", "pct": 52 }, + { "lunedi": "2026-09-14", "pct": 49 }, { "lunedi": "2026-09-21", "pct": 54 }, { "lunedi": "2026-09-28", "pct": 56 }, { "lunedi": "2026-10-05", "pct": 55 } + ] + }, + "scoperte": [ + { "titolo": "I segnali di trend riescono meno quando il mercato è molto agitato", "dettaglio": "44% di riusciti, contro il 58% dei periodi normali", "casi": 32 }, + { "titolo": "Dopo una notizia molto negativa i rimbalzi falliscono più spesso", "dettaglio": "29% di riusciti, contro il 48% del solito", "casi": 17 }, + { "titolo": "Il giorno della settimana non conta", "dettaglio": "Le differenze stanno tutte dentro il margine d'errore", "casi": 212 } + ], + "storia": [ + { "quando": "4 ottobre", "testo": "Addestrata la versione 3. È in prova come sfidante." }, + { "quando": "27 settembre", "testo": "La versione 2 prende il posto della 1: due punti di precisione in più su 120 casi di confronto." }, + { "quando": "19 settembre", "testo": "Allarme: precisione scesa al 49% su 41 casi. Modello messo da parte per 3 giorni, poi rientrato." }, + { "quando": "16 agosto", "testo": "Addestrata la versione 2. In prova come sfidante." }, + { "quando": "12 agosto", "testo": "Prima versione, addestrata su 2.140 segnali ricostruiti dai dati storici." } + ] }, "sistema": { "controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00", diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 5df0a34..c0ed982 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -287,7 +287,8 @@ public static class DemoMode "VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)", cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought), ("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false); - await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken) + await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, + rows[i].Length > 3 && rows[i][3] == "MSFT", now, cancellationToken) .ConfigureAwait(false); } } @@ -295,7 +296,7 @@ public static class DemoMode // F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on // the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss. private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought, - decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken) + decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, bool estimated, DateTimeOffset now, CancellationToken cancellationToken) { var (entry, exit) = strategy switch { @@ -304,11 +305,11 @@ public static class DemoMode _ => ("meanrev_entry", "meanrev_exit_average"), }; - async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) => + async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at, object? data = null) => await s.ExecuteAsync( - "INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, NULL, @t)", + "INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, @data, @t)", cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome), - ("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false); + ("r", new DbJson(JsonSerializer.Serialize(reasons))), ("data", data is null ? null : new DbJson(JsonSerializer.Serialize(data))), ("t", at)).ConfigureAwait(false); async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) => await s.ExecuteAsync( @@ -320,6 +321,13 @@ public static class DemoMode var buy = ids.Next(); await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false); await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); + if (estimated) + { + // F.6: the estimate of the model on MSFT, noted in observation; the usual share is the one of F.7. + await DecideAsync(buy, Trading.DecisionStages.Model, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1), + new { probability = 0.61, base_rate = 0.48, multiplier = 1, applied = 1, counts = false }).ConfigureAwait(false); + } + await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false); if (stopped) diff --git a/src/Anubis/Learning/LearningSettings.cs b/src/Anubis/Learning/LearningSettings.cs index 453b54c..3f6d8d4 100644 --- a/src/Anubis/Learning/LearningSettings.cs +++ b/src/Anubis/Learning/LearningSettings.cs @@ -14,6 +14,15 @@ public static class LearningSettings public static readonly IReadOnlyList All = [Full, Zero, Aside]; + /// True when the new values can leave operations bigger than before: the model shrinks less, or not at all. + public static bool Raised(Func before, Func after) + { + ArgumentNullException.ThrowIfNull(before); + ArgumentNullException.ThrowIfNull(after); + static int Points(string value) => int.Parse(value, CultureInfo.InvariantCulture); + return Points(after(Full.Key)) > Points(before(Full.Key)) || Points(after(Zero.Key)) > Points(before(Zero.Key)) || (after(Aside.Key) == "on" && before(Aside.Key) != "on"); + } + public static async Task<(MultiplierRule Rule, bool Aside)> LoadAsync(SettingsStore? settings, CancellationToken cancellationToken) { if (settings is null) diff --git a/src/Anubis/Learning/ModelStore.cs b/src/Anubis/Learning/ModelStore.cs index 8703cf2..fb904e9 100644 --- a/src/Anubis/Learning/ModelStore.cs +++ b/src/Anubis/Learning/ModelStore.cs @@ -67,6 +67,12 @@ public sealed class ModelStore(Database db) return s.FirstOrDefaultAsync("SELECT " + Columns + " WHERE status = @s ORDER BY trained_at DESC, id DESC", Read, ("s", status)); } + /// The version that would come back if the last promotion were taken back; null when there is nothing to take back. + public async Task UndoToAsync(CancellationToken cancellationToken) => + await FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false) is { ReplacedId: { } replaced } + ? (await AllAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version + : null; + public Task CountAsync(CancellationToken cancellationToken) => db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_models"), cancellationToken); /// Writes the result of a training in the register: the chosen model with its version, the others as attempts. @@ -135,6 +141,11 @@ public sealed class ModelStore(Database db) db.ReadAsync(s => s.QueryAsync("SELECT feature_id, model_id, probability, base_rate, multiplier, in_charge FROM ml_predictions ORDER BY created_at, id", r => new PredictionRow(r.Id("feature_id"), r.Id("model_id"), r.Measure("probability"), r.Measure("base_rate"), r.Measure("multiplier"), r.Bool("in_charge"))), cancellationToken); + /// How many live signals got an estimate in charge and then an outcome: the count towards the 300 of SPEC 11.5. + public Task EvaluatedAsync(CancellationToken cancellationToken) => + db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_predictions p JOIN ml_labels l ON l.feature_id = p.feature_id WHERE p.in_charge = @c AND l.label IS NOT NULL AND l.closed_day IS NOT NULL", + ("c", true)), cancellationToken); + // ---- History ------------------------------------------------------------------------------------------------ public static Task AddEventAsync(DbSession s, IClock clock, string kind, int? version, string text, CancellationToken cancellationToken) diff --git a/tests/Anubis.Tests/LearningCycleTests.cs b/tests/Anubis.Tests/LearningCycleTests.cs index 0696118..6b55c25 100644 --- a/tests/Anubis.Tests/LearningCycleTests.cs +++ b/tests/Anubis.Tests/LearningCycleTests.cs @@ -97,7 +97,7 @@ public sealed class LearningCycleTests Assert.IsTrue(with.Predictions.Where(p => !p.InCharge).All(p => p.Multiplier == 1)); Assert.HasCount(with.Examples.Count, with.Rows); Assert.IsTrue(with.Rows.All(r => r.Outcome == DecisionOutcomes.Passed)); - Assert.Contains("in osservazione, non cambia niente", Anubis.Server.ReasonTexts.Model((string)with.Rows[0].Data!["json"]!)!); + Assert.Contains("solo osservazione, non ha cambiato la dimensione", Anubis.Server.ReasonTexts.Model((string)with.Rows[0].Data!["json"]!)!); Assert.HasCount(0, without.Predictions); } diff --git a/tests/Anubis.Tests/LearningScreenTests.cs b/tests/Anubis.Tests/LearningScreenTests.cs new file mode 100644 index 0000000..1b4dd7c --- /dev/null +++ b/tests/Anubis.Tests/LearningScreenTests.cs @@ -0,0 +1,359 @@ +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; + +/// The Apprendimento screen, the model settings and the model box of the Panoramica (SPEC 13.5, 13.6; issue #66). +[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 Rates = new() { [StrategyNames.CryptoTrend] = 0.4 }; + + private static readonly Dictionary 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}\"."); + } + } + + /// The numbers of appendix F.7 as in the mockup, on the page, in the Panoramica and in Operazioni; nothing can be changed. + [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.", "212 su 300 necessari", "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"); + 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); + } + + /// A new installation: no invented number, then the first model, the live signals, the challenger, the undo. + [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", "0 su 300 necessari", "È 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 { [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, "120 su 300 necessari", "Sfidante, versione 2", "120 su 150", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto.", + "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)); + } + + /// SPEC 13.5, 12.4: the thresholds and the set-aside from Impostazioni; shrinking less needs the phrase with real money. + [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 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>(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? 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? estimates = null, IReadOnlyList? 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 { [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"); + Assert.IsTrue(View(new CycleState { Health = health with { DriftingClues = ["Volumi scambiati"] } }, models: champion).Checks[0] is { State: "warn" }); + } + + /// With 300 signals it still says what is missing; the count is of the system, not of the version. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheProgressSaysWhatIsMissing() + { + var (retired, champion) = (Row(ModelStatuses.Retired, 1), Row(ModelStatuses.Champion, 2)); + List 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)); + } + + /// Bands under 20 cases are said unreliable, in the sentence and one by one. + [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 clues after the ninth are "Tutto il resto", the whole stays 100; the sentence about the news follows the numbers. + [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); + } + + /// The trial before and after the first threshold; the gain without the filter is said once when it is the same. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheTrialSaysWhereItIs() + { + var (champion, challenger) = (Row(ModelStatuses.Champion, 1), Row(ModelStatuses.Challenger, 2, 520, gainWithout: 6)); + List 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, 150), (more.Pairs, more.PairsNeeded)); + StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide solo quando i casi superano 100, 150, 200, 250 e 300"); + Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger]).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); + } + + /// The next night is the coming Sunday at 03:00 in Rome, across the change of hour and the year. + [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"); + } +} diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs index 35758fa..03f88f4 100644 --- a/tests/Anubis.Tests/OverviewScreenTests.cs +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -125,7 +125,7 @@ public sealed class OverviewScreenTests // A new installation: the screens say what is missing instead of showing numbers. var home = await server.TextAsync("/"); StringAssert.Contains(home, "La lettura delle notizie è spenta insieme ai dati di mercato."); - StringAssert.Contains(home, "L'apprendimento non è ancora attivo."); + StringAssert.Contains(home, "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica."); var diary = await server.TextAsync("/diario"); StringAssert.Contains(diary, "Come sta il sistema"); StringAssert.Contains(diary, "non configurato"); diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 1e0f1cc..719d46b 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -142,7 +142,7 @@ int Screenshots(string[] pages) var folder = Path.Combine(root, "artifacts", "screenshots"); Directory.CreateDirectory(folder); - var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/notizie", "/impostazioni"]; + var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/notizie", "/apprendimento", "/impostazioni"]; using var shots = Shots.Start(browser); foreach (var page in targets) {