diff --git a/docs/adr/0018-scelte-fase-8.md b/docs/adr/0018-scelte-fase-8.md
index 7c8aca2..ad92a9d 100644
--- a/docs/adr/0018-scelte-fase-8.md
+++ b/docs/adr/0018-scelte-fase-8.md
@@ -45,3 +45,20 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
- Al primo avvio, se non ce n'è nessuno, diventa il modello in carica, in osservazione. Un file nuovo (revisione trimestrale) aggiorna frequenze di base ed esempi, non il modello: quello cambia solo con una promozione.
- Una strategia senza frequenza di base non viene stimata: moltiplicatore 1, nessuna stima, non conta tra i segnali valutati. Oggi vale per le due strategie sulle azioni, finché manca lo storico di Alpaca.
- **Esito onesto del primo modello**: 1.844 esempi crypto, 18,3% in guadagno. Nessuno dei tre modelli fa meglio di chi risponde sempre la frequenza di base (log-loss 0,494 contro 0,481 nelle combinazioni); il guadagno medio per operazione proposta passa da +1,69 a +1,76 euro, differenza che non vale niente. Resta in osservazione come tutti i modelli; i criteri di 11.5 lo fermano se non impara altro.
+
+**8. Il modello nelle decisioni.** È l'ultimo correttivo, prima del rischio: tocca ingressi e aumenti, mai uscite e riduzioni.
+- Il moltiplicatore nasce con l'esempio e vale per l'operazione finché non si chiude, aumenti e riavvii compresi, anche se nel frattempo il modello cambia o viene messo da parte. La messa da parte vale quindi per le operazioni nuove.
+- Su una posizione già rimpicciolita un aumento più piccolo del 20% della dimensione ridotta non si fa: sarebbe rincorrere gli arrotondamenti ogni giorno.
+- Un guasto del modello lascia le intenzioni com'erano e finisce nel registro tecnico.
+- Finché il modello non conta, accanto a ogni operazione si scrive la stima e il moltiplicatore che avrebbe dato (riga `model` della decisione, stime in `ml_predictions`), sia del modello in carica sia dello sfidante.
+
+**9. Controllo della notte** (03:00 di Roma; dopo un'assenza una volta sola, 5.6). Si guardano le stime che il modello in carica ha fatto per ogni esempio, quelle fatte da sfidante comprese.
+- Precisione sugli ultimi 60 casi; conta da 40. Sotto il 50% il modello è messo da parte.
+- ADWIN sull'errore quadratico (δ 0,002, finestra esatta, parti di almeno 10 casi), ricalcolato ogni notte da capo: nessuno stato da perdere. Un aumento vale come allarme per i 30 casi successivi; un calo lo chiude.
+- Deriva degli indizi: negli ultimi 60 esempi, più del 20% dei valori di un indizio in uso sta fuori dall'intervallo 1%–99% visto in addestramento. Il giorno della settimana e la strategia non contano.
+- Il rientro è automatico, al primo controllo senza motivi. Messa da parte e rientro si notificano.
+
+**10. Domenica.** Senza sfidante se ne addestra uno, se ci sono esiti nuovi rispetto all'ultimo addestramento; con uno sfidante si guarda solo se i casi di confronto hanno passato una nuova soglia. Una domenica persa si recupera al primo controllo, una volta sola. Una promozione annullata lascia la versione tra le annullate: non torna da sola.
+- Le strategie senza frequenza di base non addestrano: nessuno potrebbe stimarle.
+
+**11. Avvio (11.5).** I 300 segnali sono quelli con un esito. Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte.
diff --git a/src/Anubis.Server/ReasonTexts.cs b/src/Anubis.Server/ReasonTexts.cs
index 2b5fd40..f5bc486 100644
--- a/src/Anubis.Server/ReasonTexts.cs
+++ b/src/Anubis.Server/ReasonTexts.cs
@@ -41,12 +41,48 @@ internal static class ReasonTexts
yield break;
}
+ if (stage == DecisionStages.Model)
+ {
+ if (Model(data) is { } line)
+ {
+ yield return new WhyLine(line, good);
+ }
+
+ yield break;
+ }
+
foreach (var reason in reasons)
{
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
}
}
+ /// What the model said of an entry (SPEC 11.5): its estimate, the usual share of gains, what it changed.
+ internal static string? Model(string? data)
+ {
+ if (data is null)
+ {
+ return null;
+ }
+
+ using var json = JsonDocument.Parse(data);
+ double? Number(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number ? value.GetDouble() : null;
+ if (Number("probability") is not { } probability || Number("base_rate") is not { } rate)
+ {
+ return null;
+ }
+
+ var it = CultureInfo.GetCultureInfo("it-IT");
+ var said = string.Create(it, $"Il modello stimava il {probability * 100:0}% di probabilità di guadagno (di solito {rate * 100:0}%)");
+ var applied = Number("applied") ?? 1;
+ if (applied < 1)
+ {
+ return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto";
+ }
+
+ return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": in osservazione, non cambia niente";
+ }
+
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
private static string Asked(string? data)
{
diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs
index 95fa436..dd78a1a 100644
--- a/src/Anubis/Core/Settings.cs
+++ b/src/Anubis/Core/Settings.cs
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList All =
- [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All];
+ [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary();
diff --git a/src/Anubis/Learning/Health.cs b/src/Anubis/Learning/Health.cs
new file mode 100644
index 0000000..5cedbb6
--- /dev/null
+++ b/src/Anubis/Learning/Health.cs
@@ -0,0 +1,235 @@
+using Anubis.Core;
+
+namespace Anubis.Learning;
+
+/// An estimate saved when its example was born, with the model that made it.
+public sealed record SeenEstimate(Guid ModelId, bool InCharge, Estimate Estimate);
+
+/// A week of the watch: the precision on the last cases closed by its end.
+public sealed record WeekPrecision(DateOnly Monday, double Precision, int Cases);
+
+/// What the nightly check saw (SPEC 11.4).
+public sealed record HealthCheck
+{
+ public DateTimeOffset At { get; init; }
+
+ /// On the last cases of the model in charge; null without both wins and losses.
+ public double? Precision { get; init; }
+
+ public int Cases { get; init; }
+
+ public bool ErrorDrift { get; init; }
+
+ /// The groups of clues whose values are too often outside what the model studied.
+ public IReadOnlyList DriftingClues { get; init; } = [];
+
+ /// Why the model should stay aside; null when nothing is wrong.
+ public string? Aside { get; init; }
+}
+
+///
+/// ADWIN, written here (SPEC 11.4): it keeps the values since the last change and compares every possible older part with
+/// the newer one. When two means differ more than chance allows, the older part is dropped: the error has changed.
+///
+public sealed class Adwin(double delta = 0.002)
+{
+ private const int MinPart = 10;
+
+ private readonly List _window = [];
+
+ public int Count => _window.Count;
+
+ /// Adds a value between 0 and 1: 1 when the mean has risen, -1 when it has fallen, 0 when nothing changed.
+ public int Add(double value)
+ {
+ _window.Add(Math.Clamp(value, 0, 1));
+ var change = 0;
+ while (Cut() is { } cut)
+ {
+ change = cut.Risen ? 1 : -1;
+ _window.RemoveRange(0, cut.At);
+ }
+
+ return change;
+ }
+
+ private (int At, bool Risen)? Cut()
+ {
+ var n = _window.Count;
+ if (n < 2 * MinPart)
+ {
+ return null;
+ }
+
+ var total = _window.Sum();
+ var mean = total / n;
+ var variance = _window.Sum(v => (v - mean) * (v - mean)) / n;
+ var log = Math.Log(2 * Math.Log(n) / delta);
+ var older = 0.0;
+ for (var at = 1; at <= n - MinPart; at++)
+ {
+ older += _window[at - 1];
+ if (at < MinPart)
+ {
+ continue;
+ }
+
+ var m = 1 / ((1.0 / at) + (1.0 / (n - at)));
+ var limit = Math.Sqrt(2 / m * variance * log) + (2 / (3 * m) * log);
+ var (before, after) = (older / at, (total - older) / (n - at));
+ if (Math.Abs(before - after) > limit)
+ {
+ return (at, after > before);
+ }
+ }
+
+ return null;
+ }
+}
+
+/// The rules that set the model aside (SPEC 11.4, ADR 0018).
+public static class Health
+{
+ public const int Recent = 60;
+
+ /// The precision counts from this many cases.
+ public const int MinCases = 40;
+
+ public const double Alarm = 0.50;
+
+ /// An alarm of the error lasts for this many labelled cases.
+ public const int AlarmCases = 30;
+
+ /// A clue drifts when more than this share of the recent cases is outside the 1%–99% it was studied on.
+ public const double OutsideShare = 0.20;
+
+ ///
+ /// The check on the estimates of the model in charge, the ones it made on trial included: in
+ /// the order the outcomes came, the latest live examples with or without an outcome.
+ ///
+ public static HealthCheck Check(ModelRow champion, IReadOnlyList labelled, IReadOnlyList recent, DateTimeOffset at)
+ {
+ ArgumentNullException.ThrowIfNull(champion);
+ ArgumentNullException.ThrowIfNull(labelled);
+ ArgumentNullException.ThrowIfNull(recent);
+ var last = labelled.Skip(Math.Max(0, labelled.Count - Recent)).ToList();
+ var precision = Judge.Precision(last);
+ var error = ErrorDrift(labelled);
+ var clues = champion.Model is { } model ? ClueDrift(model, recent) : [];
+ return new HealthCheck
+ {
+ At = at,
+ Precision = precision,
+ Cases = last.Count,
+ ErrorDrift = error,
+ DriftingClues = clues,
+ Aside = last.Count >= MinCases && precision < Alarm ? AsideCodes.Precision : error ? AsideCodes.ErrorDrift : clues.Count > 0 ? AsideCodes.ClueDrift : null,
+ };
+ }
+
+ /// The squared error has risen within the last cases. Computed from the beginning each time: no state to lose.
+ public static bool ErrorDrift(IReadOnlyList labelled)
+ {
+ ArgumentNullException.ThrowIfNull(labelled);
+ var adwin = new Adwin();
+ var alarm = -1;
+ for (var i = 0; i < labelled.Count; i++)
+ {
+ var change = adwin.Add(Math.Pow(labelled[i].Probability - (labelled[i].Win ? 1 : 0), 2));
+ alarm = change > 0 ? i : change < 0 ? -1 : alarm;
+ }
+
+ return alarm >= 0 && labelled.Count - alarm <= AlarmCases;
+ }
+
+ private static List ClueDrift(TrainedModel model, IReadOnlyList recent)
+ {
+ var known = recent.Where(e => model.Strategies.Contains(e.Strategy)).ToList();
+ var last = known.Skip(Math.Max(0, known.Count - Recent)).ToList();
+ var drifting = new List();
+ foreach (var clue in model.Clues.Where(c => !c.StartsWith(Clues.StrategyPrefix, StringComparison.Ordinal) && c is not (Clues.WeekSin or Clues.WeekCos)))
+ {
+ var values = last.Where(e => e.Features.ContainsKey(clue)).Select(e => e.Features[clue]).ToList();
+ if (values.Count >= MinCases && model.Ranges.TryGetValue(clue, out var range) && values.Count(v => v < range.Low || v > range.High) > OutsideShare * values.Count)
+ {
+ drifting.Add(Clues.Find(clue)?.Group ?? clue);
+ }
+ }
+
+ return [.. drifting.Distinct(StringComparer.Ordinal)];
+ }
+
+ /// The precision week by week: each on the last cases closed by its end, when they are enough.
+ public static IReadOnlyList Weeks(IReadOnlyList labelled, DateOnly today, int weeks = 8)
+ {
+ ArgumentNullException.ThrowIfNull(labelled);
+ var monday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
+ var result = new List();
+ for (var k = weeks - 1; k >= 0; k--)
+ {
+ var start = monday.AddDays(-7 * k);
+ var closed = labelled.Where(e => e.Case.Label!.ClosedDay < start.AddDays(7)).ToList();
+ var last = closed.Skip(Math.Max(0, closed.Count - Recent)).ToList();
+ if (last.Count >= MinCases && Judge.Precision(last) is { } precision)
+ {
+ result.Add(new WeekPrecision(start, precision, last.Count));
+ }
+ }
+
+ return result;
+ }
+}
+
+/// Whether the model may start to count (SPEC 11.5).
+public sealed record ActivationCheck(int Evaluated, Scores Scores, double? CalibrationError, double Low, double High)
+{
+ public const int Needed = 300;
+
+ public const double MaxCalibrationError = 0.05;
+
+ public bool Enough => Evaluated >= Needed;
+
+ public bool Calibrated => CalibrationError is { } error && error < MaxCalibrationError;
+
+ public bool Improves => Low > 0;
+
+ public bool Passed => Enough && Calibrated && Improves;
+
+ ///
+ /// On the estimates that were in charge when each signal came, whatever version made them, weighed by maturation; the
+ /// improvement only on signals of strategies with capital at that moment.
+ ///
+ public static ActivationCheck Of(IReadOnlyList inCharge, IReadOnlyDictionary baseRates, IReadOnlyDictionary capital)
+ {
+ ArgumentNullException.ThrowIfNull(inCharge);
+ var weighed = Judge.Weigh(inCharge, baseRates);
+ var scores = Judge.Score(weighed, capital, IsFunded);
+ var funded = weighed.Where(e => IsFunded(e.Case)).ToList();
+ var (low, high) = Judge.Interval([.. funded.Select(e => (e.Multiplier - 1) * Judge.Gain(e.Case, capital))], [.. funded.Select(e => e.Weight)], 0.90);
+ return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high);
+ }
+
+ /// A signal of a strategy that had capital: zeroing those of a candidate in observation is no merit (SPEC 11.3).
+ public static bool IsFunded(Example example) => example?.Stage is { } stage && stage != Trading.StrategyStages.Observation;
+}
+
+/// The trial of the challenger against the model in charge (SPEC 11.4).
+public sealed record TrialCheck(int Pairs, int Threshold, double Low, double High, double Mean, double ChallengerPrecision, double ChampionPrecision)
+{
+ public static readonly IReadOnlyList Thresholds = [100, 150, 200, 250, 300];
+
+ /// Pairs of estimates on the same example, both with their outcome, in the order the outcomes came.
+ public static TrialCheck Of(IReadOnlyList<(Estimate Champion, Estimate Challenger)> pairs, IReadOnlyDictionary baseRates)
+ {
+ ArgumentNullException.ThrowIfNull(pairs);
+ var weights = Judge.Weigh([.. pairs.Select(p => p.Champion)], baseRates).Select(e => e.Weight).ToList();
+ var differences = pairs.Select(p => Judge.LogLoss(p.Champion.Win, p.Champion.Probability) - Judge.LogLoss(p.Champion.Win, p.Challenger.Probability)).ToList();
+ var (low, high) = Judge.Interval(differences, weights, 0.95);
+ var total = weights.Sum();
+ return new TrialCheck(pairs.Count, Thresholds.LastOrDefault(t => t <= pairs.Count), low, high, total > 0 ? differences.Zip(weights, (d, w) => d * w).Sum() / total : 0,
+ Judge.Precision([.. pairs.Select(p => p.Challenger)]) ?? 0, Judge.Precision([.. pairs.Select(p => p.Champion)]) ?? 0);
+ }
+
+ /// The advantage of the challenger cannot be told from chance unless the whole interval is above zero.
+ public bool Wins => Low > 0;
+}
diff --git a/src/Anubis/Learning/LearningCycle.cs b/src/Anubis/Learning/LearningCycle.cs
new file mode 100644
index 0000000..86cb797
--- /dev/null
+++ b/src/Anubis/Learning/LearningCycle.cs
@@ -0,0 +1,338 @@
+using System.Globalization;
+using Anubis.Backtest;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Notifications;
+using Anubis.Strategies;
+using Anubis.Trading;
+
+namespace Anubis.Learning;
+
+/// What the labels of a strategy need: the collected bars, through which closed day, its rules, the first report after a day.
+public sealed record LabelData(BacktestDataset Data, DateOnly Through, Func Create)
+{
+ public Func?>>? Earnings { get; init; }
+}
+
+/// Everything the models saw, put together once: the page and the nightly check read the same numbers.
+public sealed record LearningSnapshot(IReadOnlyList Examples, IReadOnlyList Labelled, IReadOnlyList Models, CycleState State)
+{
+ public ModelRow? Champion => Models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
+
+ public ModelRow? Challenger => Models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
+
+ /// The estimates that counted when each signal came, with their outcome, in the order the outcomes came.
+ public IReadOnlyList InCharge => [.. Labelled.Where(e => e.InCharge).Select(e => e.Estimate)];
+
+ public IReadOnlyList Of(Guid model) => [.. Labelled.Where(e => e.ModelId == model).Select(e => e.Estimate)];
+
+ public IReadOnlyList<(Estimate Champion, Estimate Challenger)> Pairs(Guid champion, Guid challenger)
+ {
+ var first = Labelled.Where(e => e.ModelId == champion).ToDictionary(e => e.Estimate.Case.Id, e => e.Estimate);
+ return [.. Labelled.Where(e => e.ModelId == challenger && first.ContainsKey(e.Estimate.Case.Id)).Select(e => (first[e.Estimate.Case.Id], e.Estimate))];
+ }
+
+ public static async Task LoadAsync(LearningDesk desk, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(desk);
+ var examples = await desk.Store.AllAsync(cancellationToken).ConfigureAwait(false);
+ var byId = examples.Where(e => e.IsLabelled).ToDictionary(e => e.Id);
+ var predictions = await desk.Models.PredictionsAsync(cancellationToken).ConfigureAwait(false);
+ var labelled = predictions.Where(p => byId.ContainsKey(p.FeatureId))
+ .Select(p => new SeenEstimate(p.ModelId, p.InCharge, new Estimate(byId[p.FeatureId], p.Probability, p.BaseRate, p.Multiplier)))
+ .OrderBy(e => e.Estimate.Case.Label!.ClosedDay).ThenBy(e => e.Estimate.Case.At).ThenBy(e => e.Estimate.Case.Symbol, StringComparer.Ordinal).ToList();
+ return new LearningSnapshot(examples, labelled, await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false), await desk.CycleAsync(cancellationToken).ConfigureAwait(false));
+ }
+}
+
+///
+/// The continuous cycle of SPEC 11.4: every night the labels, the check of the model in charge and the criteria to start
+/// counting; every Sunday the challenger, trained or judged. One run after an absence does everything that was due once
+/// (SPEC 5.6). Every step can be repeated: a run cut short is made again whole.
+///
+public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, Func, CancellationToken, Task> dataOf)
+{
+ private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
+
+ public async Task RunAsync(CancellationToken cancellationToken)
+ {
+ await desk.PrepareHistoryAsync(cancellationToken).ConfigureAwait(false);
+ await LabelAsync(cancellationToken).ConfigureAwait(false);
+ await CheckAsync(cancellationToken).ConfigureAwait(false);
+ await SundayAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ // ---- Labels -------------------------------------------------------------------------------------------------
+
+ /// The outcome of the examples whose simulated operation closed. Returns how many.
+ public async Task LabelAsync(CancellationToken cancellationToken)
+ {
+ var made = 0;
+ foreach (var group in (await desk.Store.OpenAsync(cancellationToken).ConfigureAwait(false)).GroupBy(e => e.Strategy, StringComparer.Ordinal))
+ {
+ var open = group.ToList();
+ if (await dataOf(group.Key, open, cancellationToken).ConfigureAwait(false) is not { } source)
+ {
+ continue;
+ }
+
+ foreach (var example in open)
+ {
+ // Without the bar of its own day the operation would start from the wrong one.
+ if (source.Data[example.Symbol] is not { } instrument || instrument.IndexOf(example.Day) < 0)
+ {
+ continue;
+ }
+
+ DateOnly? report = null;
+ if (example.Strategy == StrategyNames.EquityMeanrev && source.Earnings is not null
+ && await source.Earnings(example.Day, cancellationToken).ConfigureAwait(false) is { } next && next.TryGetValue(example.Symbol, out var date))
+ {
+ report = date;
+ }
+
+ if (CaseLabels.Of(example, source.Create, source.Data, source.Through, earnings: report) is { } label)
+ {
+ await desk.Store.AddLabelAsync(example.Id, label, cancellationToken).ConfigureAwait(false);
+ made++;
+ }
+ }
+ }
+
+ return made;
+ }
+
+ // ---- Check --------------------------------------------------------------------------------------------------
+
+ /// The check of the model in charge: set aside or back, and whether it may start to count.
+ public async Task CheckAsync(CancellationToken cancellationToken)
+ {
+ var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
+ if (snapshot.Champion is not { } champion)
+ {
+ return;
+ }
+
+ var now = clock.UtcNow;
+ var today = Zones.DayIn(now, Zones.Rome);
+ var labelled = snapshot.Of(champion.Id);
+ var health = Health.Check(champion, labelled, [.. snapshot.Examples.Where(e => e.Source == CaseSources.Live)], now);
+ var activation = ActivationCheck.Of(snapshot.InCharge, desk.BaseRates, await CapitalsAsync(cancellationToken).ConfigureAwait(false));
+ var state = snapshot.State;
+ var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now };
+ if (state.ActivatedAt is null && activation.Passed)
+ {
+ next = next with { ActivatedAt = now };
+ }
+
+ await db.WriteAsync(async s =>
+ {
+ if (health.Aside is { } reason && state.Aside is null)
+ {
+ var text = AsideText(reason, health) + " Lo metto da parte finché non rientra: le strategie proseguono senza di lui.";
+ await TellAsync(s, ModelEvents.SetAside, champion.Version, "Allarme: " + Lower(text), "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false);
+ }
+ else if (health.Aside is null && state is { Aside: not null, AsideAt: { } since })
+ {
+ var days = Math.Max(1, (int)Math.Round((now - since).TotalDays));
+ var text = $"Anomalia rientrata dopo {(days == 1 ? "un giorno" : days.ToString(It) + " giorni")}: il modello non è più da parte.";
+ await TellAsync(s, ModelEvents.Back, champion.Version, text, "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false);
+ }
+ else if (state.LastNight != today)
+ {
+ await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_check",
+ health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health) : "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (next.ActivatedAt is not null && state.ActivatedAt is null)
+ {
+ var text = string.Create(It, $"Il modello comincia a contare: {activation.Evaluated} segnali valutati, probabilità ben tarate (errore medio {activation.CalibrationError * 100:0.0} punti), guadagno medio per operazione proposta da {activation.Scores.GainWithout:+0.00;-0.00} a {activation.Scores.GainWith:+0.00;-0.00} euro. Può solo rimpicciolire le operazioni.");
+ await TellAsync(s, ModelEvents.Activated, champion.Version, text, text, notify: true, cancellationToken).ConfigureAwait(false);
+ }
+
+ await LearningStore.SaveStateAsync(s, clock, CycleState.Key, next, cancellationToken).ConfigureAwait(false);
+ }, cancellationToken).ConfigureAwait(false);
+ }
+
+ public static string AsideText(string reason, HealthCheck health)
+ {
+ ArgumentNullException.ThrowIfNull(health);
+ return reason switch
+ {
+ AsideCodes.Precision => string.Create(It, $"Precisione scesa al {(health.Precision ?? 0) * 100:0}% su {health.Cases} casi."),
+ AsideCodes.ErrorDrift => "Gli errori del modello sono aumentati negli ultimi casi.",
+ AsideCodes.ClueDrift => "Il mercato è diverso da quello che ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(It) + ".",
+ _ => "Anomalia.",
+ };
+ }
+
+ private async Task TellAsync(DbSession s, string kind, int? version, string history, string diary, bool notify, CancellationToken cancellationToken)
+ {
+ await ModelStore.AddEventAsync(s, clock, kind, version, history, cancellationToken).ConfigureAwait(false);
+ await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_" + kind, diary, null, cancellationToken).ConfigureAwait(false);
+ if (notify)
+ {
+ await NotificationSender.EnqueueAsync(s, clock, "model_" + kind, diary, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ // ---- Sunday -------------------------------------------------------------------------------------------------
+
+ /// The weekly part, once for each Sunday; a Sunday missed while the bot was off is done at the next run.
+ public async Task SundayAsync(CancellationToken cancellationToken)
+ {
+ var state = await desk.CycleAsync(cancellationToken).ConfigureAwait(false);
+ var today = Zones.DayIn(clock.UtcNow, Zones.Rome);
+ var sunday = today.AddDays(-(int)today.DayOfWeek);
+ if (state.LastSunday is { } done ? done >= sunday : today != sunday)
+ {
+ if (state.LastSunday is null)
+ {
+ await SaveAsync(state with { LastSunday = sunday }, cancellationToken).ConfigureAwait(false);
+ }
+
+ return;
+ }
+
+ var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
+ if (snapshot is { Champion: { } champion, Challenger: { } challenger })
+ {
+ await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+
+ await TrainAsync(snapshot, sunday, cancellationToken).ConfigureAwait(false);
+ }
+
+ private Task SaveAsync(CycleState state, CancellationToken cancellationToken) =>
+ db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken), cancellationToken);
+
+ /// The trial: a decision only when the cases have passed a new threshold (SPEC 11.4).
+ private async Task JudgeAsync(LearningSnapshot snapshot, ModelRow champion, ModelRow challenger, DateOnly sunday, CancellationToken cancellationToken)
+ {
+ var check = TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), desk.BaseRates);
+ var state = snapshot.State with { LastSunday = sunday };
+ await db.WriteAsync(async s =>
+ {
+ if (check.Threshold > challenger.ThresholdDone)
+ {
+ await ModelStore.SetThresholdAsync(s, clock, challenger.Id, check.Threshold, cancellationToken).ConfigureAwait(false);
+ if (check.Wins)
+ {
+ await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Retired, cancellationToken).ConfigureAwait(false);
+ await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
+ await ModelStore.SetReplacedAsync(s, clock, challenger.Id, champion.Id, cancellationToken).ConfigureAwait(false);
+ var text = string.Create(It, $"La versione {challenger.Version} prende il posto della {champion.Version}: stime migliori su {check.Pairs} casi di confronto, un vantaggio che non si spiega con il caso.");
+ await TellAsync(s, ModelEvents.Promoted, challenger.Version, text, text + " Puoi annullare la promozione dalla pagina Apprendimento.", notify: true, cancellationToken).ConfigureAwait(false);
+ }
+ else if (check.Threshold >= TrialCheck.Thresholds[^1])
+ {
+ await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Discarded, cancellationToken).ConfigureAwait(false);
+ var text = string.Create(It, $"Scartata la versione {challenger.Version}: dopo {check.Pairs} casi di confronto non fa meglio della {champion.Version}.");
+ await TellAsync(s, ModelEvents.Discarded, challenger.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false);
+ }, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, CancellationToken cancellationToken)
+ {
+ // A strategy without a base rate is not estimated, so it does not train either (ADR 0018).
+ var rates = desk.BaseRates;
+ var examples = snapshot.Examples.Where(e => e.IsLabelled && rates.ContainsKey(e.Strategy)).ToList();
+ var state = snapshot.State with { LastSunday = sunday };
+ var seen = state.TrainedOn > 0 ? state.TrainedOn : snapshot.Champion?.Examples ?? 0;
+ var champion = snapshot.Champion;
+ TrainingResult? result = null;
+ if (examples.Count != seen && (champion is not null || examples.Count >= ActivationCheck.Needed))
+ {
+ var input = new TrainingInput(examples)
+ {
+ BaseRates = rates,
+ Capital = await CapitalsAsync(cancellationToken).ConfigureAwait(false),
+ Funded = await FundedAsync(cancellationToken).ConfigureAwait(false),
+ Rule = (await desk.GateAsync(cancellationToken).ConfigureAwait(false)).Rule,
+ };
+ result = await Task.Run(() => Trainer.Train(input, cancellationToken), cancellationToken).ConfigureAwait(false);
+ state = state with { TrainedOn = examples.Count };
+ }
+
+ await db.WriteAsync(async s =>
+ {
+ if (result is { } trained)
+ {
+ // The state may have changed while it trained (an undo): never two challengers, never two in charge.
+ var status = await ModelStore.FindAsync(s, ModelStatuses.Champion).ConfigureAwait(false) is null ? ModelStatuses.Champion : ModelStatuses.Challenger;
+ if (await ModelStore.FindAsync(s, status).ConfigureAwait(false) is null)
+ {
+ var row = await ModelStore.RegisterAsync(s, clock, trained.Model, trained.Report, status, "weekly", clock.UtcNow, cancellationToken).ConfigureAwait(false);
+ var what = status == ModelStatuses.Champion ? "È il primo modello: parte in osservazione." : "È in prova come sfidante.";
+ var text = string.Create(It, $"Addestrata la versione {row.Version} su {row.Examples} casi ({LearnerNames.Label(row.Learner).ToLower(It)}). {what}");
+ await TellAsync(s, ModelEvents.Trained, row.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false);
+ }, cancellationToken).ConfigureAwait(false);
+ }
+
+ // ---- Undo ---------------------------------------------------------------------------------------------------
+
+ /// Takes back the last promotion (SPEC 11.4): the model it replaced is in charge again. False when there is nothing to take back.
+ public Task UndoPromotionAsync(CancellationToken cancellationToken) => UndoPromotionAsync(db, clock, cancellationToken);
+
+ public static Task UndoPromotionAsync(Database db, IClock clock, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(db);
+ return db.WriteAsync(async s =>
+ {
+ if (await ModelStore.FindAsync(s, ModelStatuses.Champion).ConfigureAwait(false) is not { ReplacedId: { } previous } champion
+ || (await s.FirstOrDefaultAsync("SELECT version FROM ml_models WHERE id = @id AND status = @st", r => (Version: (int)r.Number("version"), Found: true), ("id", previous), ("st", ModelStatuses.Retired))
+ .ConfigureAwait(false)) is not { Found: true } back)
+ {
+ return false;
+ }
+
+ await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Undone, cancellationToken).ConfigureAwait(false);
+ await ModelStore.SetStatusAsync(s, clock, previous, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
+ var text = $"Promozione annullata da te: torna in carica la versione {back.Version} al posto della {champion.Version}.";
+ await ModelStore.AddEventAsync(s, clock, ModelEvents.Undone, back.Version, text, cancellationToken).ConfigureAwait(false);
+ await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_undone", text, null, cancellationToken).ConfigureAwait(false);
+ return true;
+ }, cancellationToken);
+ }
+
+ // ---- Money --------------------------------------------------------------------------------------------------
+
+ /// The capital of each strategy in euro; the reference one (SPEC 8.6) for a strategy that has none yet.
+ public Task> CapitalsAsync(CancellationToken cancellationToken) => CapitalsAsync(db, clock, cancellationToken);
+
+ public static async Task> CapitalsAsync(Database db, IClock clock, CancellationToken cancellationToken)
+ {
+ var capitals = new Dictionary(FirstModel.ReferenceCapitals, StringComparer.Ordinal);
+ var rate = (await new FxStore(db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
+ foreach (var (strategy, capital) in await CapitalRowsAsync(db, cancellationToken).ConfigureAwait(false))
+ {
+ var euro = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(strategy)) == "USD" ? (rate > 0m ? capital / rate : 0m) : capital;
+ if (euro > 0m)
+ {
+ capitals[strategy] = (double)euro;
+ }
+ }
+
+ return capitals;
+ }
+
+ private static async Task> CapitalRowsAsync(Database db, CancellationToken cancellationToken) =>
+ [.. (await db.ReadAsync(s => s.QueryAsync("SELECT strategy, capital FROM strategy_state", r => (r.Text("strategy"), r.Money("capital"))), cancellationToken).ConfigureAwait(false))
+ .Where(r => StrategyPipeline.IsBase(r.Item1))];
+
+ private async Task> FundedAsync(CancellationToken cancellationToken) =>
+ (await db.ReadAsync(s => s.QueryAsync("SELECT strategy FROM strategy_state WHERE stage <> @o", r => r.Text("strategy"), ("o", StrategyStages.Observation)), cancellationToken)
+ .ConfigureAwait(false)).ToHashSet(StringComparer.Ordinal);
+
+ private static string Lower(string text) => text.Length == 0 ? text : char.ToLower(text[0], It) + text[1..];
+}
diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs
index 0cad11f..ad266cd 100644
--- a/src/Anubis/Learning/LearningDesk.cs
+++ b/src/Anubis/Learning/LearningDesk.cs
@@ -10,9 +10,71 @@ using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Learning;
+/// Where the learning cycle is: whether the model counts, whether it is set aside and why, what ran last.
+public sealed record CycleState
+{
+ public const string Key = "cycle";
+
+ /// When the criteria of SPEC 11.5 were met: from then on the model shrinks operations. Null: in observation.
+ public DateTimeOffset? ActivatedAt { get; init; }
+
+ /// Why the model is set aside on its own (); null when it is not.
+ public string? Aside { get; init; }
+
+ public DateTimeOffset? AsideAt { get; init; }
+
+ /// The last night checked and the last Sunday done, as dates in Rome.
+ public DateOnly? LastNight { get; init; }
+
+ public DateOnly? LastSunday { get; init; }
+
+ /// The labelled examples the last training saw.
+ public int TrainedOn { get; init; }
+
+ public HealthCheck? Health { get; init; }
+}
+
+/// Why a model is set aside on its own (SPEC 11.4).
+public static class AsideCodes
+{
+ public const string Precision = "precision";
+ public const string ErrorDrift = "error_drift";
+ public const string ClueDrift = "clue_drift";
+}
+
+/// What a model says of a new example. is what it would apply; it counts only when the gate says so.
+public sealed record ModelEstimate(ModelRow Row, double Probability, double BaseRate, double Multiplier, bool InCharge);
+
+/// What decides about the operations at a decision: the model in charge, the one on trial, and whether it counts.
+public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, MultiplierRule Rule, IReadOnlyDictionary BaseRates, bool Counts)
+{
+ /// Without a model, or without a base rate for the strategy, there is no estimate (ADR 0018).
+ public IReadOnlyList Estimate(Example example)
+ {
+ ArgumentNullException.ThrowIfNull(example);
+ if (!BaseRates.TryGetValue(example.Strategy, out var rate))
+ {
+ return [];
+ }
+
+ var estimates = new List();
+ foreach (var (row, inCharge) in new[] { (Champion, true), (Challenger, false) })
+ {
+ if (row?.Model is { } model && model.Probability(example.Features) is var probability && double.IsFinite(probability))
+ {
+ var p = Math.Round(probability, 6);
+ estimates.Add(new ModelEstimate(row, p, rate, Rule.Of(p, rate), inCharge));
+ }
+ }
+
+ return estimates;
+ }
+}
+
///
-/// Learning as the live engine sees it (SPEC 11): for each decision it gives the step that notes the examples, then saves
-/// them with the decision. A failure here never stops a decision: the strategy goes on as if there were no model.
+/// Learning as the live engine sees it (SPEC 11): for each decision it gives the steps that note the examples and apply
+/// the multiplier, then saves them with the decision. A failure here never stops a decision: the strategy goes on as if
+/// there were no model.
///
public sealed partial class LearningDesk(Database db, IClock clock, SettingsStore? settings = null, ILogger? logger = null)
{
@@ -26,6 +88,8 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
/// The file of the first model; the one built into the program unless a test gives another.
public FirstModelFile? First { get; init; } = FirstModel.Embedded;
+ public IReadOnlyDictionary BaseRates => First?.BaseRates ?? new Dictionary();
+
private const string HistoryKey = "history";
private sealed record HistoryState(string Fingerprint);
@@ -68,6 +132,16 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
}, cancellationToken).ConfigureAwait(false);
}
+ public async Task CycleAsync(CancellationToken cancellationToken) => await Store.StateAsync(CycleState.Key, cancellationToken).ConfigureAwait(false) ?? new CycleState();
+
+ public async Task GateAsync(CancellationToken cancellationToken)
+ {
+ var (rule, aside) = await LearningSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false);
+ var state = await CycleAsync(cancellationToken).ConfigureAwait(false);
+ return new ModelGate(await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false),
+ await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, BaseRates, state is { ActivatedAt: not null, Aside: null } && !aside);
+ }
+
/// What the decision of needs from learning; null when it could not be prepared.
public async Task PrepareAsync(string strategy, string stage, DateOnly day, BacktestDataset data, Func create, IReadOnlyDictionary? earnings,
CancellationToken cancellationToken)
@@ -81,20 +155,20 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
try
{
- var latest = new Dictionary(await Store.LatestAsync(strategy, cancellationToken).ConfigureAwait(false), StringComparer.Ordinal);
- foreach (var example in latest.Values.Where(e => e.Label is null).ToList())
+ var live = await Store.LiveAsync(strategy, cancellationToken).ConfigureAwait(false);
+ for (var i = 0; i < live.Count; i++)
{
// The operation of the example may have closed with the bars of today, before the nightly labels.
- if (!SingleOperation.NeedsUniverse(strategy) && data[example.Symbol] is { } instrument && instrument.IndexOf(example.Day) >= 0
- && CaseLabels.Of(example, create, data, day) is { } label)
+ if (live[i].Label is null && !SingleOperation.NeedsUniverse(strategy) && data[live[i].Symbol] is { } instrument && instrument.IndexOf(live[i].Day) >= 0
+ && CaseLabels.Of(live[i], create, data, day) is { } label)
{
- latest[example.Symbol] = example with { Label = label };
+ live[i] = live[i] with { Label = label };
}
}
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var outside = await _outside.ReadAsync(clock.UtcNow, specs, earnings, cancellationToken).ConfigureAwait(false);
- return new LearningTurn(strategy, stage, day, latest, outside, clock);
+ return new LearningTurn(strategy, stage, day, live, outside, await GateAsync(cancellationToken).ConfigureAwait(false), clock, ex => LogFailed(_logger, ex, strategy));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
@@ -107,40 +181,160 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
private static partial void LogFailed(ILogger logger, Exception exception, string strategy);
}
-/// The learning side of one decision: the steps it adds and what it saves.
-public sealed class LearningTurn
+///
+/// The last corrective (SPEC 8.5): the multiplier of the model on entries and increases, never on exits nor decreases. A
+/// new operation gets the one of its estimate; one already born keeps its own until it closes, increases included (11.1).
+///
+public sealed class ModelFilter(Func multiplierOf) : IIntentStage
{
- private readonly string _stage;
- private readonly DateOnly _day;
- private readonly IReadOnlyDictionary _latest;
- private readonly IClock _clock;
- private readonly CaseCollector _collector;
+ /// An increase smaller than this share of the reduced size is not made: it would be chasing the rounding every day.
+ public const decimal Band = 0.20m;
- internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyDictionary latest, OutsideView outside, IClock clock)
+ public string Name => "model_filter";
+
+ public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents)
{
- _stage = stage;
- _day = day;
- _latest = latest;
- _clock = clock;
- _collector = new CaseCollector(strategy, IsNew, outside, day);
+ ArgumentNullException.ThrowIfNull(context);
+ ArgumentNullException.ThrowIfNull(intents);
+ return [.. intents.Select(i => i.TargetWeight is > 0m ? Filter(context, i) : i)];
}
- /// The correctives with the steps of learning around them: the examples are noted on what the strategy proposed.
- public IReadOnlyList Around(IReadOnlyList correctives)
+ private Intent Filter(StrategyContext context, Intent intent)
{
- ArgumentNullException.ThrowIfNull(correctives);
- return [_collector, .. correctives];
- }
-
- private bool IsNew(StrategyContext context, Intent intent) => !_latest.TryGetValue(intent.Symbol, out var previous) || !previous.IsOpenAfter(_day);
-
- /// Saves the examples in the transaction of the decision.
- public async Task WriteAsync(DbSession s, Guid decisionId, CancellationToken cancellationToken)
- {
- foreach (var made in _collector.Cases)
+ // Whatever an estimate says, an operation is never made bigger: the multiplier stays between 0 and 1.
+ var multiplier = multiplierOf(context, intent.Symbol);
+ if (!double.IsFinite(multiplier) || multiplier >= 1)
{
- await LearningStore.AddAsync(s, _clock, made with { Source = CaseSources.Live, At = _clock.UtcNow, Stage = _stage, DecisionId = decisionId }, cancellationToken)
- .ConfigureAwait(false);
+ return intent;
+ }
+
+ var filtered = BookWeights.Reduce(context, intent, (decimal)Math.Max(0, multiplier), CorrectiveReasons.ModelFilter);
+ var current = BookWeights.Current(context, intent.Symbol);
+ return current > 0m && filtered.TargetWeight is { } target && target > current && target - current <= Band * target ? filtered with { TargetWeight = null } : filtered;
+ }
+}
+
+/// A step of learning that, when it fails, changes nothing (SPEC 11: the strategies go on without the model).
+internal sealed class SafeStage(IIntentStage inner, Action failed) : IIntentStage
+{
+ public string Name => inner.Name;
+
+ public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents)
+ {
+ try
+ {
+ return inner.Apply(context, intents);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ failed(ex);
+ return intents;
+ }
+ }
+}
+
+/// The learning side of one decision: the steps it adds and what it saves.
+public sealed class LearningTurn
+{
+ private readonly string _strategy;
+ private readonly string _stage;
+ private readonly DateOnly _day;
+ private readonly ILookup _live;
+ private readonly ModelGate _gate;
+ private readonly IClock _clock;
+ private readonly Action _failed;
+ private readonly CaseCollector _collector;
+ private readonly Dictionary> _estimates = new(StringComparer.Ordinal);
+
+ internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyList live, OutsideView outside, ModelGate gate, IClock clock, Action failed)
+ {
+ _strategy = strategy;
+ _stage = stage;
+ _day = day;
+ _live = live.ToLookup(e => e.Symbol, StringComparer.Ordinal);
+ _gate = gate;
+ _clock = clock;
+ _failed = failed;
+ _collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
+ }
+
+ ///
+ /// The correctives with the steps of learning around them: the examples are noted on what the strategy proposed, the
+ /// multiplier comes after every other corrective and before risk.
+ ///
+ public IReadOnlyList Around(IReadOnlyList correctives)
+ {
+ ArgumentNullException.ThrowIfNull(correctives);
+ return [new SafeStage(_collector, _failed), .. correctives, new SafeStage(new ModelFilter(MultiplierOf), _failed)];
+ }
+
+ private bool IsNew(string symbol) => _live[symbol].LastOrDefault() is not { } previous || !previous.IsOpenAfter(_day);
+
+ private double MultiplierOf(StrategyContext context, string symbol)
+ {
+ if (context.Day == _day && _collector.Cases.FirstOrDefault(c => c.Symbol == symbol) is { } made)
+ {
+ return AppliedTo(made);
+ }
+
+ // The operation was born with the latest example before this day: without one the model had nothing to say.
+ return _live[symbol].LastOrDefault(e => e.Day <= context.Day)?.Multiplier ?? 1;
+ }
+
+ private IReadOnlyList EstimatesOf(Example example)
+ {
+ if (!_estimates.TryGetValue(example.Symbol, out var estimates))
+ {
+ _estimates[example.Symbol] = estimates = _gate.Estimate(example);
+ }
+
+ return estimates;
+ }
+
+ private double AppliedTo(Example example) => _gate.Counts && EstimatesOf(example).FirstOrDefault(e => e.InCharge) is { } estimate ? estimate.Multiplier : 1;
+
+ /// Saves the examples, their estimates and the row of the decision, in the transaction of the decision.
+ public async Task WriteAsync(DbSession s, Guid decisionId, Guid? account, DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ foreach (var made in _collector.Cases)
+ {
+ var applied = 1.0;
+ IReadOnlyList estimates = [];
+ try
+ {
+ estimates = EstimatesOf(made);
+ applied = AppliedTo(made);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _failed(ex);
+ }
+
+ var example = made with { Source = CaseSources.Live, At = _clock.UtcNow, Stage = _stage, DecisionId = decisionId, Multiplier = applied };
+ if (await LearningStore.AddAsync(s, _clock, example, cancellationToken).ConfigureAwait(false) is not { } id)
+ {
+ continue;
+ }
+
+ foreach (var estimate in estimates)
+ {
+ await ModelStore.AddPredictionAsync(s, _clock, new PredictionRow(id, estimate.Row.Id, estimate.Probability, estimate.BaseRate, estimate.Multiplier, estimate.InCharge), cancellationToken)
+ .ConfigureAwait(false);
+ if (estimate.InCharge)
+ {
+ await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, _strategy, account, made.Symbol, DecisionStages.Model,
+ applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [],
+ new Dictionary
+ {
+ ["probability"] = estimate.Probability,
+ ["base_rate"] = estimate.BaseRate,
+ ["multiplier"] = estimate.Multiplier,
+ ["applied"] = applied,
+ ["version"] = estimate.Row.Version,
+ ["counts"] = _gate.Counts,
+ }, now), cancellationToken).ConfigureAwait(false);
+ }
+ }
}
}
}
diff --git a/src/Anubis/Learning/LearningSettings.cs b/src/Anubis/Learning/LearningSettings.cs
new file mode 100644
index 0000000..453b54c
--- /dev/null
+++ b/src/Anubis/Learning/LearningSettings.cs
@@ -0,0 +1,29 @@
+using System.Globalization;
+using Anubis.Core;
+
+namespace Anubis.Learning;
+
+/// The settings of the model (SPEC 13.5): the thresholds of the multiplier and the manual set-aside.
+public static class LearningSettings
+{
+ public static readonly SettingDefinition Full = new("learning.full_points", "Taglia piena fino a", "0", ["0", "2", "5"]);
+
+ public static readonly SettingDefinition Zero = new("learning.zero_points", "Niente acquisto da", "10", ["8", "10", "15", "20"]);
+
+ public static readonly SettingDefinition Aside = new("learning.aside", "Modello messo da parte", "off", ["off", "on"]);
+
+ public static readonly IReadOnlyList All = [Full, Zero, Aside];
+
+ public static async Task<(MultiplierRule Rule, bool Aside)> LoadAsync(SettingsStore? settings, CancellationToken cancellationToken)
+ {
+ if (settings is null)
+ {
+ return (MultiplierRule.Standard, false);
+ }
+
+ var full = (await settings.GetAsync(Full.Key, cancellationToken).ConfigureAwait(false)).Value;
+ var zero = (await settings.GetAsync(Zero.Key, cancellationToken).ConfigureAwait(false)).Value;
+ var aside = (await settings.GetAsync(Aside.Key, cancellationToken).ConfigureAwait(false)).Value;
+ return (new MultiplierRule(double.Parse(full, CultureInfo.InvariantCulture) / 100, double.Parse(zero, CultureInfo.InvariantCulture) / 100), aside == "on");
+ }
+}
diff --git a/src/Anubis/Learning/LearningStore.cs b/src/Anubis/Learning/LearningStore.cs
index c109e89..1504a72 100644
--- a/src/Anubis/Learning/LearningStore.cs
+++ b/src/Anubis/Learning/LearningStore.cs
@@ -12,18 +12,23 @@ public sealed class LearningStore(Database db, IClock clock)
"f.id, f.strategy, f.symbol, f.source, f.decided_day, f.decided_at, f.decision_id, f.stage, f.reason, f.weight, f.stop, f.stop_offset, f.features, f.multiplier, " +
"l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
- /// Saves an example as part of the decision that made it. An example already there (same day) stays as it is.
- public static async Task AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
+ /// Saves an example as part of the decision that made it. One already there (same day) stays as it is: null.
+ public static async Task AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(example);
var id = example.Id == Guid.Empty ? Ids.NewId(clock) : example.Id;
- await s.ExecuteAsync(
+ var added = await s.ExecuteAsync(
"INSERT INTO ml_features (id, strategy, symbol, source, decided_day, decided_at, decision_id, stage, reason, weight, stop, stop_offset, features, multiplier, created_at) " +
"VALUES (@id, @s, @sym, @src, @day, @at, @dec, @st, @r, @w, @stop, @off, @f, @m, @now) ON CONFLICT (strategy, symbol, decided_day, source) DO NOTHING", cancellationToken,
("id", id), ("s", example.Strategy), ("sym", example.Symbol), ("src", example.Source), ("day", BarStore.DayText(example.Day)), ("at", example.At),
("dec", example.DecisionId), ("st", example.Stage), ("r", example.Reason), ("w", DbValues.Money(example.Weight)), ("stop", example.Stop), ("off", example.StopOffset),
("f", new DbJson(JsonSerializer.Serialize(example.Features))), ("m", example.Multiplier), ("now", clock.UtcNow)).ConfigureAwait(false);
+ if (added == 0)
+ {
+ return null;
+ }
+
if (example.Label is { } label)
{
await AddLabelAsync(s, clock, id, label, cancellationToken).ConfigureAwait(false);
@@ -56,13 +61,9 @@ public sealed class LearningStore(Database db, IClock clock)
public Task> OpenAsync(CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND l.id IS NULL ORDER BY f.decided_at, f.strategy, f.symbol", Read, ("l", CaseSources.Live)), cancellationToken);
- /// The latest live example of each instrument of a strategy: the one its operation was born with.
- public async Task> LatestAsync(string strategy, CancellationToken cancellationToken)
- {
- var rows = await db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_at", Read, ("l", CaseSources.Live), ("s", strategy)),
- cancellationToken).ConfigureAwait(false);
- return rows.GroupBy(r => r.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last(), StringComparer.Ordinal);
- }
+ /// The live examples of a strategy, oldest first.
+ public Task> LiveAsync(string strategy, CancellationToken cancellationToken) =>
+ db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_day, f.decided_at", Read, ("l", CaseSources.Live), ("s", strategy)), cancellationToken);
public Task CountAsync(string source, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l", ("l", source)), cancellationToken);
diff --git a/src/Anubis/Strategies/Correctives.cs b/src/Anubis/Strategies/Correctives.cs
index a40645b..79345f0 100644
--- a/src/Anubis/Strategies/Correctives.cs
+++ b/src/Anubis/Strategies/Correctives.cs
@@ -8,6 +8,9 @@ public static class CorrectiveReasons
public const string CryptoRegimeAverage = "crypto_regime_below_average";
public const string CryptoRegimeVolatility = "crypto_regime_high_volatility";
public const string CalendarEvent = "calendar_event";
+
+ /// The learning model made the operation smaller (SPEC 11.1).
+ public const string ModelFilter = "model_filter";
}
/// Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them.
diff --git a/src/Anubis/Trading/Decisions.cs b/src/Anubis/Trading/Decisions.cs
index 620a25a..b0452e1 100644
--- a/src/Anubis/Trading/Decisions.cs
+++ b/src/Anubis/Trading/Decisions.cs
@@ -9,6 +9,9 @@ public static class DecisionStages
{
public const string Strategy = "strategy";
public const string Correctives = "correctives";
+
+ /// What the learning model estimated of an entry (SPEC 11.5), whether it counts or not.
+ public const string Model = "model";
public const string Sizing = "sizing";
public const string Risk = "risk";
public const string Order = "order";
diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs
index 68fa0e1..736134b 100644
--- a/src/Anubis/Trading/LiveEngine.cs
+++ b/src/Anubis/Trading/LiveEngine.cs
@@ -857,7 +857,7 @@ public sealed partial class LiveEngine : IDisposable
if (turn is not null)
{
- await turn.WriteAsync(s, decisionId, cancellationToken).ConfigureAwait(false);
+ await turn.WriteAsync(s, decisionId, account, now, cancellationToken).ConfigureAwait(false);
}
foreach (var (symbol, hold, dropped) in plan.Holds)
@@ -968,7 +968,8 @@ public sealed partial class LiveEngine : IDisposable
}, cancellationToken).ConfigureAwait(false);
}
- private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent;
+ private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent
+ or CorrectiveReasons.ModelFilter;
// The news rows go with the news in the diary, the calendar ones with the decisions.
private static string DiaryKind(string code) => code is NewsReasons.Severe or NewsReasons.Negative ? DiaryKinds.News : DiaryKinds.Decisions;
@@ -1322,7 +1323,41 @@ public sealed partial class LiveEngine : IDisposable
/// The bars of a decision, its universe and what is missing on the day of the close.
private sealed record Loaded(BacktestDataset? Data, IReadOnlySet Missing, bool MarketMissing);
- private async Task LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken)
+ ///
+ /// What the nightly labels of learning need (SPEC 11.4): the bars through the last closed day, the instruments of the
+ /// open examples included even when they left the universe, from far enough before the oldest of them.
+ ///
+ public async Task LabelDataAsync(string strategy, IReadOnlyList open, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(open);
+ if (open.Count == 0 || await _stages.GetAsync(strategy, cancellationToken).ConfigureAwait(false) is not { } stage || LastClosed(strategy) is not { } through)
+ {
+ return null;
+ }
+
+ var loaded = await LoadAsync(strategy, through, Book.Empty, provisional: false, cancellationToken, [.. open.Select(e => e.Symbol)], open.Min(e => e.Day).AddDays(-Options.WarmupDays))
+ .ConfigureAwait(false);
+ return loaded.Data is null ? null : new Anubis.Learning.LabelData(loaded.Data, through, () => CreateStrategy(strategy, stage.Qualification?.Parameters))
+ {
+ Earnings = Earnings is null ? null : async (day, ct) => (await Earnings(day, ct).ConfigureAwait(false))?.Next,
+ };
+ }
+
+ // The last day whose bar is final: yesterday in UTC for crypto, the last session closed for a quarter of an hour for stocks.
+ private DateOnly? LastClosed(string strategy)
+ {
+ var now = _clock.UtcNow;
+ if (strategy == StrategyNames.CryptoTrend)
+ {
+ return DateOnly.FromDateTime(now.UtcDateTime).AddDays(-1);
+ }
+
+ var today = Zones.DayIn(now, Zones.NewYork);
+ return _calendar is null ? null : Enumerable.Range(0, 14).Select(i => today.AddDays(-i)).Where(d => _calendar.SessionOn(d) is { } s && s.CloseUtc.AddMinutes(15) <= now).Cast().FirstOrDefault();
+ }
+
+ private async Task LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken, IReadOnlyList? extra = null,
+ DateOnly? since = null)
{
var crypto = strategy == StrategyNames.CryptoTrend;
var venue = crypto ? Venues.Okx : Venues.Alpaca;
@@ -1334,6 +1369,7 @@ public sealed partial class LiveEngine : IDisposable
}
symbols.UnionWith(book.Holdings.Keys);
+ symbols.UnionWith(extra ?? []);
var market = crypto ? NoBot.BitcoinSymbol : StrategyNames.MarketSymbol;
var dataOnly = new HashSet(StringComparer.Ordinal);
if (symbols.Add(market) && !crypto)
@@ -1344,6 +1380,7 @@ public sealed partial class LiveEngine : IDisposable
// The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The
// stock strategies read windows: the warm-up of a trial is enough.
var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
+ from = since < from ? since.Value : from;
var instruments = new List();
var missing = new HashSet(StringComparer.Ordinal);
var currency = crypto ? "EUR" : "USD";
diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs
index 5da1f77..fd9a3e3 100644
--- a/src/Anubis/Trading/ReasonCatalog.cs
+++ b/src/Anubis/Trading/ReasonCatalog.cs
@@ -36,6 +36,7 @@ public static class ReasonCatalog
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
+ ["model_filter"] = "Il modello dava a questa operazione meno probabilità del solito: acquisto rimpicciolito.",
// News and calendar (SPEC 10.5).
["news_severe"] = "Un evento grave e negativo su questo strumento: niente nuovi acquisti per 72 ore.",
["news_negative"] = "Una notizia negativa importante su questo strumento: niente acquisti né aumenti per 24 ore.",
diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs
index 7e712bc..e9bcd54 100644
--- a/src/Anubis/Trading/TradingService.cs
+++ b/src/Anubis/Trading/TradingService.cs
@@ -194,6 +194,7 @@ public sealed partial class TradingService : IDisposable
AccountReady = AccountReady,
Learning = Learning,
};
+ Cycle = new Anubis.Learning.LearningCycle(db, clock, Learning, Engine.LabelDataAsync);
}
private volatile bool _started;
@@ -216,6 +217,9 @@ public sealed partial class TradingService : IDisposable
/// The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.
public LiveEngine Engine { get; }
+ /// The nightly and weekly cycle of the model (SPEC 11.4).
+ public Anubis.Learning.LearningCycle Cycle { get; }
+
private readonly SettingsStore? _settings;
/// Learning beside the decisions (SPEC 11).
@@ -514,6 +518,11 @@ public sealed partial class TradingService : IDisposable
}
}
+ /// The night of the model: once, however long the absence (SPEC 5.6), and beside the others because it is long.
+ public static ScheduledJob ModelJob(Func run) =>
+ new("modello", "Etichette e controllo del modello", Schedule.Daily(new TimeOnly(3, 0), Zones.Rome), run)
+ { MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650), Beside = true };
+
public IReadOnlyList Jobs() =>
[
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
@@ -521,6 +530,7 @@ public sealed partial class TradingService : IDisposable
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
+ ModelJob(Cycle.RunAsync),
.. Engine.Jobs(),
.. _market is null ? Array.Empty() :
[
diff --git a/tests/Anubis.Tests/LearningCasesTests.cs b/tests/Anubis.Tests/LearningCasesTests.cs
index 7753e12..b0c18b7 100644
--- a/tests/Anubis.Tests/LearningCasesTests.cs
+++ b/tests/Anubis.Tests/LearningCasesTests.cs
@@ -221,8 +221,8 @@ public sealed class LearningCasesTests
var example = new Example(Guid.Empty, StrategyNames.EquityMeanrev, "AAPL", CaseSources.Live, First, rig.Clock.UtcNow, "meanrev_entry", 0.123456m, null, 4.25m,
new Dictionary { [Clues.Strength] = 0.1 + 0.2, [Clues.Breadth] = 1 })
{ Stage = StrategyStages.Observation, DecisionId = Ids.NewId(rig.Clock), Multiplier = 0.4 };
- var id = await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false);
- await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false);
+ var id = (await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false))!.Value;
+ Assert.IsNull(await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false), "the same example again");
var read = (await store.AllAsync(none).ConfigureAwait(false)).Single();
Assert.AreEqual((id, example.Symbol, example.Weight, example.Stop, example.StopOffset, example.Stage, example.DecisionId, example.Multiplier),
(read.Id, read.Symbol, read.Weight, read.Stop, read.StopOffset, read.Stage, read.DecisionId, read.Multiplier));
diff --git a/tests/Anubis.Tests/LearningCycleTests.cs b/tests/Anubis.Tests/LearningCycleTests.cs
new file mode 100644
index 0000000..0696118
--- /dev/null
+++ b/tests/Anubis.Tests/LearningCycleTests.cs
@@ -0,0 +1,646 @@
+using Anubis.Backtest;
+using Anubis.Brokers;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Learning;
+using Anubis.Strategies;
+using Anubis.Trading;
+
+namespace Anubis.Tests;
+
+/// The model in the decisions and its cycle: shadow, promotion, drift, set-aside, start (SPEC 11.1, 11.4, 11.5; issue #64).
+[TestClass]
+[TestCategory(Category.Integration)]
+public sealed class LearningCycleTests
+{
+ private static readonly CancellationToken _none = CancellationToken.None;
+
+ private static readonly DateOnly From = new(2026, 6, 1);
+
+ /// A model that always answers .
+ internal static TrainedModel Always(double probability) => new()
+ {
+ Clues = [Clues.Strength],
+ Learned = new Learned { Learner = LearnerNames.Logistic, Linear = new LinearBody(Odds.Logit(probability), [0], [0], [1]) },
+ Ranges = new Dictionary { [Clues.Strength] = new(0, 1, 100) },
+ Strategies = [StrategyNames.CryptoTrend],
+ };
+
+ private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary { [StrategyNames.CryptoTrend] = 0.4 } };
+
+ internal static Task AddModelAsync(Database db, IClock clock, TrainedModel model, string status, int examples = 500) =>
+ db.WriteAsync(s => ModelStore.RegisterAsync(s, clock, model, new ModelReport { Examples = examples, Attempts = [new Attempt(LearnerNames.Logistic, new Scores(), new Scores(), true)] }, status, "test", clock.UtcNow, _none), _none);
+
+ private static Task StateAsync(Database db, IClock clock, CycleState state) => db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, _none), _none);
+
+ // ---- In the decisions -------------------------------------------------------------------------------------------
+
+ private sealed record Run(IReadOnlyList<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> Fills, IReadOnlyList Examples, IReadOnlyList Predictions,
+ IReadOnlyList Rows, int Failures);
+
+ private static async Task LiveAsync(TrainedModel? champion, bool active, TrainedModel? challenger = null, FirstModelFile? rates = null, string stage = StrategyStages.Simulation, int days = 20,
+ Func? before = null)
+ {
+ var last = From.AddDays(days);
+ await using var rig = await LiveRig.CreateAsync(From, last, stage: stage).ConfigureAwait(false);
+ rig.UseFirst(rates ?? Rates);
+ if (champion is not null)
+ {
+ await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, champion, ModelStatuses.Champion).ConfigureAwait(false);
+ }
+
+ if (challenger is not null)
+ {
+ await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, challenger, ModelStatuses.Challenger).ConfigureAwait(false);
+ }
+
+ if (active)
+ {
+ await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }).ConfigureAwait(false);
+ }
+
+ for (var day = From; day <= last; day = day.AddDays(1))
+ {
+ if (before is not null)
+ {
+ await before(rig, day).ConfigureAwait(false);
+ }
+
+ await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
+ }
+
+ var fills = await rig.Rig.QueryAsync("SELECT i.symbol, f.side, f.quantity, f.executed_at FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, i.symbol",
+ r => (r.Text("symbol"), r.Text("side"), r.Money("quantity"), r.Moment("executed_at"))).ConfigureAwait(false);
+ var rows = await rig.Rig.QueryAsync("SELECT symbol, stage, outcome, data FROM decisions WHERE stage = 'model' ORDER BY created_at",
+ r => new DecisionRow(Guid.Empty, "", null, r.TextOrNull("symbol"), r.Text("stage"), r.Text("outcome"), [], new Dictionary { ["json"] = r.TextOrNull("data") }, default)).ConfigureAwait(false);
+ return new Run([.. fills], await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false), await rig.Learning.Models.PredictionsAsync(_none).ConfigureAwait(false), [.. rows], rig.Failures);
+ }
+
+ private static string Text(IEnumerable<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> fills) => string.Join('\n', fills.Select(f => $"{f.Symbol} {f.Side} {f.Quantity} {f.At:MM-dd HH:mm}"));
+
+ /// SPEC 11.5: until it counts, the model notes its estimates beside each operation and changes nothing.
+ [TestMethod]
+ [DataRow(StrategyStages.Simulation)]
+ [DataRow(StrategyStages.Observation)]
+ public async Task InObservationItNotesItsEstimatesAndChangesNothing(string stage)
+ {
+ var without = await LiveAsync(null, active: false, stage: stage).ConfigureAwait(false);
+ var with = await LiveAsync(Always(0.1), active: false, Always(0.6), stage: stage).ConfigureAwait(false);
+ Assert.AreEqual(Text(without.Fills), Text(with.Fills));
+ Assert.IsGreaterThan(1, with.Examples.Count);
+ Assert.IsTrue(with.Examples.All(e => e.Multiplier == 1));
+
+ // Two estimates for each signal: the one in charge, with the multiplier it would apply, and the one on trial.
+ Assert.HasCount(2 * with.Examples.Count, with.Predictions);
+ Assert.IsTrue(with.Predictions.Where(p => p.InCharge).All(p => p is { Multiplier: 0, BaseRate: 0.4 } && Math.Abs(p.Probability - 0.1) < 1e-6));
+ Assert.IsTrue(with.Predictions.Where(p => !p.InCharge).All(p => p.Multiplier == 1));
+ Assert.HasCount(with.Examples.Count, with.Rows);
+ Assert.IsTrue(with.Rows.All(r => r.Outcome == DecisionOutcomes.Passed));
+ Assert.Contains("in osservazione, non cambia niente", Anubis.Server.ReasonTexts.Model((string)with.Rows[0].Data!["json"]!)!);
+ Assert.HasCount(0, without.Predictions);
+ }
+
+ /// When it counts: nothing is ever bigger, exits are the same, the multiplier of birth holds for the increases.
+ [TestMethod]
+ public async Task WhenItCountsItOnlyMakesOperationsSmaller()
+ {
+ var full = await LiveAsync(Always(0.4), active: true).ConfigureAwait(false);
+ var none = await LiveAsync(null, active: false).ConfigureAwait(false);
+ Assert.AreEqual(Text(none.Fills), Text(full.Fills), "who always answers the base rate leaves everything as it is");
+
+ var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
+ Assert.IsTrue(half.Examples.All(e => Math.Abs(e.Multiplier - 0.5) < 1e-3));
+ Assert.IsTrue(half.Rows.All(r => r.Outcome == DecisionOutcomes.Reduced));
+ Assert.Contains("acquisto ridotto al 50%", Anubis.Server.ReasonTexts.Model((string)half.Rows[0].Data!["json"]!)!);
+ decimal Bought(Run run, string symbol) => run.Fills.Where(f => f.Symbol == symbol && f.Side == "buy").Sum(f => f.Quantity);
+ foreach (var symbol in full.Fills.Select(f => f.Symbol).Distinct())
+ {
+ // The first purchase is half, or more where the limits had already cut the whole one.
+ Assert.IsInRange(0.47, 1, (double)(half.Fills.First(f => f.Symbol == symbol).Quantity / full.Fills.First(f => f.Symbol == symbol).Quantity), symbol);
+ Assert.IsLessThanOrEqualTo(Bought(full, symbol), Bought(half, symbol), symbol);
+ }
+
+ Assert.AreEqual(0.5, (double)(half.Fills[0].Quantity / full.Fills[0].Quantity), 0.01, "where no limit cuts");
+
+ // The full exits come on the same days.
+ string Exits(Run run) => string.Join(' ', run.Fills.Where(f => f.Side == "sell").Select(f => f.Symbol + DateOnly.FromDateTime(f.At.UtcDateTime)).Distinct().Order());
+ Assert.Contains(Exits(half), Exits(full), StringComparison.Ordinal);
+
+ var zero = await LiveAsync(Always(0.2), active: true).ConfigureAwait(false);
+ Assert.HasCount(0, zero.Fills);
+ Assert.AreEqual(string.Join(',', full.Examples.Select(e => e.Symbol + e.Day)), string.Join(',', zero.Examples.Select(e => e.Symbol + e.Day)), "the examples do not depend on the model");
+ Assert.IsTrue(zero.Rows.All(r => r.Outcome == DecisionOutcomes.Refused));
+ }
+
+ /// The multiplier is fixed at birth: a model that changes its mind, or is set aside, does not touch an operation already open.
+ [TestMethod]
+ public async Task TheMultiplierIsFixedAtBirth()
+ {
+ async Task Swap(LiveRig rig, DateOnly day)
+ {
+ // After 10 days the model is set aside: new operations are whole again, the ones already born are not.
+ if (day == From.AddDays(10))
+ {
+ await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow, Aside = AsideCodes.Precision }).ConfigureAwait(false);
+ }
+ }
+
+ var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
+ var swapped = await LiveAsync(Always(0.35), active: true, before: Swap).ConfigureAwait(false);
+ Assert.IsTrue(swapped.Examples.Any(e => e.Day >= From.AddDays(9)) && swapped.Fills.Count > 0 && swapped.Examples.Any(e => e.Day < From.AddDays(9)));
+ foreach (var example in swapped.Examples)
+ {
+ Assert.AreEqual(example.Day < From.AddDays(9) ? 0.5 : 1, example.Multiplier, 1e-3, $"{example.Symbol} {example.Day}");
+ }
+
+ // The operations born halved trade exactly as if the model were still there, increases included.
+ foreach (var symbol in swapped.Examples.GroupBy(e => e.Symbol).Where(g => g.All(e => e.Day < From.AddDays(9))).Select(g => g.Key))
+ {
+ Assert.AreEqual(Text(half.Fills.Where(f => f.Symbol == symbol)), Text(swapped.Fills.Where(f => f.Symbol == symbol)));
+ }
+ }
+
+ /// Set aside by the user, or without a base rate for the strategy: multiplier 1, and without a base rate not even an estimate.
+ [TestMethod]
+ public async Task WithoutABaseRateThereIsNoEstimate()
+ {
+ var none = await LiveAsync(null, active: false).ConfigureAwait(false);
+ var run = await LiveAsync(Always(0.1), active: true, rates: new FirstModelFile()).ConfigureAwait(false);
+ Assert.AreEqual(Text(none.Fills), Text(run.Fills));
+ Assert.HasCount(0, run.Predictions);
+ Assert.IsTrue(run.Examples.All(e => e.Multiplier == 1));
+ }
+
+ /// A model that breaks never stops a decision: the strategy goes on as if there were none.
+ [TestMethod]
+ public async Task ABrokenModelNeverStopsADecision()
+ {
+ var none = await LiveAsync(null, active: false).ConfigureAwait(false);
+
+ // A tree that points outside itself throws at every estimate.
+ var broken = Always(0.1) with
+ {
+ Learned = new Learned { Learner = LearnerNames.Boosting, Trees = new TreesBody(0, 1, false, [new Tree([0], [0.5], [7], [9], [true], [0])]) },
+ };
+ var run = await LiveAsync(broken, active: true).ConfigureAwait(false);
+ Assert.AreEqual(Text(none.Fills), Text(run.Fills));
+ Assert.AreEqual(0, run.Failures);
+ Assert.HasCount(0, run.Predictions);
+ Assert.HasCount(none.Examples.Count, run.Examples);
+ }
+
+ /// The filter on its own: never bigger, exits and decreases untouched, no chasing of the rounding.
+ [TestMethod]
+ public void TheFilterNeverMakesAnOrderBigger() => Property.ForAll(
+ gen => (Target: gen.Bool() ? (decimal?)gen.Decimal(0m, 0.5m, 4) : null, Multiplier: gen.Pick([double.NaN, -3, 0, 0.2, 0.5, 0.99, 1, 1.7, 50, double.PositiveInfinity])),
+ x =>
+ {
+ var data = LearningCasesTests.Coins(300, 1);
+ var seen = new List<(Intent Before, Intent After)>();
+ var strategy = new Fixed(x.Target);
+ BacktestEngine.Run(strategy, data, new BacktestOptions
+ {
+ From = data.Sessions[250],
+ To = data.Sessions[256],
+ Correctives = [new Spy(i => seen.Add((i, i))), new ModelFilter((_, _) => x.Multiplier), new Spy(i => seen[^1] = (seen[^1].Before, i))],
+ });
+ foreach (var (before, after) in seen)
+ {
+ Assert.IsTrue(after.TargetWeight is null || after.TargetWeight <= before.TargetWeight, $"{before.TargetWeight} -> {after.TargetWeight}");
+ if (before.TargetWeight is null or 0m || x.Multiplier >= 1 || double.IsNaN(x.Multiplier))
+ {
+ Assert.AreEqual(before.TargetWeight, after.TargetWeight);
+ }
+ }
+ }, 60);
+
+ private sealed class Fixed(decimal? target) : IStrategy
+ {
+ public string Id => "fixed";
+
+ public string Version => "t";
+
+ public IReadOnlyList Schedule() => [DecisionTime.AfterClose];
+
+ public IReadOnlyList Universe(UniverseContext context) => ["BTC-EUR"];
+
+ public IReadOnlyList Decide(StrategyContext context) => [new Intent("BTC-EUR", target, "x")];
+ }
+
+ private sealed class Spy(Action seen) : IIntentStage
+ {
+ public string Name => "spy";
+
+ public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents)
+ {
+ foreach (var intent in intents)
+ {
+ seen(intent);
+ }
+
+ return intents;
+ }
+ }
+
+ // ---- The nightly cycle ------------------------------------------------------------------------------------------
+
+ /// An archive with a model in charge, and what the cycle needs to run on it.
+ private sealed class Night : IAsyncDisposable
+ {
+ private int _count;
+
+ public TradingRig Rig { get; private set; } = null!;
+
+ public LearningDesk Desk { get; private set; } = null!;
+
+ public LearningCycle Cycle { get; private set; } = null!;
+
+ public ModelRow Champion { get; private set; } = null!;
+
+ public static async Task CreateAsync()
+ {
+ var night = new Night { Rig = await TradingRig.CreateAsync().ConfigureAwait(false) };
+ night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero)); // A Wednesday, 03:00 in Rome.
+ night.Desk = new LearningDesk(night.Rig.Db, night.Rig.Clock) { First = Rates };
+ night.Cycle = new LearningCycle(night.Rig.Db, night.Rig.Clock, night.Desk, (_, _, _) => Task.FromResult(null));
+ await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { LastSunday = new DateOnly(2027, 2, 28) }).ConfigureAwait(false);
+ night.Champion = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
+ return night;
+ }
+
+ /// A closed signal with what each model said when it was born, the first one in charge.
+ public async Task CaseAsync(bool win, double result = 0.02, string stage = StrategyStages.Simulation, IReadOnlyDictionary? features = null, params (ModelRow Model, double P)[] said)
+ {
+ var day = new DateOnly(2025, 1, 1).AddDays(_count++);
+ await Rig.Db.WriteAsync(async s =>
+ {
+ var id = (await LearningStore.AddAsync(s, Rig.Clock, new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
+ "trend_entry", 0.2m, null, null, features ?? new Dictionary { [Clues.Strength] = 0.5 })
+ { Stage = stage, Label = new CaseLabel(win, win ? result : -result, day.AddDays(1), day.AddDays(1), "x") }, _none).ConfigureAwait(false))!.Value;
+ foreach (var (model, p) in said)
+ {
+ await ModelStore.AddPredictionAsync(s, Rig.Clock, new PredictionRow(id, model.Id, p, 0.4, MultiplierRule.Standard.Of(p, 0.4), model.Id == Champion.Id), _none).ConfigureAwait(false);
+ }
+ }, _none).ConfigureAwait(false);
+ }
+
+ public async Task RunAsync()
+ {
+ await Cycle.RunAsync(_none).ConfigureAwait(false);
+ return (await DiaryAsync().ConfigureAwait(false)).LastOrDefault() ?? "";
+ }
+
+ public void ToSunday() => Rig.Clock.Set(new DateTimeOffset(2027, 3, 7, 2, 0, 0, TimeSpan.Zero));
+
+ public Task> DiaryAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE kind = 'Apprendimento' ORDER BY occurred_at, id", r => r.Text("message")), _none);
+
+ public Task> NotificationsAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT kind FROM notifications ORDER BY created_at, id", r => r.Text("kind")), _none);
+
+ public async Task StatusAsync(Guid id) => (await Desk.Models.AllAsync(_none).ConfigureAwait(false)).Single(m => m.Id == id).Status;
+
+ public ValueTask DisposeAsync() => Rig.DisposeAsync();
+ }
+
+ /// SPEC 11.4, 5.6: one run labels what matured and says once that nothing is wrong.
+ [TestMethod]
+ public async Task TheNightLabelsWhatMaturedAndSaysItOnce()
+ {
+ var last = From.AddDays(24);
+ await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
+ rig.UseFirst(Rates);
+ await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
+ for (var day = From; day <= last; day = day.AddDays(1))
+ {
+ await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
+ }
+
+ var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
+ var open = (await rig.Learning.Store.OpenAsync(_none).ConfigureAwait(false)).Count;
+ await cycle.RunAsync(_none).ConfigureAwait(false);
+ await cycle.RunAsync(_none).ConfigureAwait(false);
+ var after = await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false);
+ Assert.IsGreaterThan(0, open - after.Count(e => e.Label is null));
+
+ // The labels are those of the history on the same bars.
+ var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR");
+ foreach (var example in after)
+ {
+ Assert.AreEqual(CaseLabels.Of(example, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, last.AddDays(-1)), example.Label);
+ }
+
+ var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
+ Assert.AreEqual("Controllo del modello: nessuna anomalia.", diary.Single());
+ }
+
+ /// SPEC 5.6: off for three nights, the job of the model runs once at the return, labels what matured meanwhile and says one line.
+ [TestMethod]
+ public async Task AfterThreeDaysOffLabelsAndCheckAreMadeOnce()
+ {
+ var off = From.AddDays(14);
+ var last = From.AddDays(24);
+ await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
+ rig.UseFirst(Rates);
+ await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
+ for (var day = From; day <= off; day = day.AddDays(1))
+ {
+ await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
+ }
+
+ var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
+ await cycle.RunAsync(_none).ConfigureAwait(false);
+ var labelled = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null);
+ var went = rig.Rig.Clock.UtcNow;
+
+ // Back on the fourth day, with the bars of the meantime already there: the real job of the engine, as it is registered.
+ for (var day = off; day < last; day = day.AddDays(1))
+ {
+ await rig.StoreBarAsync(day).ConfigureAwait(false);
+ }
+
+ rig.Rig.Clock.Set(new DateTimeOffset(last.ToDateTime(new TimeOnly(9, 0)), TimeSpan.Zero));
+ var runs = 0;
+ var scheduler = new Scheduler(rig.Rig.Clock, new EventBus());
+ scheduler.Add(TradingService.ModelJob(async ct =>
+ {
+ await cycle.RunAsync(ct).ConfigureAwait(false);
+ runs++;
+ }), went);
+ await scheduler.RunDueAsync(_none).ConfigureAwait(false);
+ await scheduler.RunDueAsync(_none).ConfigureAwait(false);
+ for (var i = 0; i < 600 && runs == 0; i++)
+ {
+ await Task.Delay(50, _none).ConfigureAwait(false);
+ }
+
+ await scheduler.RunDueAsync(_none).ConfigureAwait(false);
+ Assert.AreEqual(1, runs, "one run for all the missed nights");
+ var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
+ Assert.HasCount(2, diary, "one line before and one at the return");
+ Assert.IsGreaterThan(labelled, (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null), "what matured meanwhile has its label");
+ }
+
+ /// The challenger replaces the one in charge only at a threshold and only when the advantage is not chance; one click takes it back.
+ [TestMethod]
+ public async Task AChallengerThatIsReallyBetterIsPromotedAtAThreshold()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
+ var gen = new Gen(3);
+ for (var i = 0; i < 99; i++)
+ {
+ var win = gen.Double() < 0.4;
+ await night.CaseAsync(win, said: [(night.Champion, 0.4), (challenger, win ? 0.6 : 0.25)]).ConfigureAwait(false);
+ }
+
+ night.ToSunday();
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "99 cases: no decision yet");
+
+ await night.CaseAsync(true, said: [(night.Champion, 0.4), (challenger, 0.6)]).ConfigureAwait(false);
+ night.Rig.Clock.Advance(TimeSpan.FromDays(3));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "100 cases but not a Sunday");
+
+ night.Rig.Clock.Advance(TimeSpan.FromDays(4));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
+ Assert.AreEqual(ModelStatuses.Retired, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
+ CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_promoted");
+
+ Assert.IsTrue(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false));
+ Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
+ Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
+ Assert.IsFalse(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false), "only once");
+ night.Rig.Clock.Advance(TimeSpan.FromDays(7));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "what the user took back does not come back");
+ }
+
+ /// An advantage that is chance never promotes; after 300 cases the challenger is discarded. Between thresholds nothing is decided.
+ [TestMethod]
+ public async Task AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
+ var gen = new Gen(8);
+ night.ToSunday();
+ for (var i = 0; i < 300; i++)
+ {
+ await night.CaseAsync(gen.Double() < 0.4, said: [(night.Champion, 0.4), (challenger, 0.4 + (gen.Double() * 0.1) - 0.05)]).ConfigureAwait(false);
+ if (i is 99 or 120 or 260)
+ {
+ night.Rig.Clock.Advance(TimeSpan.FromDays(7));
+ await night.RunAsync().ConfigureAwait(false);
+ var row = (await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false))!;
+ Assert.AreEqual(i switch { 99 or 120 => 100, _ => 250 }, row.ThresholdDone);
+ }
+ }
+
+ night.Rig.Clock.Advance(TimeSpan.FromDays(7));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(ModelStatuses.Discarded, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
+ Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
+ Assert.IsTrue((await night.DiaryAsync().ConfigureAwait(false)).Any(d => d.StartsWith("Scartata la versione", StringComparison.Ordinal)));
+ }
+
+ /// On Sunday, without a challenger and with new outcomes, one is trained; a Sunday missed while off is done at the next run, once.
+ [TestMethod]
+ public async Task OnSundayAChallengerIsTrainedOnce()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ await night.Rig.Db.WriteAsync(async s =>
+ {
+ foreach (var example in LearningModelTests.Cases(300, x => Odds.Probability(x[1]), source: CaseSources.Live))
+ {
+ await LearningStore.AddAsync(s, night.Rig.Clock, example, _none).ConfigureAwait(false);
+ }
+ }, _none).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNull(await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false), "a Wednesday");
+
+ // Off from Wednesday to the Tuesday after two Sundays: one training at the return.
+ night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 16, 9, 0, 0, TimeSpan.Zero));
+ await night.RunAsync().ConfigureAwait(false);
+ var challenger = await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
+ Assert.AreEqual((2, 300), (challenger!.Version, challenger.Examples));
+ await night.RunAsync().ConfigureAwait(false);
+ var all = await night.Desk.Models.AllAsync(_none).ConfigureAwait(false);
+ Assert.HasCount(4, all, "champion, challenger and its two attempts");
+ Assert.HasCount(1, all.Where(m => m.Status == ModelStatuses.Challenger));
+
+ // On trial it is never retrained, and without new outcomes the next one is not trained either.
+ night.Rig.Clock.Advance(TimeSpan.FromDays(7));
+ await night.RunAsync().ConfigureAwait(false);
+ await night.Rig.Db.WriteAsync(s => ModelStore.SetStatusAsync(s, night.Rig.Clock, challenger.Id, ModelStatuses.Discarded, _none), _none).ConfigureAwait(false);
+ night.Rig.Clock.Advance(TimeSpan.FromDays(7));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.HasCount(4, await night.Desk.Models.AllAsync(_none).ConfigureAwait(false));
+ }
+
+ /// Precision under 50% on at least 40 cases: set aside, said once, until it comes back.
+ [TestMethod]
+ public async Task ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ for (var i = 0; i < 39; i++)
+ {
+ // Always wrong: what it says is likely loses.
+ await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.35 : 0.42)]).ConfigureAwait(false);
+ }
+
+ Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
+ await night.CaseAsync(false, said: [(night.Champion, 0.42)]).ConfigureAwait(false);
+ night.Rig.Clock.Advance(TimeSpan.FromDays(1));
+ Assert.Contains("lo metto da parte", (await night.RunAsync().ConfigureAwait(false)).ToLowerInvariant());
+ Assert.AreEqual(AsideCodes.Precision, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
+ night.Rig.Clock.Advance(TimeSpan.FromDays(1));
+ Assert.Contains("resta da parte", await night.RunAsync().ConfigureAwait(false));
+ for (var i = 0; i < 60; i++)
+ {
+ await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.45 : 0.35)]).ConfigureAwait(false);
+ }
+
+ night.Rig.Clock.Advance(TimeSpan.FromDays(1));
+ Assert.Contains("rientrata dopo 2 giorni", await night.RunAsync().ConfigureAwait(false));
+ Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
+ CollectionAssert.AreEqual(new[] { "model_set_aside", "model_back" }, await night.NotificationsAsync().ConfigureAwait(false));
+ }
+
+ /// While it is set aside, by itself or by the user, the gate lets everything through.
+ [TestMethod]
+ public async Task SetAsideMeansMultiplierOne()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ var settings = new SettingsStore(night.Rig.Db, night.Rig.Clock, new EventBus());
+ var desk = new LearningDesk(night.Rig.Db, night.Rig.Clock, settings) { First = Rates };
+ Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "in observation");
+ await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow }).ConfigureAwait(false);
+ Assert.IsTrue((await desk.GateAsync(_none).ConfigureAwait(false)).Counts);
+ await settings.SetAsync(LearningSettings.Aside.Key, "on", "test", _none).ConfigureAwait(false);
+ Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by the user");
+ await settings.SetAsync(LearningSettings.Aside.Key, "off", "test", _none).ConfigureAwait(false);
+ await settings.SetAsync(LearningSettings.Zero.Key, "20", "test", _none).ConfigureAwait(false);
+ Assert.AreEqual(new MultiplierRule(0, 0.20), (await desk.GateAsync(_none).ConfigureAwait(false)).Rule);
+ await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow, Aside = AsideCodes.ClueDrift }).ConfigureAwait(false);
+ Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by itself");
+ }
+
+ /// The error rises: ADWIN sees it and the model is set aside.
+ [TestMethod]
+ public async Task ARisingErrorSetsTheModelAside()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ for (var i = 0; i < 120; i++)
+ {
+ var win = i % 5 < 2;
+ await night.CaseAsync(win, said: [(night.Champion, win ? 0.95 : 0.05)]).ConfigureAwait(false);
+ }
+
+ Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
+ for (var i = 0; i < 24; i++)
+ {
+ // Still more right than wrong on the last 60, but suddenly much worse.
+ var win = i % 5 < 2;
+ await night.CaseAsync(win, said: [(night.Champion, win ? 0.1 : 0.9)]).ConfigureAwait(false);
+ }
+
+ night.Rig.Clock.Advance(TimeSpan.FromDays(1));
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(AsideCodes.ErrorDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
+ }
+
+ /// The clues leave what the model studied: set aside, naming them. The clues not in use do not count.
+ [TestMethod]
+ public async Task CluesNeverStudiedSetTheModelAside()
+ {
+ await using var night = await Night.CreateAsync().ConfigureAwait(false);
+ for (var i = 0; i < 60; i++)
+ {
+ await night.CaseAsync(i % 5 < 2, features: new Dictionary { [Clues.Strength] = i < 48 ? 0.5 : 3, [Clues.Vix] = 900 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
+ }
+
+ Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false), "a fifth is not more than a fifth");
+ for (var i = 0; i < 4; i++)
+ {
+ await night.CaseAsync(false, features: new Dictionary { [Clues.Strength] = 3 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
+ }
+
+ night.Rig.Clock.Advance(TimeSpan.FromDays(1));
+ Assert.Contains("forza della tendenza", await night.RunAsync().ConfigureAwait(false));
+ Assert.AreEqual(AsideCodes.ClueDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
+ }
+
+ /// SPEC 11.5: it starts to count with 300 signals, good calibration and a gain that is not chance, and only all three.
+ [TestMethod]
+ public async Task ItStartsToCountOnlyWithAllThreeCriteria()
+ {
+ // 40% of wins: 48% among those estimated 0.48, 28% among those estimated 0.28.
+ async Task Fill(Night night, int count, Func said, string stage = StrategyStages.Simulation)
+ {
+ for (var i = 0; i < count; i++)
+ {
+ var high = i % 5 < 3;
+ var win = high ? i % 25 is 0 or 1 or 5 or 6 or 10 or 11 or 15 : i % 25 is 3 or 8 or 13;
+ await night.CaseAsync(win, stage: stage, said: [(night.Champion, said(i))]).ConfigureAwait(false);
+ }
+ }
+
+ static double Calibrated(int i) => i % 5 < 3 ? 0.47 : 0.30;
+ await using (var night = await Night.CreateAsync().ConfigureAwait(false))
+ {
+ await Fill(night, 299, Calibrated).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "299 signals");
+ await Fill(night, 1, Calibrated).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNotNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt);
+ CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_activated");
+ }
+
+ await using (var night = await Night.CreateAsync().ConfigureAwait(false))
+ {
+ await Fill(night, 320, i => i % 5 < 3 ? 0.75 : 0.15).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "badly calibrated");
+ }
+
+ await using (var night = await Night.CreateAsync().ConfigureAwait(false))
+ {
+ await Fill(night, 320, _ => 0.41).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no improvement");
+ }
+
+ await using (var night = await Night.CreateAsync().ConfigureAwait(false))
+ {
+ await Fill(night, 320, Calibrated, StrategyStages.Observation).ConfigureAwait(false);
+ await night.RunAsync().ConfigureAwait(false);
+ Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no signal of a strategy with capital");
+ }
+ }
+
+ /// ADWIN on known cases: a jump is seen, its direction too, noise alone is not.
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AdwinSeesAJumpAndNotTheNoise()
+ {
+ var alarms = 0;
+ for (var seed = 0; seed < 50; seed++)
+ {
+ var gen = new Gen(seed);
+ var adwin = new Adwin();
+ alarms += Enumerable.Range(0, 400).Any(_ => adwin.Add(gen.Double()) != 0) ? 1 : 0;
+ }
+
+ Assert.IsLessThanOrEqualTo(2, alarms, "false alarms on noise");
+ var up = new Adwin();
+ var random = new Gen(1);
+ var found = Enumerable.Range(0, 200).Select(i => (i, Change: up.Add((i < 100 ? 0.2 : 0.6) + (random.Double() * 0.2)))).First(x => x.Change != 0);
+ Assert.AreEqual(1, found.Change);
+ Assert.IsTrue(found.i is >= 100 and < 140, $"{found.i}");
+ Assert.IsLessThan(40, up.Count - (200 - found.i - 1), "the older part is dropped");
+ var down = new Adwin();
+ Assert.AreEqual(-1, Enumerable.Range(0, 200).Select(i => down.Add(i < 100 ? 0.8 : 0.2)).First(c => c != 0));
+ }
+}
diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs
index 79afb8d..054c295 100644
--- a/tests/Anubis.Tests/LiveSupport.cs
+++ b/tests/Anubis.Tests/LiveSupport.cs
@@ -110,10 +110,23 @@ internal sealed class LiveRig : IAsyncDisposable
{
AccountReady = _ => AccountStarted,
Gate = Gate,
- Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock),
+ Learning = Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock) { First = First },
};
}
+ public Anubis.Learning.LearningDesk Learning { get; private set; } = null!;
+
+ /// The first model and the base rates the engine starts from.
+ public Anubis.Learning.FirstModelFile? First { get; private set; } = Anubis.Learning.FirstModel.Embedded;
+
+ /// The engine again, with other base rates.
+ public void UseFirst(Anubis.Learning.FirstModelFile? first)
+ {
+ First = first;
+ Engine.Dispose();
+ Build();
+ }
+
/// The rules of SPEC 10.5 the engine applies to purchases and stops; none unless a test sets them.
public News.IEntryGate? Gate { get; private set; }