diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md index b6335ef..bc56674 100644 --- a/Encelado/docs/API.md +++ b/Encelado/docs/API.md @@ -138,7 +138,8 @@ type Tick = { }; learning: { mode: "ombra-disabilitato" | "ombra" | "attivo"; - labelledRows: number; + labelledRows: number; // basket etichettati come li conta il dataset (con le feature d'ingresso): lo stesso numero di dataset.labelledRows + // di /api/learning; ricontato dal ledger all'avvio dopo la verifica del realizzato e a ogni ciclo target: number; // 300 rollingAuc: number | null; banditPreset: string; // proposta, mai applicata @@ -293,7 +294,17 @@ type SecretInfo = { present: boolean; masked: string; savedUtc: string | null }; ### `GET /api/learning` -Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile); a motore fermo e per i file di `knowledge/` la legge dal disco in sola lettura. Query: `features=all` aggiunge il vettore completo per basket. L'`ETag` è la versione della sezione (`versions.learning`) con l'impronta dei file letti — modelli, `knowledge/`, `baskets.csv`, i file delle decisioni e `strategy.json`, da cui un motore fermo prende interruttori, `pMin` e basket: anche una modifica a mano del file cambia l'`ETag` (entro 2 s) —: con `If-None-Match` uguale la risposta è **304** senza costruire niente. Ogni salvataggio di un campo `strategy:` dalle Impostazioni fa avanzare `versions.learning`, così la pagina rilegge subito. `generatedUtc` è l'ora in cui il motore ha pubblicato il rapporto (o quella della lettura dal disco). A motore fermo `baskets[].pMl` è quella dell'ultima riga di valutazione del ledger e `vol` porta solo σ prevista, σ media, rapporto e scala di `z_in` di quella riga (`bars` 0, `activeModel` vuoto, `context` −1), oppure `null`. +Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile); a motore fermo e per i file di `knowledge/` la legge dal disco in sola lettura. Query: `features=all` aggiunge il vettore completo per basket. L'`ETag` è la versione della sezione (`versions.learning`) con l'impronta dei file letti — modelli, `knowledge/`, `baskets.csv`, i file delle decisioni e `strategy.json`, da cui un motore fermo prende interruttori, `pMin` e basket: anche una modifica a mano del file cambia l'`ETag` (entro 2 s) —: con `If-None-Match` uguale la risposta è **304** senza costruire niente. Ogni salvataggio di un campo `strategy:` dalle Impostazioni fa avanzare `versions.learning`, così la pagina rilegge subito. `generatedUtc` è l'ora in cui il motore ha pubblicato il rapporto (o quella della lettura dal disco). + +I contributi di un basket (`topContributions`, `features`) spiegano sempre la `pMl` mostrata accanto: vengono dal modello che l'ha data, nel momento in cui l'ha data, e la somma dei `contribution` di `features` più `intercept` è il logit di `pMl`. Il motore li prende insieme alla p a ogni chiusura di barra a basket piatto e li conserva con l'ingresso, anche in `learning_state.json` (così sopravvivono a un riavvio). Una p che nessuna spiegazione accompagna è mostrata senza contributi (`topContributions` vuoto, `features` vuoto con `features=all`, `intercept` `null`): per esempio la p all'ingresso di un basket aperto prima della 5.1, quando il modello nel frattempo è cambiato, o la p del campione MLP. Senza `pMl` (il modello non ha ancora visto un basket) non ci sono contributi. + +A motore fermo: +- per un basket in posizione all'ultima riga di valutazione, `pMl` è quella dell'ingresso con i contributi salvati con l'ingresso (`pMlKind` «all'ingresso», `pMlUtc` l'ora dell'ingresso); +- per un basket senza posizione, `pMl` è quella dell'ultima riga di valutazione del ledger se il modello salvato la ridà per i valori di quella riga (`pMlKind` «ultima barra»); altrimenti — il modello ha imparato dopo quella barra, o il motore aveva dato al modello un vettore diverso da quello che la riga registra (il vettore valutato alla chiusura di barra non ha ancora il costo dell'ingresso, la riga sì) — è quella che il modello salvato dà ai valori della riga (`pMlKind` «ricalcolata con il modello di oggi», `pMlUtc` l'ora della riga); +- `vol` porta solo σ prevista, σ media, rapporto e scala di `z_in` dell'ultima riga (`bars` 0, `activeModel` vuoto, `context` −1), oppure `null`; +- un file dei modelli che non si riesce a leggere (modificato a mano, schema diverso) lascia l'ultima lettura buona di quella parte, e un avviso in `warnings` lo dice («… non leggibile (…): mostro l'ultima lettura buona»); se non c'è mai stata una lettura buona l'avviso dice che sono mostrati i valori iniziali. Un file assente vale i valori iniziali, senza avviso. + +`dataset` è ricalcolato quando cambia `baskets.csv`, quando compare un file delle decisioni, quando il ledger riceve una correzione `pnl_realizzato` o la marcatura `feature_inaffidabile` di `lastNOutcomes` (lette in modo incrementale), e comunque al più ogni ora. ```ts { schema: 1; generatedUtc: string; source: "engine" | "disk"; engineState: string; @@ -321,7 +332,9 @@ Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile) brier100: number | null; logLoss100: number | null; hitRate100: number | null; meanP100: number | null; lastOutcomes10: number | null; recentP: number[]; recentLabel: number[]; aucHistory: Array<{ utc: string; auc100: number }>; calibration: CalibrationBin[] }; baskets: Array<{ basket: string; cross: string; enabled: boolean; state: string; pMl: number | null; pMlUtc: string | null; - pMlKind: "ultima barra" | "all'ingresso" | ""; wouldBeFiltered: boolean; + pMlKind: "ultima barra" | "all'ingresso" | "ricalcolata con il modello di oggi" | ""; + intercept: number | null; // intercetta del modello che ha dato pMl: Σ features[].contribution + intercept = logit(pMl); null senza contributi + wouldBeFiltered: boolean; topContributions: Array<{ index: number; name: string; label: string; value: number | null; z: number | null; contribution: number | null }>; features: Array<{ index: number; name: string; label: string; value: number | null; z: number | null; contribution: number | null }> | null; vol: null | { bars: number; activeModel: string; ewmaSigma: number | null; harSigma: number | null; forecastSigma: number | null; @@ -331,6 +344,9 @@ Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile) currentPreset: string; applied: false; rewardsSuspect: boolean; arms: Array<{ context: number; contextLabel: string; preset: string; alpha: number; beta: number; successes: number; failures: number; n: number; mean: number; low95: number; high95: number; bestInContext: boolean }>; + // bestInContext: la media a posteriori più alta del contesto, solo per un braccio con almeno un esito (n > 0): + // un bandit nuovo non ha bracci migliori, e nemmeno un contesto i cui bracci provati non fanno meglio del prior + // (a pari media vince il primo braccio nell'ordine Conservative, Moderate, Aggressive) lastProposal: null | { utc: string; context: number; preset: string; explored: boolean; means: number[]; text: string } }; volatility: null | { historyCount: number; tercileLow: number | null; tercileHigh: number | null }; knowledge: { calibration: Array<{ dimension: string; bucket: string; count: number; winRate: number | null; meanPnl: number | null; totalPnl: number | null; motivazione: string }>; diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/LearningAnalytics.cs b/Encelado/src/Encelado.Core/Baskets/Learning/LearningAnalytics.cs index cf750be..0bd3421 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/LearningAnalytics.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/LearningAnalytics.cs @@ -280,14 +280,27 @@ public static class LearningRows : new VolatilityContextSummary(history.Count, sorted[sorted.Length / 3], sorted[2 * sorted.Length / 3]); } - /// One basket as the meta-model sees it: p, what pushes it (the five largest |w·z|), the full vector, the volatility. - public static BasketLearningRow Basket(string name, string cross, bool enabled, string state, double pMl, DateTime? pMlUtc, bool atEntry, double pMin, - IReadOnlyList features, BasketVolRow? vol) + /// The kind of an engine's probability: the entry's while the basket holds (or waits for) a position, the last bar close's otherwise. + public static string KindOf(bool atEntry) => atEntry ? BasketLearningRow.KindAtEntry : BasketLearningRow.KindLastBar; + + /// + /// One basket as the meta-model sees it: p and the kind of reading it is, what pushes it (the + /// five largest |w·z|), the full vector, the volatility. The contributions are shown only when + /// they give back the p shown (5.1 review): an explanation of another model, or of another + /// moment, is left out rather than put next to a probability it did not produce. + /// + public static BasketLearningRow Basket(string name, string cross, bool enabled, string state, double pMl, DateTime? pMlUtc, string kind, double pMin, + ScoreExplanation explained, BasketVolRow? vol) { - ArgumentNullException.ThrowIfNull(features); - string kind = !double.IsFinite(pMl) ? string.Empty : atEntry ? BasketLearningRow.KindAtEntry : BasketLearningRow.KindLastBar; - return new BasketLearningRow(name, cross, enabled, state, pMl, double.IsFinite(pMl) ? pMlUtc : null, kind, double.IsFinite(pMl) && pMl < pMin, - OnlineLogistic.Top(features, 5), features, vol); + ArgumentNullException.ThrowIfNull(explained); + bool known = double.IsFinite(pMl); + bool explains = explained.Explains(pMl); + IReadOnlyList features = explains ? explained.Features : []; + return new BasketLearningRow(name, cross, enabled, state, pMl, known ? pMlUtc : null, known ? kind : string.Empty, known && pMl < pMin, + OnlineLogistic.Top(features, 5), features, vol) + { + Intercept = explains ? explained.Intercept : double.NaN, + }; } } diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/LearningJson.cs b/Encelado/src/Encelado.Core/Baskets/Learning/LearningJson.cs index 8069c74..451cace 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/LearningJson.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/LearningJson.cs @@ -367,6 +367,7 @@ public static class LearningJson Num(w, "pMl", b.PMl, 4); TimeOrNull(w, "pMlUtc", b.PMlUtc); w.WriteString("pMlKind", b.PMlKind); + Num(w, "intercept", b.Intercept, 6); w.WriteBoolean("wouldBeFiltered", b.WouldBeFiltered); Features(w, "topContributions", b.TopContributions); if (allFeatures) diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/LearningReport.cs b/Encelado/src/Encelado.Core/Baskets/Learning/LearningReport.cs index 43e7491..176beac 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/LearningReport.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/LearningReport.cs @@ -94,7 +94,7 @@ public sealed record LearningLiveReport /// When the models taught by the proceeds-based labels of 4.0.0–5.0.0 were retired; null when never. public DateTime? LabelsFixedUtc { get; init; } - /// Labelled baskets the engine counted (the tick's headline, against the 300 of the activation). + /// Labelled baskets as the training set counts them, with their entry features (the tick's headline, against the 300 of the activation; the dataset's labelledRows). public int LabelledRows { get; init; } /// The volatility model in use on the first enabled basket (EWMA or HAR). @@ -302,7 +302,13 @@ public sealed record BasketVolRow( int Context, string ContextLabel); -/// One basket as the meta-model sees it. +/// +/// One basket as the meta-model sees it. The contributions explain the probability shown (5.1 +/// review): they come from the model that gave , at the moment it gave it, so +/// their sum plus is the logit of . A probability no +/// stored explanation goes with (an entry remembered by an older version, a model that moved +/// since) is shown without contributions. +/// public sealed record BasketLearningRow( string Basket, string Cross, @@ -316,8 +322,33 @@ public sealed record BasketLearningRow( IReadOnlyList Features, BasketVolRow? Vol) { + /// The engine's probability at the last bar close of a basket without a position. public const string KindLastBar = "ultima barra"; + + /// The probability given at the entry of the open basket. public const string KindAtEntry = "all'ingresso"; + + /// A stopped bot's page: the saved model's probability for the values of the last evaluation row, which the model of that bar no longer is. + public const string KindRecomputed = "ricalcolata con il modello di oggi"; + + /// The intercept of the model that gave ; NaN without contributions. + public double Intercept { get; init; } = double.NaN; +} + +/// +/// A probability with what made it, from one model at one moment (5.1 review): the features' +/// contributions (w·z, in index order) and the intercept add up to its logit. No +/// contributions when the probability is not the logistic's (the MLP champion, or nothing seen). +/// +public sealed record ScoreExplanation(double P, double Intercept, IReadOnlyList Features) +{ + /// Nothing to explain: no probability, no contributions. + public static readonly ScoreExplanation None = new(double.NaN, double.NaN, []); + + /// Whether the contributions and the intercept give back (to ): a stored or a recomputed explanation may be shown next to it. + public bool Explains(double p, double tolerance = 1e-6) => + Features.Count > 0 && double.IsFinite(p) && double.IsFinite(Intercept) && + Math.Abs(OnlineLogistic.Sigmoid(Features.Sum(static f => f.Contribution) + Intercept) - p) <= tolerance; } /// One arm of the bandit: a preset in a volatility context. diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/OnlineLogistic.cs b/Encelado/src/Encelado.Core/Baskets/Learning/OnlineLogistic.cs index f150f09..b53a86e 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/OnlineLogistic.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/OnlineLogistic.cs @@ -266,6 +266,33 @@ public sealed class OnlineLogistic : IModel return values; } + /// + /// The probability for one row with what made it, in one read of the weights (5.1 review): + /// the contributions and the intercept add up to its logit. NaN and no contributions before + /// the model has seen a basket, as the champion's prediction. Pure. + /// + public ScoreExplanation Score(double[] features) + { + ArgumentNullException.ThrowIfNull(features); + return _seen == 0 ? ScoreExplanation.None : new ScoreExplanation(Predict(features), _b, Explain(features)); + } + + /// The values of from a vector and the standardised values and contributions kept with it (an entry remembered with its explanation). + public static IReadOnlyList Rebuild(IReadOnlyList features, IReadOnlyList z, IReadOnlyList contributions) + { + ArgumentNullException.ThrowIfNull(features); + ArgumentNullException.ThrowIfNull(z); + ArgumentNullException.ThrowIfNull(contributions); + int n = Math.Min(features.Count, Math.Min(z.Count, contributions.Count)); + FeatureValue[] values = new FeatureValue[n]; + for (int i = 0; i < n; i++) + { + values[i] = new FeatureValue(i, NameOf(i), LabelOf(i), features[i], z[i], contributions[i]); + } + + return values; + } + /// The largest contributions of by |w·z|. public static IReadOnlyList Top(IReadOnlyList values, int count) { diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs b/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs index b32fb19..ea285c3 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs @@ -63,8 +63,10 @@ public sealed class ThompsonBandit /// /// Every arm's posterior, read without drawing anything: α and β, the rewards behind them /// (α − 1 wins, β − 1 losses on the Beta(1, 1) prior), the posterior mean with its 95 % - /// credible interval, and whether it is the best mean of its context. In context order, - /// arms in preset order (Conservative, Moderate, Aggressive). + /// credible interval, and whether it is the best mean of its context. An arm never tried + /// is never the best (5.1 review): its mean is the prior's, not something learnt, so a + /// fresh bandit has no best arm, and neither has a context whose tried arms do no better + /// than the prior. In context order, arms in preset order (Conservative, Moderate, Aggressive). /// public IReadOnlyList Arms() { @@ -83,8 +85,9 @@ public sealed class ThompsonBandit double alpha = _alpha[c, a], beta = _beta[c, a]; int wins = (int)Math.Round(Math.Max(0, alpha - 1)); int losses = (int)Math.Round(Math.Max(0, beta - 1)); - arms.Add(new BanditArm(c, ContextLabel(c), ((PresetName)a).ToString(), alpha, beta, wins, losses, wins + losses, means[a], - Statistics.BetaDistribution.Quantile(0.025, alpha, beta), Statistics.BetaDistribution.Quantile(0.975, alpha, beta), a == best)); + int n = wins + losses; + arms.Add(new BanditArm(c, ContextLabel(c), ((PresetName)a).ToString(), alpha, beta, wins, losses, n, means[a], + Statistics.BetaDistribution.Quantile(0.025, alpha, beta), Statistics.BetaDistribution.Quantile(0.975, alpha, beta), a == best && n > 0)); } } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Learning.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Learning.cs index 5002f35..00e5f54 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Learning.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Learning.cs @@ -38,6 +38,32 @@ public sealed partial class BasketEngine /// The tests' seam: the learning state a run builds once it holds the instance lock, built the same way. internal LearningState StartLearning() => _learning ??= new LearningState(_dataDir, _config.Run.KnowledgePath, _ledger, _strategy); + /// + /// An open basket taken back after a restart gets the probability it entered with, from the + /// learning state's entry (5.1 review): the tick, the page and the ledger's rows show the p it + /// entered with, as they did before the restart, explained by the model that gave it — kept + /// with the entry, or the current model when it still gives that p. Display and records only: + /// an open basket's p filters and sizes nothing. + /// + private void RestoreEntryScore(BasketSlot slot) + { + if (_learning?.EntryOf(slot.PositionBasketId) is not { } entry || !double.IsFinite(entry.PAtEntry)) + { + return; + } + + ScoreExplanation explained = entry.Explained(); + if (!explained.Explains(entry.PAtEntry) && _learning.Score(entry.Features) is { } now && now.Explains(entry.PAtEntry)) + { + explained = now; + } + + slot.LastFeatures = [.. entry.Features]; + slot.PMl = entry.PAtEntry; + slot.PMlUtc = entry.Utc == default ? null : entry.Utc; + slot.Explained = explained; + } + /// The training function of the cycles (the tests replace it); the engine's own by default. internal Func?, CancellationToken, CycleResult> CycleTrainer { @@ -143,8 +169,8 @@ public sealed partial class BasketEngine private string CycleTriggerOf(Exception? error) => _cycles.Status.Trigger is { Length: > 0 } t ? t : error is OperationCanceledException ? CycleTriggers.Manual : string.Empty; - /// Builds the report and publishes it. Decision thread only; a failure costs the report, never the loop. - private void PublishLearning(DateTime now) + /// Builds the report and publishes it. Decision thread only (internal: the tests publish it over their own venue); a failure costs the report, never the loop. + internal void PublishLearning(DateTime now) { if (_learning is null) { @@ -179,7 +205,6 @@ public sealed partial class BasketEngine bool volModelSet = false; foreach (BasketSlot s in _slots) { - IReadOnlyList features = s.LastFeatures is { } f ? learner.Explain(f) : []; VolStats vs = s.Vol.Stats(_strategy.VolAverageDays); int context = ThompsonBandit.VolatilityContext(vs.ForecastSigma, _volHistory); BasketVolRow? vol = LearningRows.Vol(vs, context, _strategy.VolScaleMin, _strategy.VolScaleMax); @@ -191,7 +216,9 @@ public sealed partial class BasketEngine string state = !s.Enabled && s.Position is null && s.Pending is null && s.State == BasketState.Idle ? "Disabled" : s.State.ToString(); bool atEntry = s.Position is not null || s.State.IsPending(); - rows.Add(LearningRows.Basket(s.Name, s.Cross.Symbol, s.Enabled, state, s.PMl, s.PMlUtc, atEntry, pMin, features, vol)); + + // The contributions taken with the p (5.1 review): the model of that bar, or of the entry, whatever it learnt since. + rows.Add(LearningRows.Basket(s.Name, s.Cross.Symbol, s.Enabled, state, s.PMl, s.PMlUtc, LearningRows.KindOf(atEntry), pMin, s.Explained, vol)); } CycleRunStatus run = _cycles.Status; diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs index 20f4ed5..5c2384d 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs @@ -100,12 +100,16 @@ public sealed partial class BasketEngine /// /// At startup, on the Demo or Live account: the rows written by 4.0.0–5.0.0 are checked /// against the venue's history and corrected with new lines (). - /// When rows of those versions were wrong, once: the lastNOutcomes feature is - /// declared unreliable up to now, the notes' proceeds range is recorded, and the models - /// that learnt from the wrong labels are retired and rebuilt. A failure is retried at - /// the next start. + /// The learning state then reads the corrected ledger again (5.1 review): the outcomes behind + /// lastNOutcomes and the labelled count it read before the corrections are replaced, + /// so every evaluation row of this session carries a lastNOutcomes computed from the + /// venue's labels. When rows of those versions were wrong, once: the feature is declared + /// unreliable up to now — the rows before were computed from the wrong labels, those after + /// are right whatever happens to the retire — the notes' proceeds range is recorded, and the + /// models that learnt from the wrong labels are retired and rebuilt. A failure is retried at + /// the next start. Internal: the tests drive it over their own venue. /// - private async Task BackfillRealizedAsync(CancellationToken ct) + internal async Task BackfillRealizedAsync(CancellationToken ct) { try { @@ -125,6 +129,7 @@ public sealed partial class BasketEngine try { + Learner.Reseed(); if (Learner.LabelsFixed || !RealizedBackfill.LegacyRowsWereCorrected(_ledger)) { return; diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index 307249c..df0e2ad 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -326,6 +326,7 @@ public sealed partial class BasketEngine slot.PositionBasketId = p.BasketId; slot.State = BasketState.Open; slot.Intent = "ripreso dallo stato salvato: " + p.Describe(); + RestoreEntryScore(slot); _knownPositions.UnionWith(p.A.AllPositionIds); _knownPositions.UnionWith(p.B.AllPositionIds); Log.Info($"[{name}] basket ripreso dallo stato salvato: {p.Describe()}"); diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index 97689aa..f5db97a 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -206,6 +206,9 @@ public sealed partial class BasketEngine : IEngine /// When was computed (a bar close while flat; it stays the entry's while the basket is open). public DateTime? PMlUtc { get; set; } + /// What made : the contributions and the intercept of the model that gave it, taken with it (5.1 review). + public ScoreExplanation Explained { get; set; } = ScoreExplanation.None; + public bool Busy { get; set; } public string PositionBasketId { get; set; } = string.Empty; @@ -1088,8 +1091,10 @@ public sealed partial class BasketEngine : IEngine { BasketEvaluation preview = _decider.Compute(ctx); double[] features = LearningFeatures.From(ctx, preview, preview.Z < 0); + ScoreExplanation score = Learner.Score(features); slot.LastFeatures = features; - slot.PMl = Learner.Predict(features); + slot.PMl = score.P; + slot.Explained = score; slot.PMlUtc = now; ctx = ctx with { PMl = slot.PMl, MlActive = MlGate.IsActive(_strategy.Learning.Enabled, Learner.Active, slot.PMl) }; } @@ -1384,8 +1389,9 @@ public sealed partial class BasketEngine : IEngine slot.PositionBasketId = basketId; if (slot.LastFeatures is { } fx) { - // The p given at the decision goes with the features: the rolling AUC scores it at the close (5.1). - Learner.RememberEntry(basketId, fx, slot.PMl, DateTime.UtcNow); + // The p given at the decision goes with the features: the rolling AUC scores it at the close (5.1), + // and the page explains it with the model that gave it (5.1 review). + Learner.RememberEntry(basketId, fx, slot.PMl, DateTime.UtcNow, slot.Explained); } Transition(slot, BasketState.Open); diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs index 5a1504a..bec390f 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs @@ -187,31 +187,52 @@ public static class LearningDiskReader } } - /// Parses a JSON model file, retrying a text caught half-written; null when absent or unreadable after three tries. - private static T? ReadJson(string path, Func parse, List warnings) + /// + /// Parses a JSON model file, retrying a text caught half-written. Value null and no error when + /// the file is absent (the defaults are right); value null with the error when it stayed + /// unreadable after three tries (the caller keeps its last good reading, 5.1 review). + /// + private static (T? Value, string? Error) ReadJson(string path, Func parse) where T : class { - for (int attempt = 0; attempt < 3; attempt++) + for (int attempt = 0; ; attempt++) { try { string? text = ReadText(path); - return text is null ? null : parse(text); + return (text is null ? null : parse(text), null); } catch (Exception ex) when (ex is JsonException or InvalidOperationException or KeyNotFoundException or FormatException or IOException or IndexOutOfRangeException or UnauthorizedAccessException) { - if (attempt < 2) + if (attempt >= 2) { - Thread.Sleep(50); - } - else - { - warnings.Add($"{Path.GetFileName(path)} non leggibile ({ex.Message}): mostro l'ultima lettura buona"); + return (null, ex.Message); } + + Thread.Sleep(50); } } + } - return null; + /// + /// One part of the models of a stopped bot: the file's reading; when the file cannot be read, + /// the last good reading of that part with a warning that says so, or — never read well — + /// null (the caller's starting values) with a warning that says that instead (5.1 review). An + /// absent file is null without a warning: the starting values are what it means. + /// + private static T? Part(string path, Func parse, bool readBefore, T? lastGood, List warnings) + where T : class + { + (T? value, string? error) = ReadJson(path, parse); + if (error is null) + { + return value; + } + + warnings.Add(readBefore + ? $"{Path.GetFileName(path)} non leggibile ({error}): mostro l'ultima lettura buona" + : $"{Path.GetFileName(path)} non leggibile ({error}): nessuna lettura buona prima, mostro i valori iniziali"); + return lastGood; } // ----------------------------------------------------------------------- @@ -244,7 +265,7 @@ public static class LearningDiskReader { string cross = SyntheticCross.TryDerive(d.A, d.B, out SyntheticCross? x) ? x!.Symbol : "?"; read.LastRows.TryGetValue(d.Name, out DecisionLine? line); - IReadOnlyList features = line is null ? [] : read.Logistic.Explain(line.Features); + (double pMl, DateTime? pMlUtc, string kind, ScoreExplanation explained) = Score(read, line); BasketVolRow? vol = null; if (line is not null && double.IsFinite(line.SigmaForecast)) { @@ -253,7 +274,7 @@ public static class LearningDiskReader double.IsFinite(ratio) ? Math.Clamp(ratio, strategy.VolScaleMin, strategy.VolScaleMax) : double.NaN, double.NaN, double.NaN, 0, 0, null, -1, "n/d a motore fermo"); } - rows.Add(LearningRows.Basket(d.Name, cross, d.Enabled, d.Enabled ? "Idle" : "Disabled", line?.PMl ?? double.NaN, line?.Ts, line is { BasketId.Length: > 0 }, pMin, features, vol)); + rows.Add(LearningRows.Basket(d.Name, cross, d.Enabled, d.Enabled ? "Idle" : "Disabled", pMl, pMlUtc, kind, pMin, explained, vol)); } LearningStatus status = new(LearningStatus.ModeOf(enabled, c.Active), enabled, weekly, strategy.Learning.Challenger, c.Active, enabled && c.Active, c.Champion, c.Version, @@ -280,40 +301,130 @@ public static class LearningDiskReader }; } - private sealed record DiskModels(LearningCapture Capture, OnlineLogistic Logistic, IReadOnlyDictionary LastRows, IReadOnlyList Warnings); + /// What the files of a stopped bot hold, each part kept for the next reading to fall back on. + private sealed record DiskModels( + LearningCapture Capture, + OnlineLogistic Logistic, + SmallMlp? Mlp, + ThompsonBandit Bandit, + LearningStateData State, + CycleSummary? LastCycle, + DatasetSummary? CycleDataset, + IReadOnlyDictionary LastRows, + IReadOnlyList Warnings); + /// + /// The models of a stopped bot. A file that cannot be read keeps the part last read well + /// (5.1 review) — the bandit, the state, the challenger, the logistic, the last cycle — and + /// the warning says so; never read well, the starting values, and the warning says that. An + /// absent file means the starting values. The labelled count is the training set's. + /// private static DiskModels LoadModels(LearningPaths p, DiskModels? previous) { List warnings = []; string models = p.ModelsDir; - OnlineLogistic logistic = ReadJson(Path.Combine(models, "logreg_current.json"), OnlineLogistic.FromJson, warnings) ?? previous?.Logistic ?? new OnlineLogistic(LearningFeatures.Count); - SmallMlp? mlp = ReadJson(Path.Combine(models, "mlp_current.json"), SmallMlp.FromJson, warnings); - ThompsonBandit bandit = ReadJson(Path.Combine(models, "bandit.json"), static t => ThompsonBandit.FromJson(t), warnings) ?? new ThompsonBandit(3, 42); - LearningStateData state = ReadJson(Path.Combine(models, "learning_state.json"), LearningStateFile.Read, warnings) ?? new LearningStateData(); - CycleSummary? last = null; - DatasetSummary? dataset = null; - if (ReadText(Path.Combine(models, "last_cycle.json")) is { } cycleText && !LearningJson.TryReadCycleFile(cycleText, out last, out dataset)) - { - warnings.Add("last_cycle.json non leggibile: l'ultimo ciclo non è mostrato"); - } + bool before = previous is not null; + OnlineLogistic logistic = Part(Path.Combine(models, "logreg_current.json"), OnlineLogistic.FromJson, before, previous?.Logistic, warnings) ?? new OnlineLogistic(LearningFeatures.Count); + SmallMlp? mlp = Part(Path.Combine(models, "mlp_current.json"), SmallMlp.FromJson, before, previous?.Mlp, warnings); + ThompsonBandit bandit = Part(Path.Combine(models, "bandit.json"), static t => ThompsonBandit.FromJson(t), before, previous?.Bandit, warnings) ?? new ThompsonBandit(3, 42); + LearningStateData state = Part(Path.Combine(models, "learning_state.json"), LearningStateFile.Read, before, previous?.State, warnings) ?? new LearningStateData(); + (CycleSummary? last, DatasetSummary? dataset) = LastCycle(Path.Combine(models, "last_cycle.json"), previous, warnings); - // The labels behind lastNOutcomes and the headline's count: the corrected basket rows. + // The labels behind lastNOutcomes, and the labelled count as the training set counts it + // (a labelled basket with its entry features): the tick's headline says the same (5.1 review). List labelled = []; + int labelledRows = state.LabelledRows; try { labelled = [.. Ledger.ReadBasketsCorrected(p.LedgerDir).Where(static r => r.HasLabel && !r.IsLoneLeg)]; + labelledRows = LearningDataset.Build(p.LedgerDir, DateTime.UtcNow).Summary.LabelledRows; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - warnings.Add($"baskets.csv non leggibile ({ex.Message})"); + warnings.Add($"ledger non leggibile ({ex.Message}): basket etichettati dallo stato salvato"); } double lastOutcomes = labelled.Count == 0 ? double.NaN : labelled.TakeLast(10).Average(static r => r.Label); RollingPerformance rolling = RollingMetrics.Compute(state.Recent, state.AucHistory, lastOutcomes); LearningCapture capture = new(state.Active, state.Champion, state.Version, state.LastCycleUtc, state.LastReport.Length > 0 ? state.LastReport : "nessun ciclo eseguito", - state.LabelsFixedUtc, Math.Max(state.LabelledRows, labelled.Count), [.. state.Entries.Keys], logistic.Summarize(), mlp?.Summarize(last?.ChallengerWins ?? false), + state.LabelsFixedUtc, labelledRows, [.. state.Entries.Keys], logistic.Summarize(), mlp?.Summarize(last?.ChallengerWins ?? false), bandit.Summarize(string.Empty, state.LastProposal, false), rolling, last, dataset, []); - return new DiskModels(capture, logistic, LastRows(Path.Combine(p.LedgerDir, "decisions.jsonl")), warnings); + return new DiskModels(capture, logistic, mlp, bandit, state, last, dataset, LastRows(Path.Combine(p.LedgerDir, "decisions.jsonl")), warnings); + } + + /// last_cycle.json: the last cycle and its dataset; when unreadable, the last good reading (or nothing, never read well), with a warning. + private static (CycleSummary? Last, DatasetSummary? Dataset) LastCycle(string path, DiskModels? previous, List warnings) + { + string why = string.Empty; + try + { + string? text = ReadText(path); + if (text is null) + { + return (null, null); + } + + if (LearningJson.TryReadCycleFile(text, out CycleSummary? last, out DatasetSummary? dataset)) + { + return (last, dataset); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + why = $" ({ex.Message})"; + } + + if (previous is not null) + { + warnings.Add($"last_cycle.json non leggibile{why}: mostro l'ultima lettura buona"); + return (previous.LastCycle, previous.CycleDataset); + } + + warnings.Add($"last_cycle.json non leggibile{why}: l'ultimo ciclo non è mostrato"); + return (null, null); + } + + /// + /// A basket's probability on a stopped bot's page, always with the contributions of the model + /// that gave it (5.1 review). In a position at its last evaluation row: the p it entered with, + /// explained by what was kept with its entry in learning_state.json — or by the saved + /// model when that still gives the same p — and otherwise shown without contributions. Without + /// a position: the row's p when the saved model gives it back for the row's values; else the + /// saved model's p for those values, said to be recomputed (the row's p came from the model of + /// that bar). The MLP champion's p is never explained by w·z. + /// + private static (double P, DateTime? Utc, string Kind, ScoreExplanation Explained) Score(DiskModels read, DecisionLine? line) + { + if (line is null) + { + return (double.NaN, null, string.Empty, ScoreExplanation.None); + } + + bool logisticChampion = read.State.Champion != "mlp16" || read.Mlp is null; + if (line.BasketId.Length > 0) + { + if (!read.State.Entries.TryGetValue(line.BasketId, out EntryMemory? entry) || !double.IsFinite(entry.PAtEntry)) + { + // No entry kept for it (its close settled, or it was never remembered): the row's p, unexplained. + return (line.PMl, line.Ts, BasketLearningRow.KindAtEntry, ScoreExplanation.None); + } + + ScoreExplanation kept = entry.Explained(); + if (!kept.Explains(entry.PAtEntry) && logisticChampion && read.Logistic.Score(entry.Features) is { } now && now.Explains(entry.PAtEntry)) + { + kept = now; + } + + return (entry.PAtEntry, entry.Utc == default ? line.Ts : entry.Utc, BasketLearningRow.KindAtEntry, kept); + } + + ScoreExplanation today = logisticChampion ? read.Logistic.Score(line.Features) : ScoreExplanation.None; + if (today.Explains(line.PMl) || !double.IsFinite(today.P)) + { + return (line.PMl, line.Ts, BasketLearningRow.KindLastBar, today); + } + + return (today.P, line.Ts, BasketLearningRow.KindRecomputed, today); } /// Each basket's last evaluation row, from the last 64 KB of the current month's ledger (a partial first or last line is skipped). @@ -554,8 +665,9 @@ public static class LearningDiskReader /// /// The training set of the ledger as it is now, with its warnings: recomputed when a basket - /// row was written, a decision file appeared, or at most once an hour (a correction line). - /// Null when the ledger folder does not exist. + /// row was written, a decision file appeared, a P&L correction or the mask of + /// lastNOutcomes was written (5.1 review: both read incrementally, so the check is + /// cheap), or at most once an hour. Null when the ledger folder does not exist. /// public static (DatasetSummary? Summary, IReadOnlyList Warnings) ReadDataset(LearningPaths p, DateTime nowUtc) { @@ -566,7 +678,10 @@ public static class LearningDiskReader } string baskets = Path.Combine(p.LedgerDir, "baskets.csv"); - string stamp = StampOf([baskets]) + "|" + string.Join(',', Ledger.DecisionFiles(p.LedgerDir).Select(Path.GetFileName)) + "|" + nowUtc.ToString("yyyyMMddHH", CultureInfo.InvariantCulture); + int corrections = Ledger.ReadPnlCorrections(p.LedgerDir).Count; + DateTime mask = Ledger.ReadFeatureMaskUntil(p.LedgerDir, LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]); + string stamp = StampOf([baskets]) + "|" + string.Join(',', Ledger.DecisionFiles(p.LedgerDir).Select(Path.GetFileName)) + + string.Create(CultureInfo.InvariantCulture, $"|{corrections}|{mask.Ticks}|{nowUtc:yyyyMMddHH}"); LearningDataset.Result r = Cached("dataset|" + p.LedgerDir, stamp, () => LearningDataset.Build(p.LedgerDir, nowUtc)); return (r.Summary, r.Warnings); } @@ -575,13 +690,22 @@ public static class LearningDiskReader // The tick of a stopped engine // ----------------------------------------------------------------------- - /// The tick's few numbers of a stopped engine, from learning_state.json alone (cheap: read again only when it changes). + /// + /// The tick's few numbers of a stopped engine, from learning_state.json alone (cheap: read + /// again only when it changes). A file that cannot be read keeps the last good reading, as the page does. + /// public static LearningHeadline Headline(LearningPaths p, BasketStrategyConfig strategy, bool cycleRunning, DateTime nowUtc) { ArgumentNullException.ThrowIfNull(p); ArgumentNullException.ThrowIfNull(strategy); string path = Path.Combine(p.ModelsDir, "learning_state.json"); - LearningStateData state = CachedNoWait("headline|" + p.DataDir, StampOf([path]), () => ReadJson(path, LearningStateFile.Read, []) ?? new LearningStateData()); + string key = "headline|" + p.DataDir; + LearningStateData state = CachedNoWait(key, StampOf([path]), () => ReadJson(path, LearningStateFile.Read) switch + { + ({ } read, _) => read, + (null, null) => new LearningStateData(), + _ => Last(key) ?? new LearningStateData(), + }); double auc = ModelEvaluator.RollingAuc(state.Recent, RollingMetrics.Window); return new LearningHeadline(LearningStatus.ModeOf(strategy.Learning.Enabled, state.Active), state.LabelledRows, ModelEvaluator.MinRowsForActivation, auc, state.LastProposal?.Preset ?? string.Empty, "EWMA", cycleRunning, 0); diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningFiles.cs b/Encelado/src/Encelado.Engine/Baskets/LearningFiles.cs index 025a903..f589585 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningFiles.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningFiles.cs @@ -62,8 +62,30 @@ public static class AtomicFile } } -/// An entry waiting for its outcome: the features at the decision and the probability the champion gave then (NaN when it had seen nothing yet). -public sealed record EntryMemory(double[] Features, double PAtEntry, DateTime Utc); +/// +/// An entry waiting for its outcome: the features at the decision and the probability the +/// champion gave then (NaN when it had seen nothing yet). Since the 5.1 review also what made +/// that probability — the standardised values, the contributions and the intercept of the +/// model of that moment — so the page explains an open basket's p with the model that gave it, +/// whatever the model learnt since; null for an entry remembered before (or by the MLP champion). +/// +public sealed record EntryMemory(double[] Features, double PAtEntry, DateTime Utc, double[]? Z = null, double[]? Contributions = null, double Intercept = double.NaN) +{ + /// An entry with the explanation of its probability, when there is one. + public static EntryMemory Of(double[] features, double pAtEntry, DateTime utc, ScoreExplanation? explained) + { + ArgumentNullException.ThrowIfNull(features); + return explained is { Features.Count: > 0 } x && x.Explains(pAtEntry) + ? new EntryMemory([.. features], pAtEntry, utc, [.. x.Features.Select(static f => f.Z)], [.. x.Features.Select(static f => f.Contribution)], x.Intercept) + : new EntryMemory([.. features], pAtEntry, utc); + } + + /// The probability at entry with what made it; 's contributions when the entry kept none. + public ScoreExplanation Explained() => + Z is { } z && Contributions is { } c && z.Length == Features.Length && c.Length == Features.Length && double.IsFinite(Intercept) + ? new ScoreExplanation(PAtEntry, Intercept, OnlineLogistic.Rebuild(Features, z, c)) + : new ScoreExplanation(PAtEntry, double.NaN, []); +} /// What data/models/learning_state.json holds. public sealed record LearningStateData @@ -80,7 +102,7 @@ public sealed record LearningStateData public DateTime? LabelsFixedUtc { get; init; } - /// Labelled baskets counted when the file was written (the page of a stopped bot reads it; the engine recounts from the ledger). + /// Labelled baskets, as the training set counts them, when the file was written (the tick of a stopped bot reads it; the engine and the page count the ledger again). public int LabelledRows { get; init; } /// (p, label) of the closed baskets, the p given at their entry, oldest first. @@ -163,6 +185,14 @@ public static class LearningStateFile } w.WriteString("utc", e.Utc == default ? string.Empty : Utc(e.Utc)); + if (e.Z is { } z && e.Contributions is { } c && double.IsFinite(e.Intercept)) + { + // What made p (5.1 review): full precision, the page adds them up to its logit. + Numbers(w, "z", z); + Numbers(w, "c", c); + w.WriteNumber("b", e.Intercept); + } + w.WriteEndObject(); } @@ -240,7 +270,9 @@ public static class LearningStateFile else if (p.Value.ValueKind == JsonValueKind.Object && p.Value.TryGetProperty("f", out JsonElement f) && f.ValueKind == JsonValueKind.Array) { double pe = p.Value.TryGetProperty("p", out JsonElement pv) && pv.ValueKind == JsonValueKind.Number ? pv.GetDouble() : double.NaN; - entries[p.Name] = new EntryMemory([.. f.EnumerateArray().Select(static x => x.GetDouble())], pe, Time(p.Value, "utc") ?? default); + double b = p.Value.TryGetProperty("b", out JsonElement bv) && bv.ValueKind == JsonValueKind.Number ? bv.GetDouble() : double.NaN; + entries[p.Name] = new EntryMemory([.. f.EnumerateArray().Select(static x => x.GetDouble())], pe, Time(p.Value, "utc") ?? default, + NumbersOf(p.Value, "z"), NumbersOf(p.Value, "c"), b); } } } @@ -270,6 +302,30 @@ public static class LearningStateFile }; } + private static void Numbers(Utf8JsonWriter w, string name, IReadOnlyList values) + { + w.WriteStartArray(name); + foreach (double v in values) + { + if (double.IsFinite(v)) + { + w.WriteNumberValue(v); + } + else + { + w.WriteNullValue(); + } + } + + w.WriteEndArray(); + } + + /// An array of numbers of an entry (null as NaN); null when absent. + private static double[]? NumbersOf(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array + ? [.. a.EnumerateArray().Select(static x => x.ValueKind == JsonValueKind.Number ? x.GetDouble() : double.NaN)] + : null; + private static string Utc(DateTime t) => DateTime.SpecifyKind(t, DateTimeKind.Utc).ToString("O", CultureInfo.InvariantCulture); private static string Str(JsonElement e, string name) => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs index 20fc62f..3bcef8e 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs @@ -99,7 +99,7 @@ public sealed class LearningState : IDisposable _logistic = new OnlineLogistic(LearningFeatures.Count); _bandit = new ThompsonBandit(3, 42); Load(); - SeedOutcomesFromLedger(); + SeedFromLedger(); } public bool Active => _active; @@ -188,21 +188,54 @@ public sealed class LearningState : IDisposable } /// - /// A basket opened: its features and the probability the champion gave at the decision - /// wait for the outcome. Saved at once (5.1): a crash between the entry and the close must - /// not lose what the model will learn from. + /// The champion's probability for a candidate entry with what made it, in one read under the + /// lock (5.1 review): the contributions and the intercept of the logistic of this moment add + /// up to its logit, whatever the model learns afterwards. The engine keeps the pair, so the + /// page never explains a probability with a model that did not give it. NaN as + /// ; no contributions for the MLP champion (w·z does not explain it). /// - public void RememberEntry(string basketId, double[] features, double pAtEntry = double.NaN, DateTime? utc = null) + public ScoreExplanation Score(double[] features) + { + ArgumentNullException.ThrowIfNull(features); + lock (_gate) + { + if (_champion == "mlp16" && _challenger is not null) + { + return new ScoreExplanation(_challenger.Predict(features), double.NaN, []); + } + + return _logistic.Seen == 0 && _challenger is null + ? ScoreExplanation.None + : new ScoreExplanation(_logistic.Predict(features), _logistic.Bias, _logistic.Explain(features)); + } + } + + /// + /// A basket opened: its features and the probability the champion gave at the decision + /// wait for the outcome, with what made that probability when it is given (5.1 review: the + /// page explains an open basket with the model of its entry). Saved at once (5.1): a crash + /// between the entry and the close must not lose what the model will learn from. + /// + public void RememberEntry(string basketId, double[] features, double pAtEntry = double.NaN, DateTime? utc = null, ScoreExplanation? explained = null) { ArgumentException.ThrowIfNullOrEmpty(basketId); ArgumentNullException.ThrowIfNull(features); lock (_gate) { - _entries[basketId] = new EntryMemory([.. features], pAtEntry, utc ?? DateTime.UtcNow); + _entries[basketId] = EntryMemory.Of(features, pAtEntry, utc ?? DateTime.UtcNow, explained); SaveStateFileSafe(); } } + /// The entry remembered for a basket (read only), or null: what a restart gives back to an open basket. + public EntryMemory? EntryOf(string basketId) + { + lock (_gate) + { + return _entries.TryGetValue(basketId, out EntryMemory? e) ? e : null; + } + } + /// A basket whose outcome will never teach (its P&L stayed an estimate): its entry is dropped. public bool Forget(string basketId) { @@ -220,14 +253,16 @@ public sealed class LearningState : IDisposable /// /// A basket closed with the venue's number: the shadow model learns, the rolling AUC takes - /// the probability given at its entry, the bandit is rewarded. Everything is saved. + /// the probability given at its entry, the bandit is rewarded. Everything is saved, even + /// when the registry line of a deactivation cannot be written (5.1 review). The labelled + /// count grows only with a remembered entry: a basket without its entry features is not a + /// training row (the count is the dataset's, ). /// public void Observe(string basketId, int label, int volContext, PresetName preset, DateTime? nowUtc = null) { DateTime now = nowUtc ?? DateTime.UtcNow; lock (_gate) { - _labelledRows++; _lastOutcomes.Add(label); if (_lastOutcomes.Count > 100) { @@ -239,6 +274,7 @@ public sealed class LearningState : IDisposable _rolling = null; if (_entries.Remove(basketId, out EntryMemory? entry)) { + _labelledRows++; if (double.IsFinite(entry.PAtEntry)) { _recent.Add((entry.PAtEntry, label)); @@ -264,8 +300,8 @@ public sealed class LearningState : IDisposable { _active = false; Log.Warn(string.Create(CultureInfo.InvariantCulture, $"meta-modello: AUC mobile {_rollingAuc:F3} sotto {ModelEvaluator.DeactivationAuc:F2}: torna in shadow mode")); - AppendKnowledge("models_registry.csv", LearningKnowledge.RegistryHeader, - [string.Create(CultureInfo.InvariantCulture, $"v{_version};{now:O};{_champion};{_logistic.Seen};{_rollingAuc:F3};;;shadow;AUC mobile su 100 basket sotto {ModelEvaluator.DeactivationAuc:F2}")]); + string line = string.Create(CultureInfo.InvariantCulture, $"v{_version};{now:O};{_champion};{_logistic.Seen};{_rollingAuc:F3};;;shadow;AUC mobile su 100 basket sotto {ModelEvaluator.DeactivationAuc:F2}"); + Try("models_registry.csv", () => AppendKnowledge("models_registry.csv", LearningKnowledge.RegistryHeader, [line])); } } @@ -383,6 +419,10 @@ public sealed class LearningState : IDisposable _lastCycleUtc = nowUtc; _lastDataset = result.Dataset.Summary; _datasetWarnings = result.Dataset.Warnings; + + // The labelled count starts again from the cycle's dataset, plus what closed while it trained (5.1 review). + HashSet inDataset = new(result.Dataset.Rows.Select(static r => r.BasketId), StringComparer.Ordinal); + _labelledRows = result.Dataset.Summary.LabelledRows + _observedDuringCycle.Count(o => !inDataset.Contains(o.Id)); if (result.Training is not { } t) { _observedDuringCycle.Clear(); @@ -673,21 +713,61 @@ public sealed class LearningState : IDisposable } } - /// The recent outcomes behind lastNOutcomes: the last hundred baskets whose P&L the venue established. - private void SeedOutcomesFromLedger() + /// + /// What the ledger says now, read again after the startup's check of the realised results + /// (5.1 review): the corrections it appended change labels, and the session must not go on + /// with the outcomes and the count read before them — every evaluation row it writes carries + /// lastNOutcomes, and that row is never masked. Done whether or not the models are + /// retired afterwards. The count is saved for the page of a stopped bot. + /// + public void Reseed() + { + lock (_gate) + { + SeedFromLedger(); + SaveStateFileSafe(); + } + } + + /// + /// The recent outcomes behind lastNOutcomes — the last hundred baskets whose P&L the + /// venue established — and the labelled count, counted as the training set counts it (a + /// labelled basket with its entry features, ), so the tick's + /// headline and the page's dataset say the same number (5.1 review). A ledger that cannot be + /// read changes nothing. + /// + private void SeedFromLedger() + { + if (RecentOutcomes(_ledgerDir) is not { } outcomes) + { + return; + } + + try + { + _labelledRows = LearningDataset.Build(_ledgerDir, DateTime.UtcNow).Summary.LabelledRows; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warn($"apprendimento: basket etichettati non ricontati ({ex.Message})"); + } + + _lastOutcomes.Clear(); + _lastOutcomes.AddRange(outcomes); + _rolling = null; + } + + /// The labels of the last hundred baskets of the corrected ledger, oldest first; null when it cannot be read (an absent ledger is empty). + private static List? RecentOutcomes(string ledgerDir) { try { - List labelled = [.. Ledger.ReadBasketsCorrected(_ledgerDir).Where(static r => r.HasLabel && !r.IsLoneLeg)]; - _labelledRows = labelled.Count; - foreach (BasketOutcomeRow r in labelled.TakeLast(100)) - { - _lastOutcomes.Add(r.Label); - } + return [.. Ledger.ReadBasketsCorrected(ledgerDir).Where(static r => r.HasLabel && !r.IsLoneLeg).TakeLast(100).Select(static r => r.Label)]; } - catch (IOException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - // The ledger may be absent on a first run. + Log.Warn($"apprendimento: esiti recenti non letti dal ledger ({ex.Message})"); + return null; } } @@ -700,10 +780,18 @@ public sealed class LearningState : IDisposable /// labels from the venue); the challenger goes away until the next cycle; the bandit /// restarts from its prior, because the volatility context of its past rewards is not in /// the ledger. One line in models_registry.csv says it. Returns false when already done. + /// + /// All or nothing (5.1 review): every read and every move comes first, and a failure there + /// throws with the models untouched, in memory and on disk (the next start tries again). + /// Once the files are aside the new models are swapped in and saved with the mark that + /// the retire is done; the registry line is the only part that may be missing, and a + /// warning says so — a retire is never repeated over the rewards learnt after it. + /// /// public bool RetireAndReplay(DateTime nowUtc, string reason) { List replay = BuildDataset(); + List? outcomes = RecentOutcomes(_ledgerDir); lock (_gate) { if (_labelsFixedUtc != default) @@ -736,38 +824,36 @@ public sealed class LearningState : IDisposable File.Delete(mlpCurrent); } - _logistic = new OnlineLogistic(LearningFeatures.Count); + // The files are aside: from here on nothing throws, and the new state goes in whole. + OnlineLogistic logistic = new(LearningFeatures.Count); + foreach (LabelledBasket b in replay) + { + logistic.Update(b.Features, b.Label); + } + + _logistic = logistic; _challenger = null; _champion = "logistica"; _bandit = new ThompsonBandit(3, 42); _lastProposal = null; _recent.Clear(); _aucHistory.Clear(); - _lastOutcomes.Clear(); _active = false; _rollingAuc = double.NaN; _lastCycle = null; _lastDataset = null; _datasetWarnings = []; - foreach (LabelledBasket b in replay) - { - _logistic.Update(b.Features, b.Label); - _lastOutcomes.Add(b.Label); - } - - while (_lastOutcomes.Count > 100) - { - _lastOutcomes.RemoveAt(0); - } - + _labelledRows = replay.Count; + _lastOutcomes.Clear(); + _lastOutcomes.AddRange(outcomes ?? [.. replay.TakeLast(100).Select(static b => b.Label)]); _logisticSummary = null; _mlpSummary = null; _banditSummary = null; _rolling = null; _lastReport = string.Create(CultureInfo.InvariantCulture, $"modelli ritirati il {nowUtc:yyyy-MM-dd HH:mm} UTC (etichette dai proceeds): logistica rifatta su {replay.Count} basket con le etichette corrette, bandit dal prior"); - AppendKnowledge("models_registry.csv", LearningKnowledge.RegistryHeader, - [string.Create(CultureInfo.InvariantCulture, $"v{_version};{nowUtc:O};logistica+bandit;{replay.Count};;;;ritirato;{LearningKnowledge.Clean(reason)}")]); _labelsFixedUtc = nowUtc; + string line = string.Create(CultureInfo.InvariantCulture, $"v{_version};{nowUtc:O};logistica+bandit;{replay.Count};;;;ritirato;{LearningKnowledge.Clean(reason)}"); + Try("models_registry.csv", () => AppendKnowledge("models_registry.csv", LearningKnowledge.RegistryHeader, [line])); Save(); } diff --git a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs index 83f7ee8..69b6780 100644 --- a/Encelado/src/Encelado.Engine/Baskets/Ledger.cs +++ b/Encelado/src/Encelado.Engine/Baskets/Ledger.cs @@ -325,15 +325,22 @@ public sealed class Ledger : IDisposable /// The time until which is unreliable (feature_inaffidabile); when never marked. public DateTime ReadFeatureMaskUntil(string feature) => ReadFeatureMaskUntil(_directory, feature); - /// The same, for a ledger folder read by someone who is not its writer (the learning cycle, the disk reader). + /// + /// The same, for a ledger folder read by someone who is not its writer (the learning cycle, the + /// disk reader). Read incrementally with the P&L corrections (5.1 review): the page's dataset + /// asks at every request whether a mark appeared. + /// public static DateTime ReadFeatureMaskUntil(string directory, string feature) { DateTime until = DateTime.MinValue; - foreach (string line in DecisionLines(directory, LedgerMarkers.FeatureUnreliable)) + foreach (string file in DecisionFiles(directory)) { - if (LedgerMarkers.TryParseFeatureMask(line, out string f, out DateTime t) && f == feature && t > until) + foreach ((string f, DateTime t) in CorrectionScan.ReadMasks(file)) { - until = t; + if (f == feature && t > until) + { + until = t; + } } } @@ -466,11 +473,11 @@ public sealed class Ledger : IDisposable DateTime.TryParse(Str(e, name), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : default; /// - /// The P&L corrections of one decision file, read incrementally: the ledger's files - /// only grow, so after the first reading only the bytes appended since are scanned - /// (the Storico page asks often; a month of evaluations is tens of megabytes). A file - /// whose first bytes changed, or that got shorter, is another file (the month rotated) - /// and is read again from the start. + /// The P&L corrections and the feature masks of one decision file, read incrementally: + /// the ledger's files only grow, so after the first reading only the bytes appended since + /// are scanned (the Storico and Apprendimento pages ask often; a month of evaluations is + /// tens of megabytes). A file whose first bytes changed, or that got shorter, is another + /// file (the month rotated) and is read again from the start. /// private static class CorrectionScan { @@ -480,13 +487,19 @@ public sealed class Ledger : IDisposable { public readonly Lock Gate = new(); public readonly List Items = []; + public readonly List<(string Feature, DateTime Until)> Masks = []; public long Offset; public byte[] Head = []; } private static readonly System.Collections.Concurrent.ConcurrentDictionary Files = new(StringComparer.OrdinalIgnoreCase); - public static List Read(string path) + public static List Read(string path) => Scan>(path, static e => [.. e.Items]); + + /// The feature_inaffidabile marks of the file: feature and time until which it is unreliable. + public static List<(string Feature, DateTime Until)> ReadMasks(string path) => Scan>(path, static e => [.. e.Masks]); + + private static T Scan(string path, Func take) { Entry entry = Files.GetOrAdd(Path.GetFullPath(path), static _ => new Entry()); lock (entry.Gate) @@ -500,6 +513,7 @@ public sealed class Ledger : IDisposable { entry.Offset = 0; entry.Items.Clear(); + entry.Masks.Clear(); } entry.Head = head; @@ -511,24 +525,33 @@ public sealed class Ledger : IDisposable int end = buffer.Length == 0 ? -1 : Array.LastIndexOf(buffer, (byte)'\n'); if (end >= 0) { - foreach (string line in Encoding.UTF8.GetString(buffer, 0, end + 1).Split('\n')) + foreach (string raw in Encoding.UTF8.GetString(buffer, 0, end + 1).Split('\n')) { - if (PnlCorrectionRecord.TryParse(line.TrimEnd('\r')) is { } c) + string line = raw.TrimEnd('\r'); + if (PnlCorrectionRecord.TryParse(line) is { } c) { entry.Items.Add(c); } + else if (LedgerMarkers.TryParseFeatureMask(line, out string feature, out DateTime until)) + { + entry.Masks.Add((feature, until)); + } } entry.Offset += end + 1; } } } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + // Rotated away or never written: nothing in it. + } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warn($"ledger: correzioni non lette da {Path.GetFileName(path)} ({ex.Message})"); } - return [.. entry.Items]; + return take(entry); } } diff --git a/Encelado/src/Encelado.Engine/Engine/SampleData.Learning.cs b/Encelado/src/Encelado.Engine/Engine/SampleData.Learning.cs index 84c6f4c..97093b6 100644 --- a/Encelado/src/Encelado.Engine/Engine/SampleData.Learning.cs +++ b/Encelado/src/Encelado.Engine/Engine/SampleData.Learning.cs @@ -181,11 +181,11 @@ public static partial class SampleData List baskets = []; foreach (BasketView b in view.Baskets) { - IReadOnlyList features = b.MlFeatures is { } f ? core.Logistic.Explain([.. f]) : []; + ScoreExplanation explained = b.MlFeatures is { } f ? core.Logistic.Score([.. f]) : ScoreExplanation.None; int context = ThompsonBandit.VolatilityContext(b.Vol.ForecastSigma, core.VolHistory); string state = !b.Enabled && b.Position is null && b.Pending is null && b.State == BasketState.Idle ? "Disabled" : b.State.ToString(); DateTime pUtc = b.Position is { } pos ? pos.OpenedUtc.AddMinutes(-1) : b.Pending is { } pending ? pending.DecidedUtc : barClose; - baskets.Add(LearningRows.Basket(b.Name, b.Cross, b.Enabled, state, b.PMl, pUtc, b.IsOpen || b.Pending is not null, pMin, features, + baskets.Add(LearningRows.Basket(b.Name, b.Cross, b.Enabled, state, b.PMl, pUtc, LearningRows.KindOf(b.IsOpen || b.Pending is not null), pMin, explained, LearningRows.Vol(b.Vol, context, strategy.VolScaleMin, strategy.VolScaleMax))); } diff --git a/Encelado/src/Encelado.Server/Web/wwwroot/js/pages/basket.js b/Encelado/src/Encelado.Server/Web/wwwroot/js/pages/basket.js index 7348ed9..ac5f95c 100644 --- a/Encelado/src/Encelado.Server/Web/wwwroot/js/pages/basket.js +++ b/Encelado/src/Encelado.Server/Web/wwwroot/js/pages/basket.js @@ -346,19 +346,23 @@ function tabMl(d) { scroller: o.feat, rowKey: r => r.name, compact: true, caption: 'Feature', columns: [{ key: 'l', label: 'Feature', minPx: 140, text: r => r.label || r.name, tip: r => r.name }, { key: 'v', label: 'Valore', width: '90px', cls: 'num', text: r => (isNum(r.value) ? num(r.value, 3) : '—') }] }); + o.featTitle = el('h3', null, 'Feature all\'ultima barra'); pane.replaceChildren(el('div', { class: 'stat' }, el('div', { class: 'l' }, 'p_ML: probabilità di chiudere in utile', o.mode), o.p, o.thr), - card('Contributi più forti (peso × valore standardizzato)', o.bars), card('Feature all\'ultima barra', o.feat)); + card('Contributi più forti (peso × valore standardizzato)', o.bars), el('div', { class: 'card' }, o.featTitle, o.feat)); return o; }); + // While the basket holds (or waits for) a position its vector and p_ML are the entry's, not the last bar's. + setText(v.featTitle, d.position || d.pending ? 'Feature all\'ingresso' : 'Feature all\'ultima barra'); const ml = d.ml || {}; setText(v.p, isNum(ml.pMl) ? num(ml.pMl * 100, 1) + ' %' : '—'); setTag(v.mode, ml.active ? 'attivo' : 'ombra', ml.active ? 'ok' : '', ml.active ? 'Il modello filtra gli ingressi' : 'Registrata nel ledger, non filtra'); setText(v.thr, `soglia d'ingresso ${num((d.thresholds?.mlMinProbability ?? 0) * 100, 0)} %` + (ml.active ? '' : ' · in ombra non blocca niente')); const lb = learning?.baskets?.find(x => x.basket === d.name); const contrib = (lb?.topContributions || []).filter(x => isNum(x.contribution)); - fill(v.bars, learning ? contrib.map(x => x.name + x.contribution).join() : 'wait', () => (!learning ? el('div', { class: 'small' }, 'Lettura del rapporto di apprendimento…') + const unexplained = isNum(lb?.pMl) && !contrib.length; + fill(v.bars, learning ? contrib.map(x => x.name + x.contribution).join() + unexplained : 'wait', () => (!learning ? el('div', { class: 'small' }, 'Lettura del rapporto di apprendimento…') : contrib.length ? weightBars(contrib.map(x => ({ label: x.label || x.name, value: x.contribution, tip: `${x.label || x.name}: valore ${isNum(x.value) ? num(x.value, 3) : '—'}, z ${isNum(x.z) ? num(x.z, 2) : '—'}, contributo ${sgn(x.contribution, 3)}` }))) - : el('div', { class: 'small' }, 'Nessun contributo disponibile per questo basket.'))); + : el('div', { class: 'small' }, unexplained ? 'Nessun contributo che spieghi questa p_ML: l\'ha data un modello che nel frattempo è cambiato senza salvarne la spiegazione, o l\'MLP.' : 'Nessun contributo disponibile per questo basket.'))); v.grid.setRows(ml.features || []); } diff --git a/Encelado/tests/Encelado.Tests/LearningReportTests.cs b/Encelado/tests/Encelado.Tests/LearningReportTests.cs index 9753a75..ea766e4 100644 --- a/Encelado/tests/Encelado.Tests/LearningReportTests.cs +++ b/Encelado/tests/Encelado.Tests/LearningReportTests.cs @@ -173,7 +173,9 @@ public class LearningReadersTests Assert.InRange(moderate.Mean, moderate.Low95, moderate.High95); Assert.True(moderate.BestInContext); Assert.Equal("vol media", moderate.ContextLabel); - Assert.All(s.Arms.GroupBy(static a => a.Context), static g => Assert.Single(g, static a => a.BestInContext)); + + // The only best arm is the one with rewards that beat the prior: context 0 was never tried, and in context 2 the one loss leaves the untried arms ahead. + Assert.Same(moderate, Assert.Single(s.Arms, static a => a.BestInContext)); BanditArm prior = s.Arms.Single(static a => a.Context == 0 && a.Preset == "Conservative"); Assert.Equal(0.025, prior.Low95, 6); Assert.Equal(0.975, prior.High95, 6); @@ -720,15 +722,23 @@ public sealed class LearningDiskReaderTests : TempFolderTests Assert.False(r.Schedule.Running); } + /// + /// A stopped bot's page takes each basket's last evaluation row: its p when the saved model gives it + /// back for the row's values, with the contributions of that model; otherwise the saved model's p for + /// those values, said to be recomputed (5.1 review: the contributions always explain the p shown). + /// [Fact] public void TheLastBarRowOfEachBasketGivesItsProbabilityWhileStopped() { Fixture(35); + OnlineLogistic saved = OnlineLogistic.FromJson(File.ReadAllText(Path.Combine(Root, "models", "logreg_current.json"))); + BasketEvaluation e = new() { Z = 1.1, RhoW = -0.8 }; + BasketContext ctx = CorrectionScenery.Context(LearningScenery.T0.AddDays(21)) with { Name = "EURUSD/USDCHF", BasketId = "EURUSD/USDCHF", SigmaForecast = 0.0004, SigmaAverage30d = 0.0005 }; + BasketDecision skip = new(DecisionKind.Skip, false, null, ["no_signal"], "niente", e, null); + double p = saved.Predict(LearningFeatures.ReadDecisionLine(Ledger.Serialize("run", "Demo", "MODERATE", "h", ctx, skip, "skip", null, null))!.Features); using (Ledger ledger = new(LedgerDir)) { - BasketEvaluation e = new() { Z = 1.1, RhoW = -0.8 }; - BasketContext ctx = CorrectionScenery.Context(LearningScenery.T0.AddDays(21)) with { Name = "EURUSD/USDCHF", BasketId = "EURUSD/USDCHF", PMl = 0.47, SigmaForecast = 0.0004, SigmaAverage30d = 0.0005 }; - ledger.Decision("run", "Demo", "MODERATE", "h", ctx, new BasketDecision(DecisionKind.Skip, false, null, ["no_signal"], "niente", e, null), "skip", null); + ledger.Decision("run", "Demo", "MODERATE", "h", ctx with { PMl = p }, skip, "skip", null); } // A line still being written at the end of the file. @@ -736,15 +746,30 @@ public sealed class LearningDiskReaderTests : TempFolderTests LearningLiveReport part = LearningDiskReader.ReadModels(Paths, LearningScenery.Strategy(), CycleRunStatus.Idle, LearningScenery.T0.AddDays(21)); BasketLearningRow row = part.Baskets.Single(static b => b.Basket == "EURUSD/USDCHF"); - Assert.Equal(0.47, row.PMl, 9); + Assert.Equal(p, row.PMl, 6); Assert.Equal(BasketLearningRow.KindLastBar, row.PMlKind); - Assert.True(row.WouldBeFiltered); + Assert.Equal(p < 0.55, row.WouldBeFiltered); Assert.Equal(LearningFeatures.Count, row.Features.Count); Assert.Equal(5, row.TopContributions.Count); + Assert.Equal(saved.Bias, row.Intercept, 9); + Assert.Equal(p, OnlineLogistic.Sigmoid(row.Features.Sum(static f => f.Contribution) + row.Intercept), 9); Assert.NotNull(row.Vol); Assert.Equal(0.8, row.Vol!.VolRatio, 9); Assert.Equal(0.8, row.Vol.ZInScale, 9); Assert.True(double.IsNaN(part.Baskets.Single(static b => b.Basket == "AUDUSD/USDCAD").PMl)); + + // A row whose p the saved model does not give (the model of that bar learnt something else): recomputed, and said so. + using (Ledger ledger = new(LedgerDir)) + { + ledger.Decision("run", "Demo", "MODERATE", "h", ctx with { TimeUtc = ctx.TimeUtc.AddMinutes(15), PMl = 0.47 }, skip, "skip", null); + } + + BasketLearningRow recomputed = LearningDiskReader.ReadModels(Paths, LearningScenery.Strategy(), CycleRunStatus.Idle, LearningScenery.T0.AddDays(21).AddMinutes(20)) + .Baskets.Single(static b => b.Basket == "EURUSD/USDCHF"); + Assert.Equal(BasketLearningRow.KindRecomputed, recomputed.PMlKind); + Assert.Equal(p, recomputed.PMl, 6); + Assert.Equal(ctx.TimeUtc.AddMinutes(15), recomputed.PMlUtc); + Assert.Equal(p, OnlineLogistic.Sigmoid(recomputed.Features.Sum(static f => f.Contribution) + recomputed.Intercept), 9); } [Fact] @@ -1007,7 +1032,7 @@ public sealed class SampleLearningApiTests : ApiHostFixture Assert.Equal(5, baskets.Length); foreach (JsonElement b in baskets) { - HasKeys(b, "basket", "cross", "enabled", "state", "pMl", "pMlUtc", "pMlKind", "wouldBeFiltered", "topContributions", "features", "vol"); + HasKeys(b, "basket", "cross", "enabled", "state", "pMl", "pMlUtc", "pMlKind", "intercept", "wouldBeFiltered", "topContributions", "features", "vol"); Assert.Equal(JsonValueKind.Null, b.GetProperty("features").ValueKind); Assert.InRange(b.GetProperty("topContributions").GetArrayLength(), 1, 5); HasKeys(b.GetProperty("topContributions")[0], "index", "name", "label", "value", "z", "contribution"); @@ -1053,7 +1078,11 @@ public sealed class SampleLearningApiTests : ApiHostFixture { JsonElement features = b.GetProperty("features"); Assert.Equal(LearningFeatures.Count, features.GetArrayLength()); - double logit = features.EnumerateArray().Sum(static f => f.GetProperty("contribution").GetDouble()) + bias; + + // The intercept of the model that gave pMl (the sample's model is the one of the page). + double intercept = b.GetProperty("intercept").GetDouble(); + Assert.Equal(bias, intercept, 5); + double logit = features.EnumerateArray().Sum(static f => f.GetProperty("contribution").GetDouble()) + intercept; Assert.InRange(Math.Abs(b.GetProperty("pMl").GetDouble() - OnlineLogistic.Sigmoid(logit)), 0, 1e-3); } } diff --git a/Encelado/tests/Encelado.Tests/LearningReviewTests.cs b/Encelado/tests/Encelado.Tests/LearningReviewTests.cs new file mode 100644 index 0000000..ebf0053 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/LearningReviewTests.cs @@ -0,0 +1,718 @@ +using System.Globalization; +using System.Text; +using System.Text.Json.Nodes; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.History; +using Encelado.Core.Baskets.Learning; +using Encelado.Core.Broker; +using Encelado.Engine.Baskets; +using Encelado.Engine.Configuration; + +namespace Encelado.Tests; + +/// Scenery of the learning review: a trained logistic, evaluation rows of one basket with a chosen p, a model that moves. +internal static class ReviewScenery +{ + public const string Pair = "EURUSD/USDCHF"; + + public static readonly DateTime T0 = new(2026, 9, 30, 9, 0, 0, DateTimeKind.Utc); + + /// A logistic that has learnt a rule on 400 random rows, so its weights and its standardiser are far from zero. + public static OnlineLogistic Trained(int seed = 42) + { + OnlineLogistic model = new(LearningFeatures.Count); + Random rng = new(seed); + for (int i = 0; i < 400; i++) + { + double[] x = new double[LearningFeatures.Count]; + for (int j = 0; j < x.Length; j++) + { + x[j] = (rng.NextDouble() * 4) - 2; + } + + model.Update(x, x[0] + (0.5 * x[1]) > 0 ? 1 : 0); + } + + return model; + } + + public static BasketContext Ctx(DateTime t, double pMl) + { + Instrument eurusd = new(1, "EURUSD", "EUR/USD", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1], true, true, 0, 50, ""); + Instrument usdchf = new(6, "USDCHF", "USD/CHF", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1], true, true, 0, 50, ""); + return new BasketContext + { + TimeUtc = t, + BasketId = Pair, + Name = Pair, + Cross = SyntheticCross.Derive("EURUSD", "USDCHF"), + A = new SymbolSeries(eurusd, TimeSpan.FromMinutes(15)), + B = new SymbolSeries(usdchf, TimeSpan.FromMinutes(15)), + Equity = 149_000, + PipValueUsdA = 1, + PipValueUsdB = 1, + UsdPerQuoteA = 1, + UsdPerQuoteB = 1, + Mid = static _ => null, + LastOutcomes = 0.4, + PMl = pMl, + }; + } + + /// An evaluation row of the basket, as the engine writes it at a bar close. + public static void Row(Ledger ledger, DateTime t, BasketEvaluation e, double pMl, string evento, string? basketId, DecisionKind kind = DecisionKind.Skip) + { + BasketDecision d = kind == DecisionKind.Enter + ? new(DecisionKind.Enter, true, new SizingResult(true, 55_000, 117_000, 62_000, 117_000, 150, 2, "ok"), ["enter"], "entro", e, null) + : new(kind, false, null, [kind == DecisionKind.Hold ? "hold" : "no_signal"], "niente", e, null); + ledger.Decision("run", "Demo", "MODERATE", "h", Ctx(t, pMl), d, evento, basketId); + } + + /// The vector the ledger gives back for an evaluation (what the page of a stopped bot reads). + public static double[] VectorOf(Ledger ledger, DateTime t, BasketEvaluation e, string evento, string? basketId, DecisionKind kind = DecisionKind.Skip) + { + BasketDecision d = kind == DecisionKind.Enter + ? new(DecisionKind.Enter, true, new SizingResult(true, 55_000, 117_000, 62_000, 117_000, 150, 2, "ok"), ["enter"], "entro", e, null) + : new(kind, false, null, [kind == DecisionKind.Hold ? "hold" : "no_signal"], "niente", e, null); + string line = Ledger.Serialize("run", "Demo", "MODERATE", "h", Ctx(t, double.NaN), d, evento, basketId, null); + return LearningFeatures.ReadDecisionLine(line)!.Features; + } + + /// The logit the contributions of a row add up to with an intercept, as a probability. + public static double Explained(IEnumerable features, double intercept) => OnlineLogistic.Sigmoid(features.Sum(static f => f.Contribution) + intercept); + + public static BasketStrategyConfig Strategy() => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); +} + +/// +/// The learning review of 5.1 (group «apprendimento»): the retire of the proceeds-taught models is +/// all or nothing and runs once, the session's lastNOutcomes comes from the corrected ledger, the +/// page's dataset follows a correction at once, the labelled count is the dataset's, the +/// contributions shown explain the probability shown, an unreadable file keeps its last good +/// reading, and an arm never tried is never the best of its context. +/// +public sealed class LearningReviewTests : TempFolderTests +{ + private string Models => Path.Combine(Root, "models"); + + private LearningPaths Paths => new(Root, KnowledgeDir); + + // ----------------------------------------------------------------------- + // The bandit: an arm never tried is never the best of its context + // ----------------------------------------------------------------------- + + [Fact] + public void AnArmNeverTriedIsNeverTheBestOfItsContext() + { + ThompsonBandit fresh = new(3, 42); + Assert.DoesNotContain(fresh.Arms(), static a => a.BestInContext); + + ThompsonBandit b = new(3, 42); + b.Reward(1, PresetName.Moderate, true); + b.Reward(2, PresetName.Aggressive, false); + b.Reward(0, PresetName.Conservative, false); + b.Reward(0, PresetName.Moderate, true); + IReadOnlyList arms = b.Arms(); + + // A win makes the only arm with a reward the best of its context. + Assert.Equal("Moderate", Assert.Single(arms, static a => a.Context == 1 && a.BestInContext).Preset); + + // A loss leaves the untried arms with the higher mean: nobody is the best yet. + Assert.DoesNotContain(arms, static a => a.Context == 2 && a.BestInContext); + + // Two tried arms: the better one, even though an untried arm sits at the prior's 0.5. + Assert.Equal("Moderate", Assert.Single(arms, static a => a.Context == 0 && a.BestInContext).Preset); + Assert.All(arms.Where(static a => a.BestInContext), static a => Assert.True(a.N > 0)); + } + + // ----------------------------------------------------------------------- + // apprendimento-04 — the retire is all or nothing and runs once + // ----------------------------------------------------------------------- + + private Ledger LegacyLedger() + { + Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.ProceedsRow()); + CorrectionScenery.Ingresso(ledger, CorrectionScenery.B1, new DateTime(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc)); + return ledger; + } + + [Fact] + public void ARegistryThatCannotBeAppendedStillFinishesTheRetireAndItRunsOnce() + { + using Ledger ledger = LegacyLedger(); + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, [3605914106, 3605914105], "proceeds"); + string prior = new ThompsonBandit(3, 42).ToJson(); + Directory.CreateDirectory(KnowledgeDir); + string registry = Path.Combine(KnowledgeDir, "models_registry.csv"); + Directory.CreateDirectory(registry); // a file that cannot be appended (locked, wrong owner) + + string rewarded; + using (LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy())) + { + Assert.True(learning.RetireAndReplay(ReviewScenery.T0, "etichette dai proceeds")); + Assert.True(learning.LabelsFixed); + Assert.Equal(prior, learning.BanditJson); + + // A genuine 5.1 close after the retire teaches the bandit. + learning.Observe("Y", 1, 2, PresetName.Aggressive); + rewarded = learning.BanditJson; + } + + Directory.Delete(registry); + using LearningState next = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + Assert.True(next.LabelsFixed); + Assert.False(next.RetireAndReplay(ReviewScenery.T0.AddDays(1), "di nuovo")); + Assert.Equal(rewarded, next.BanditJson); + Assert.Single(Directory.GetDirectories(Path.Combine(Models, "ritirati"))); + } + + [Fact] + public void ARetireThatCannotMoveTheFilesChangesNothingInMemory() + { + using Ledger ledger = LegacyLedger(); + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, [3605914106, 3605914105], "proceeds"); + using LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + learning.RememberEntry("X", LearningScenery.Vector(1), 0.6); + learning.Observe("X", 1, 1, PresetName.Moderate); + string bandit = learning.BanditJson; + int seen = learning.LogisticSeen; + + // ritirati is a file: the folder for the retired models cannot be made. + File.WriteAllText(Path.Combine(Models, "ritirati"), "x"); + Assert.ThrowsAny(() => learning.RetireAndReplay(ReviewScenery.T0, "etichette dai proceeds")); + + Assert.False(learning.LabelsFixed); + Assert.Equal(bandit, learning.BanditJson); + Assert.Equal(seen, learning.LogisticSeen); + } + + [Fact] + public void AnUnwritableRegistryNeverStopsAnObservationFromBeingSaved() + { + Directory.CreateDirectory(Models); + List<(double, int)> recent = [.. Enumerable.Range(0, 99).Select(static i => (i % 2 == 0 ? 0.9 : 0.1, i % 2 == 0 ? 0 : 1))]; + File.WriteAllText(Path.Combine(Models, "learning_state.json"), LearningStateFile.Write(new LearningStateData + { + Active = true, + Version = 3, + Recent = recent, + Entries = new Dictionary { ["E"] = new(LearningScenery.Vector(2), 0.95, ReviewScenery.T0) }, + })); + Directory.CreateDirectory(KnowledgeDir); + string registry = Path.Combine(KnowledgeDir, "models_registry.csv"); + Directory.CreateDirectory(registry); + + using Ledger ledger = new(LedgerDir); + using (LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy())) + { + Assert.True(learning.Active); + + // The rolling AUC falls under 0.52 on 100 baskets: back to shadow, and the registry line fails. + learning.Observe("E", 0, 1, PresetName.Moderate, ReviewScenery.T0.AddHours(1)); + Assert.False(learning.Active); + } + + Directory.Delete(registry); + using LearningState again = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + Assert.False(again.Active); + Assert.Equal(1, again.LogisticSeen); + Assert.Equal(100, again.Capture().Rolling.Count); + } + + // ----------------------------------------------------------------------- + // apprendimento-05 — the page's dataset follows a correction at once + // ----------------------------------------------------------------------- + + [Fact] + public void TheDiskDatasetFollowsACorrectionAndAMaskWrittenInTheSameHour() + { + // Dated now: a line of another month would rotate decisions.jsonl and move the stamp by itself. + DateTime opened = DateTime.SpecifyKind(DateTime.UtcNow.AddTicks(-(DateTime.UtcNow.Ticks % TimeSpan.TicksPerSecond)), DateTimeKind.Utc); + using (Ledger seed = new(LedgerDir)) + { + seed.Basket(CorrectionScenery.Row(CorrectionScenery.B1, "EURUSD/USDCAD", "tp_pips", -2.2, opened.ToString("O", CultureInfo.InvariantCulture), + opened.AddMinutes(1).ToString("O", CultureInfo.InvariantCulture), 17_908.25)); + CorrectionScenery.Ingresso(seed, CorrectionScenery.B1, opened); + } + + DateTime now = new(2026, 9, 30, 8, 5, 0, DateTimeKind.Utc); + (DatasetSummary? before, _) = LearningDiskReader.ReadDataset(Paths, now); + Assert.Equal(1, before!.Wins); + + using (Ledger ledger = new(LedgerDir)) + { + ledger.PnlCorrection("run51", ledger.ReadBaskets()[0], -38.79, -38.79, true, [3605914106, 3605914105], "proceeds"); + } + + (DatasetSummary? corrected, _) = LearningDiskReader.ReadDataset(Paths, now.AddMinutes(20)); + Assert.Equal(0, corrected!.Wins); + Assert.Equal(1, corrected.CorrectedRows); + Assert.Equal(-38.79, corrected.PnlNetUsd, 2); + + using (Ledger ledger = new(LedgerDir)) + { + ledger.FeatureUnreliable("run51", LearningFeatures.Names[LearningFeatures.LastOutcomesIndex], LearningFeatures.LastOutcomesIndex, opened.AddMinutes(5), "etichette dai proceeds"); + } + + (_, IReadOnlyList warnings) = LearningDiskReader.ReadDataset(Paths, now.AddMinutes(25)); + Assert.Contains(warnings, static w => w.Contains("lastNOutcomes mascherata", StringComparison.Ordinal)); + Assert.Equal(opened.AddMinutes(5), Ledger.ReadFeatureMaskUntil(LedgerDir, LearningFeatures.Names[LearningFeatures.LastOutcomesIndex])); + } + + // ----------------------------------------------------------------------- + // apprendimento-06 — the labelled count is the dataset's + // ----------------------------------------------------------------------- + + [Fact] + public void TheLabelledCountIsTheDatasetsAfterTheRetire() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.Row("B1", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T09:15:00Z", "2026-09-29T21:15:28Z", 17_908.25, "take-profit")); + ledger.Basket(CorrectionScenery.Row("B2", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T10:15:00Z", "2026-09-29T22:15:28Z", 17_000, "take-profit")); + CorrectionScenery.Ingresso(ledger, "B1", new DateTime(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc)); + CorrectionScenery.Ingresso(ledger, "B2", new DateTime(2026, 9, 29, 10, 15, 0, DateTimeKind.Utc)); + + using LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); // built before the backfill, as at a start + List rows = ledger.ReadBaskets(); + ledger.PnlCorrection("run51", rows[0], -38.79, -38.79, true, [1, 2], "proceeds"); + ledger.PnlCorrection("run51", rows[1], double.NaN, double.NaN, false, [], "posizioni non ritrovate"); + Assert.True(learning.RetireAndReplay(ReviewScenery.T0, "proceeds")); + + Assert.Equal(1, LearningDataset.Build(LedgerDir, DateTime.UtcNow).Summary.LabelledRows); + Assert.Equal(1, learning.Capture().LabelledRows); + Assert.Equal(0, learning.LastOutcomes, 9); // the one label left is the corrected loss + } + + [Fact] + public void TheCountStartsFromTheDatasetAndOnlyARememberedEntryAddsToIt() + { + using Ledger ledger = new(LedgerDir); + LearningScenery.Baskets(ledger, 4); + ledger.Basket(CorrectionScenery.Row("NOENTRY", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-02T09:00:00Z", "2026-09-02T10:00:00Z", -8, + "tp | P&L: storico eToro (netProfit − fees)")); + + using LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + Assert.Equal(4, learning.Capture().LabelledRows); // the basket without its entry line is not a training row + + learning.Observe("GHOST", 1, 1, PresetName.Moderate); // no remembered entry: nothing to train on + Assert.Equal(4, learning.Capture().LabelledRows); + + learning.RememberEntry("REAL", LearningScenery.Vector(4), 0.5); + learning.Observe("REAL", 1, 1, PresetName.Moderate); + Assert.Equal(5, learning.Capture().LabelledRows); + } + + [Fact] + public void AStoppedBotsPageCountsTheDatasetNotAStaleStateFile() + { + using (Ledger ledger = new(LedgerDir)) + { + LearningScenery.Baskets(ledger, 2); + ledger.Basket(CorrectionScenery.Row("NOENTRY", "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-02T09:00:00Z", "2026-09-02T10:00:00Z", -8, + "tp | P&L: storico eToro (netProfit − fees)")); + } + + Directory.CreateDirectory(Models); + File.WriteAllText(Path.Combine(Models, "learning_state.json"), LearningStateFile.Write(new LearningStateData { Version = 2, LabelledRows = 50 })); + LearningLiveReport part = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0); + Assert.Equal(2, part.LabelledRows); + } + + // ----------------------------------------------------------------------- + // apprendimento-08 — the contributions shown explain the probability shown + // ----------------------------------------------------------------------- + + [Fact] + public void AStoppedBotExplainsAnOpenBasketWithItsEntryVector() + { + OnlineLogistic model = ReviewScenery.Trained(); + Directory.CreateDirectory(Models); + File.WriteAllText(Path.Combine(Models, "logreg_current.json"), model.ToJson()); + BasketEvaluation atEntry = new() { Z = -2.4, RhoW = -0.85, RhoShort = -0.8, HalfLife = 30 }; + BasketEvaluation later = new() { Z = -0.8, RhoW = -0.6, RhoShort = -0.3, HalfLife = 55 }; + double[] entryVector = LearningFeatures.From(ReviewScenery.Ctx(ReviewScenery.T0, double.NaN), atEntry, true); + double pEntry = model.Predict(entryVector); + + using (Ledger ledger = new(LedgerDir)) + { + ReviewScenery.Row(ledger, ReviewScenery.T0, atEntry, pEntry, "ingresso", "B1", DecisionKind.Enter); + + // A later bar while the basket is open: the engine writes the entry p with the evaluation of this bar. + ReviewScenery.Row(ledger, ReviewScenery.T0.AddMinutes(45), later, pEntry, "posizione", "B1", DecisionKind.Hold); + using LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + learning.RememberEntry("B1", entryVector, pEntry, ReviewScenery.T0); + } + + LearningLiveReport r = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddHours(1)); + BasketLearningRow row = r.Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal(pEntry, row.PMl, 6); + Assert.Equal(BasketLearningRow.KindAtEntry, row.PMlKind); + Assert.Equal(ReviewScenery.T0, row.PMlUtc); + Assert.Equal(entryVector[0], row.Features[0].Value, 9); + Assert.Equal(pEntry, ReviewScenery.Explained(row.Features, r.Logistic.Bias), 6); + } + + [Fact] + public void AStoppedBotRecomputesAFlatBasketWithTheSavedModelAndSaysSo() + { + OnlineLogistic before = ReviewScenery.Trained(); + BasketEvaluation e = new() { Z = 1.6, RhoW = -0.8, RhoShort = -0.7, HalfLife = 40, CostPips = 2.1 }; + using (Ledger ledger = new(LedgerDir)) + { + double[] vector = ReviewScenery.VectorOf(ledger, ReviewScenery.T0, e, "skip", null); + ReviewScenery.Row(ledger, ReviewScenery.T0, e, before.Predict(vector), "skip", null); + } + + // The saved model is the bar's: the row's p and its contributions agree. + Directory.CreateDirectory(Models); + File.WriteAllText(Path.Combine(Models, "logreg_current.json"), before.ToJson()); + LearningLiveReport same = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddMinutes(5)); + BasketLearningRow row = same.Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal(BasketLearningRow.KindLastBar, row.PMlKind); + Assert.Equal(row.PMl, ReviewScenery.Explained(row.Features, same.Logistic.Bias), 6); + + // The model learnt after the bar (another basket closed): the p is the saved model's, and the kind says so. + OnlineLogistic after = ReviewScenery.Trained(); + for (int i = 0; i < 40; i++) + { + after.Update(LearningScenery.Vector(i), i % 3 == 0 ? 1 : 0); + } + + File.WriteAllText(Path.Combine(Models, "logreg_current.json"), after.ToJson()); + LearningLiveReport moved = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddMinutes(10)); + BasketLearningRow recomputed = moved.Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal("ricalcolata con il modello di oggi", recomputed.PMlKind); + Assert.Equal(ReviewScenery.T0, recomputed.PMlUtc); + Assert.Equal(recomputed.PMl, ReviewScenery.Explained(recomputed.Features, moved.Logistic.Bias), 6); + Assert.NotEqual(row.PMl, recomputed.PMl, 6); + } + + // ----------------------------------------------------------------------- + // apprendimento-10 — an unreadable file keeps its last good reading + // ----------------------------------------------------------------------- + + private void GoodModels() + { + Directory.CreateDirectory(Models); + ThompsonBandit bandit = new(3, 42); + for (int i = 0; i < 7; i++) + { + bandit.Reward(1, PresetName.Moderate, i % 2 == 0); + } + + File.WriteAllText(Path.Combine(Models, "bandit.json"), bandit.ToJson()); + File.WriteAllText(Path.Combine(Models, "learning_state.json"), LearningStateFile.Write(new LearningStateData + { + Version = 4, + LabelsFixedUtc = ReviewScenery.T0, + LastReport = "ciclo buono", + Entries = new Dictionary { ["OPEN1"] = new(LearningScenery.Vector(1), 0.6, ReviewScenery.T0) }, + })); + } + + [Fact] + public void AnUnreadableBanditOrStateKeepsTheLastGoodReading() + { + GoodModels(); + LearningLiveReport good = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddHours(1)); + Assert.Equal(7, good.Bandit.Arms.Sum(static a => a.N)); + + File.WriteAllText(Path.Combine(Models, "bandit.json"), "{ \"broken\": "); + File.WriteAllText(Path.Combine(Models, "learning_state.json"), "{ not json"); + LearningLiveReport bad = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddHours(2)); + + Assert.Contains(bad.Warnings, static w => w.Contains("bandit.json non leggibile", StringComparison.Ordinal) && w.Contains("ultima lettura buona", StringComparison.Ordinal)); + Assert.Contains(bad.Warnings, static w => w.Contains("learning_state.json non leggibile", StringComparison.Ordinal) && w.Contains("ultima lettura buona", StringComparison.Ordinal)); + Assert.Equal(7, bad.Bandit.Arms.Sum(static a => a.N)); + Assert.Equal(ReviewScenery.T0, bad.LabelsFixedUtc); + Assert.Equal(4, bad.Status.ModelVersion); + Assert.Equal("ciclo buono", bad.Status.LastReport); + Assert.Equal(1, bad.Status.TrackedEntries); + } + + [Fact] + public void WithoutAGoodReadingTheWarningSaysTheStartingValuesAreShown() + { + Directory.CreateDirectory(Models); + File.WriteAllText(Path.Combine(Models, "bandit.json"), "{ \"broken\": "); + LearningLiveReport bad = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0); + + string warning = Assert.Single(bad.Warnings, static w => w.Contains("bandit.json non leggibile", StringComparison.Ordinal)); + Assert.DoesNotContain("ultima lettura buona", warning, StringComparison.Ordinal); + Assert.Contains("valori iniziali", warning, StringComparison.Ordinal); + Assert.Equal(0, bad.Bandit.Arms.Sum(static a => a.N)); + } + + [Fact] + public void AFileThatIsGoneIsNotKeptAsTheLastGoodReading() + { + GoodModels(); + Assert.Equal(7, LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0).Bandit.Arms.Sum(static a => a.N)); + + File.Delete(Path.Combine(Models, "bandit.json")); + LearningLiveReport gone = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddMinutes(1)); + Assert.Equal(0, gone.Bandit.Arms.Sum(static a => a.N)); + Assert.DoesNotContain(gone.Warnings, static w => w.Contains("bandit.json", StringComparison.Ordinal)); + } + + [Fact] + public void TheStoppedHeadlineKeepsTheLastGoodStateFile() + { + Directory.CreateDirectory(Models); + string state = Path.Combine(Models, "learning_state.json"); + File.WriteAllText(state, LearningStateFile.Write(new LearningStateData { LabelledRows = 12 })); + Assert.Equal(12, LearningDiskReader.Headline(Paths, ReviewScenery.Strategy(), false, ReviewScenery.T0).LabelledRows); + + File.WriteAllText(state, "{ not json"); + Assert.Equal(12, LearningDiskReader.Headline(Paths, ReviewScenery.Strategy(), false, ReviewScenery.T0.AddSeconds(1)).LabelledRows); + } + + // ----------------------------------------------------------------------- + // apprendimento-08 — a probability keeps what made it + // ----------------------------------------------------------------------- + + private LearningState TrainedState(Ledger ledger) + { + LearningScenery.Baskets(ledger, 40); + LearningState learning = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + learning.RunCycle(LearningScenery.T0.AddDays(20)); + return learning; + } + + /// Teaches the model a few closes: its weights and its standardiser move. + private static void MoveTheModel(LearningState learning, int closes = 25) + { + for (int i = 0; i < closes; i++) + { + string id = string.Create(CultureInfo.InvariantCulture, $"MOVE{i}"); + learning.RememberEntry(id, LearningScenery.Vector(10 + (i * 0.37)), 0.5); + learning.Observe(id, i % 2, 1, PresetName.Moderate); + } + } + + [Fact] + public void AScoreKeepsExplainingItsProbabilityAfterTheModelLearns() + { + using Ledger ledger = new(LedgerDir); + using LearningState learning = TrainedState(ledger); + double[] f = LearningScenery.Vector(0.7); + + ScoreExplanation score = learning.Score(f); + Assert.Equal(learning.Predict(f), score.P, 12); + Assert.Equal(LearningFeatures.Count, score.Features.Count); + Assert.True(score.Explains(score.P, 1e-12)); + + // Other baskets close: the explanation taken with the p still gives it back, today's model does not. + MoveTheModel(learning); + Assert.True(score.Explains(score.P, 1e-12)); + Assert.False(learning.Score(f).Explains(score.P)); + } + + [Fact] + public void AnEntryKeepsWhatMadeItsProbabilityThroughARestart() + { + using Ledger ledger = new(LedgerDir); + double[] f = LearningScenery.Vector(0.9); + ScoreExplanation score; + using (LearningState learning = TrainedState(ledger)) + { + score = learning.Score(f); + learning.RememberEntry("B1", f, score.P, ReviewScenery.T0, score); + learning.RememberEntry("OLD", f, 0.7, ReviewScenery.T0); // as an older version remembered it + } + + using LearningState again = new(Root, KnowledgeDir, ledger, ReviewScenery.Strategy()); + EntryMemory entry = again.EntryOf("B1")!; + Assert.Equal(score.Intercept, entry.Intercept, 12); + Assert.True(entry.Explained().Explains(score.P)); + Assert.Equal(score.Features.Select(static v => v.Contribution), entry.Explained().Features.Select(static v => v.Contribution)); + Assert.Empty(again.EntryOf("OLD")!.Explained().Features); + Assert.Null(again.EntryOf("NONE")); + } + + [Fact] + public void AStoppedBotExplainsAnOpenBasketWithTheModelOfItsEntry() + { + BasketEvaluation atEntry = new() { Z = -2.4, RhoW = -0.85, RhoShort = -0.8, HalfLife = 30 }; + double[] entryVector = LearningFeatures.From(ReviewScenery.Ctx(ReviewScenery.T0, double.NaN), atEntry, true); + double pEntry; + using (Ledger ledger = new(LedgerDir)) + { + using LearningState learning = TrainedState(ledger); + ScoreExplanation score = learning.Score(entryVector); + pEntry = score.P; + ReviewScenery.Row(ledger, ReviewScenery.T0, atEntry, pEntry, "ingresso", "B1", DecisionKind.Enter); + ReviewScenery.Row(ledger, ReviewScenery.T0.AddMinutes(45), new BasketEvaluation { Z = -0.8, RhoW = -0.6 }, pEntry, "posizione", "B1", DecisionKind.Hold); + learning.RememberEntry("B1", entryVector, pEntry, ReviewScenery.T0, score); + + // The model learns from other closes before the bot stops. + MoveTheModel(learning); + } + + LearningLiveReport r = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddHours(1)); + BasketLearningRow row = r.Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal(pEntry, row.PMl, 6); + Assert.Equal(BasketLearningRow.KindAtEntry, row.PMlKind); + Assert.Equal(entryVector[0], row.Features[0].Value, 9); + Assert.Equal(pEntry, ReviewScenery.Explained(row.Features, row.Intercept), 6); + Assert.NotEqual(r.Logistic.Bias, row.Intercept, 9); + Assert.NotEqual(pEntry, ReviewScenery.Explained(row.Features, r.Logistic.Bias), 6); + } + + [Fact] + public void AnEntryWithoutItsExplanationIsShownWithoutContributionsOnceTheModelMoved() + { + BasketEvaluation atEntry = new() { Z = -2.4, RhoW = -0.85, RhoShort = -0.8, HalfLife = 30 }; + double[] entryVector = LearningFeatures.From(ReviewScenery.Ctx(ReviewScenery.T0, double.NaN), atEntry, true); + using (Ledger ledger = new(LedgerDir)) + { + using LearningState learning = TrainedState(ledger); + double pEntry = learning.Predict(entryVector); + ReviewScenery.Row(ledger, ReviewScenery.T0, atEntry, pEntry, "ingresso", "B1", DecisionKind.Enter); + learning.RememberEntry("B1", entryVector, pEntry, ReviewScenery.T0); // remembered before the review: no explanation + MoveTheModel(learning); + } + + BasketLearningRow row = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddHours(1)) + .Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal(BasketLearningRow.KindAtEntry, row.PMlKind); + Assert.True(double.IsFinite(row.PMl)); + Assert.Empty(row.Features); + Assert.Empty(row.TopContributions); + Assert.True(double.IsNaN(row.Intercept)); + } + + // ----------------------------------------------------------------------- + // The engine: a restart gives an open basket its p back; the startup check reseeds the session + // ----------------------------------------------------------------------- + + private string DataPath => Path.Combine(Root, "data"); + + private BotConfig Config() + { + BotConfig c = new(); + c.Run.BaseDirectory = Root; + c.Run.ExecutionMode = "Demo"; + return c; + } + + private static JsonObject Leg(string symbol, long instrument, double units, double price, long positionId, DateTime opened) => new() + { + ["symbol"] = symbol, ["instrumentId"] = instrument, ["isBuy"] = true, ["units"] = units, ["entryPrice"] = price, ["positionId"] = positionId, + ["clientRef"] = "c" + positionId.ToString(CultureInfo.InvariantCulture), ["openedUtc"] = opened.ToString("O", CultureInfo.InvariantCulture), ["entryFeesUsd"] = 0, + ["stopLossRate"] = 0, ["adds"] = new JsonArray(), + }; + + /// The state of the Demo account with the basket EURUSD/USDCHF open since (id B1, legs 11 and 12). + private void WriteOpenBasketState(DateTime opened) + { + DateTime seen = DateTime.UtcNow.AddSeconds(-30); + JsonObject basket = new() + { + ["name"] = ReviewScenery.Pair, ["basketId"] = "B1", ["buyCross"] = true, ["openedUtc"] = opened.ToString("O", CultureInfo.InvariantCulture), + ["entryZ"] = -2.4, ["lastAddZ"] = -2.4, ["adds"] = 0, ["barsHeld"] = 3, ["entryCostPips"] = 1.5, ["tpPips"] = 20, ["maxLossUsd"] = 1_500, + ["zStop"] = 3.5, ["maxAdds"] = 1, ["preset"] = "MODERATE", ["equityAtEntry"] = 100_000, ["accruedFeesUsd"] = 0, ["entryMotivazione"] = "prova", + ["a"] = Leg("EURUSD", 1, 10_000, 1.1000, 11, opened), + ["b"] = Leg("USDCHF", 6, 9_000, 0.9000, 12, opened), + }; + JsonObject state = new() + { + ["savedUtc"] = seen.ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Demo", ["peakNetEquity"] = 100_000, ["cumulativeCashFlow"] = 0, + ["lastBalance"] = 100_000, ["lastBalanceUtc"] = seen.ToString("O", CultureInfo.InvariantCulture), ["sessionDate"] = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["dayStartEquity"] = 100_000, ["lastPositionIds"] = new JsonArray(11, 12), ["baskets"] = new JsonArray(basket), ["pendingEntries"] = new JsonArray(), + }; + string path = AccountStateFiles.PathFor(DataPath, ExecutionMode.Demo); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, state.ToJsonString(), new UTF8Encoding(false)); + } + + [Fact] + public async Task ARestartGivesAnOpenBasketTheProbabilityItEnteredWith() + { + BotConfig config = Config(); + DateTime opened = DateTime.UtcNow.AddHours(-1); + double[] f = LearningScenery.Vector(1.4); + ScoreExplanation score; + using (Ledger ledger = new(Path.Combine(DataPath, "ledger"))) + { + LearningScenery.Baskets(ledger, 40); + using LearningState learning = new(DataPath, config.Run.KnowledgePath, ledger, ReviewScenery.Strategy()); + learning.RunCycle(LearningScenery.T0.AddDays(20)); + score = learning.Score(f); + learning.RememberEntry("B1", f, score.P, opened, score); + MoveTheModel(learning); + } + + WriteOpenBasketState(opened); + MoneyVenue venue = new(); + BasketEngine engine = BasketEngine.OverVenue(config, venue); + engine.StartLearning(); + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + engine.PublishLearning(DateTime.UtcNow); + engine.PublishView(); + + BasketLearningRow row = engine.Learning!.Baskets.Single(static b => b.Basket == ReviewScenery.Pair); + Assert.Equal(score.P, row.PMl, 6); + Assert.Equal(BasketLearningRow.KindAtEntry, row.PMlKind); + Assert.Equal(opened, row.PMlUtc); + Assert.Equal(score.P, ReviewScenery.Explained(row.Features, row.Intercept), 6); + Assert.Equal(score.P, engine.View!.Baskets.Single(static b => b.Name == ReviewScenery.Pair).PMl, 6); + await engine.DisposeAsync(); + } + + [Fact] + public async Task TheStartupCheckReseedsTheSessionEvenWhenTheRetireFailsAndTheRetireRunsAtTheNextStart() + { + BotConfig config = Config(); + string ledgerDir = Path.Combine(DataPath, "ledger"); + DateTime opened = new(2026, 9, 29, 9, 15, 0, DateTimeKind.Utc); + DateTime closed = new(2026, 9, 29, 21, 15, 0, DateTimeKind.Utc); + using (Ledger ledger = new(ledgerDir)) + { + // A 5.0 row: the close proceeds as the P&L (a "win"), with the positions it named. + ledger.Basket(CorrectionScenery.Row("B50", ReviewScenery.Pair, "tp_pips", -2.2, opened.ToString("O", CultureInfo.InvariantCulture), closed.ToString("O", CultureInfo.InvariantCulture), + 17_908.25, "take-profit | posizioni: 101 102")); + CorrectionScenery.Ingresso(ledger, "B50", opened); + } + + MoneyVenue venue = new(); + venue.History.Add(new ClosedTrade(101, 1, true, 10_000, 1.1, 1.1, opened, closed, -10, 0)); + venue.History.Add(new ClosedTrade(102, 6, true, 9_000, 0.9, 0.9, opened, closed, -20, 0)); + BasketEngine engine = BasketEngine.OverVenue(config, venue); + LearningState learning = engine.StartLearning(); + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + Assert.Equal(1, learning.LastOutcomes, 9); // read before the check: the proceeds look like a win + string bandit = learning.BanditJson; + + // ritirati is a file: the retire cannot put the models aside. + string models = Path.Combine(DataPath, "models"); + Directory.CreateDirectory(models); + File.WriteAllText(Path.Combine(models, "ritirati"), "x"); + await engine.BackfillRealizedAsync(CancellationToken.None); + + Assert.False(learning.LabelsFixed); + Assert.Equal(bandit, learning.BanditJson); + Assert.Equal(0, learning.LastOutcomes, 9); // the session decides with the venue's label + Assert.Equal(1, learning.Capture().LabelledRows); + string feature = LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]; + DateTime mask = Ledger.ReadFeatureMaskUntil(ledgerDir, feature); + Assert.NotEqual(DateTime.MinValue, mask); + await engine.DisposeAsync(); + + // The next start: the folder can be made, the retire runs once, the mark stays where it was. + File.Delete(Path.Combine(models, "ritirati")); + BasketEngine next = BasketEngine.OverVenue(config, venue); + LearningState again = next.StartLearning(); + await next.LoadInstrumentsAsync(CancellationToken.None); + next.LoadState(); + await next.BackfillRealizedAsync(CancellationToken.None); + Assert.True(again.LabelsFixed); + Assert.Equal(0, again.LastOutcomes, 9); + Assert.Equal(mask, Ledger.ReadFeatureMaskUntil(ledgerDir, feature)); + Assert.Single(Directory.GetDirectories(Path.Combine(models, "ritirati"))); + await next.DisposeAsync(); + } +}