Let the model shrink entries once it has earned it and watch it every night

The multiplier is the last corrective and is fixed when an operation is
born. Until the criteria of SPEC 11.5 are met the estimates are only noted
beside each operation. Every night the outcomes are labelled and the model
is checked (precision, ADWIN on the error, clues never studied) and set
aside when it is wrong; every Sunday a challenger is trained or judged.

refs #64

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 12:02:55 +01:00
1 parent 99ff2d9402
commit df21962da3
16 files changed
+1615 -52

No files matched your search

+36
View File
@@ -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);
}
}
/// <summary>What the model said of an entry (SPEC 11.5): its estimate, the usual share of gains, what it changed.</summary>
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)
{
+1 -1
View File
@@ -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<SettingDefinition> 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<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
+235
View File
@@ -0,0 +1,235 @@
using Anubis.Core;
namespace Anubis.Learning;
/// <summary>An estimate saved when its example was born, with the model that made it.</summary>
public sealed record SeenEstimate(Guid ModelId, bool InCharge, Estimate Estimate);
/// <summary>A week of the watch: the precision on the last cases closed by its end.</summary>
public sealed record WeekPrecision(DateOnly Monday, double Precision, int Cases);
/// <summary>What the nightly check saw (SPEC 11.4).</summary>
public sealed record HealthCheck
{
public DateTimeOffset At { get; init; }
/// <summary>On the last <see cref="Health.Recent"/> cases of the model in charge; null without both wins and losses.</summary>
public double? Precision { get; init; }
public int Cases { get; init; }
public bool ErrorDrift { get; init; }
/// <summary>The groups of clues whose values are too often outside what the model studied.</summary>
public IReadOnlyList<string> DriftingClues { get; init; } = [];
/// <summary>Why the model should stay aside; null when nothing is wrong.</summary>
public string? Aside { get; init; }
}
/// <summary>
/// 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.
/// </summary>
public sealed class Adwin(double delta = 0.002)
{
private const int MinPart = 10;
private readonly List<double> _window = [];
public int Count => _window.Count;
/// <summary>Adds a value between 0 and 1: 1 when the mean has risen, -1 when it has fallen, 0 when nothing changed.</summary>
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;
}
}
/// <summary>The rules that set the model aside (SPEC 11.4, ADR 0018).</summary>
public static class Health
{
public const int Recent = 60;
/// <summary>The precision counts from this many cases.</summary>
public const int MinCases = 40;
public const double Alarm = 0.50;
/// <summary>An alarm of the error lasts for this many labelled cases.</summary>
public const int AlarmCases = 30;
/// <summary>A clue drifts when more than this share of the recent cases is outside the 1%–99% it was studied on.</summary>
public const double OutsideShare = 0.20;
/// <summary>
/// The check on the estimates of the model in charge, the ones it made on trial included: <paramref name="labelled"/> in
/// the order the outcomes came, <paramref name="recent"/> the latest live examples with or without an outcome.
/// </summary>
public static HealthCheck Check(ModelRow champion, IReadOnlyList<Estimate> labelled, IReadOnlyList<Example> 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,
};
}
/// <summary>The squared error has risen within the last cases. Computed from the beginning each time: no state to lose.</summary>
public static bool ErrorDrift(IReadOnlyList<Estimate> 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<string> ClueDrift(TrainedModel model, IReadOnlyList<Example> 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<string>();
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)];
}
/// <summary>The precision week by week: each on the last cases closed by its end, when they are enough.</summary>
public static IReadOnlyList<WeekPrecision> Weeks(IReadOnlyList<Estimate> labelled, DateOnly today, int weeks = 8)
{
ArgumentNullException.ThrowIfNull(labelled);
var monday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
var result = new List<WeekPrecision>();
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;
}
}
/// <summary>Whether the model may start to count (SPEC 11.5).</summary>
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;
/// <summary>
/// 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.
/// </summary>
public static ActivationCheck Of(IReadOnlyList<Estimate> inCharge, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> 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);
}
/// <summary>A signal of a strategy that had capital: zeroing those of a candidate in observation is no merit (SPEC 11.3).</summary>
public static bool IsFunded(Example example) => example?.Stage is { } stage && stage != Trading.StrategyStages.Observation;
}
/// <summary>The trial of the challenger against the model in charge (SPEC 11.4).</summary>
public sealed record TrialCheck(int Pairs, int Threshold, double Low, double High, double Mean, double ChallengerPrecision, double ChampionPrecision)
{
public static readonly IReadOnlyList<int> Thresholds = [100, 150, 200, 250, 300];
/// <summary>Pairs of estimates on the same example, both with their outcome, in the order the outcomes came.</summary>
public static TrialCheck Of(IReadOnlyList<(Estimate Champion, Estimate Challenger)> pairs, IReadOnlyDictionary<string, double> 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);
}
/// <summary>The advantage of the challenger cannot be told from chance unless the whole interval is above zero.</summary>
public bool Wins => Low > 0;
}
+338
View File
@@ -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;
/// <summary>What the labels of a strategy need: the collected bars, through which closed day, its rules, the first report after a day.</summary>
public sealed record LabelData(BacktestDataset Data, DateOnly Through, Func<IStrategy> Create)
{
public Func<DateOnly, CancellationToken, Task<IReadOnlyDictionary<string, DateOnly>?>>? Earnings { get; init; }
}
/// <summary>Everything the models saw, put together once: the page and the nightly check read the same numbers.</summary>
public sealed record LearningSnapshot(IReadOnlyList<Example> Examples, IReadOnlyList<SeenEstimate> Labelled, IReadOnlyList<ModelRow> Models, CycleState State)
{
public ModelRow? Champion => Models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
public ModelRow? Challenger => Models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
/// <summary>The estimates that counted when each signal came, with their outcome, in the order the outcomes came.</summary>
public IReadOnlyList<Estimate> InCharge => [.. Labelled.Where(e => e.InCharge).Select(e => e.Estimate)];
public IReadOnlyList<Estimate> 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<LearningSnapshot> 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));
}
}
/// <summary>
/// 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.
/// </summary>
public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, Func<string, IReadOnlyList<Example>, CancellationToken, Task<LabelData?>> 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 -------------------------------------------------------------------------------------------------
/// <summary>The outcome of the examples whose simulated operation closed. Returns how many.</summary>
public async Task<int> 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 --------------------------------------------------------------------------------------------------
/// <summary>The check of the model in charge: set aside or back, and whether it may start to count.</summary>
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 -------------------------------------------------------------------------------------------------
/// <summary>The weekly part, once for each Sunday; a Sunday missed while the bot was off is done at the next run.</summary>
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);
/// <summary>The trial: a decision only when the cases have passed a new threshold (SPEC 11.4).</summary>
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 ---------------------------------------------------------------------------------------------------
/// <summary>Takes back the last promotion (SPEC 11.4): the model it replaced is in charge again. False when there is nothing to take back.</summary>
public Task<bool> UndoPromotionAsync(CancellationToken cancellationToken) => UndoPromotionAsync(db, clock, cancellationToken);
public static Task<bool> 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 --------------------------------------------------------------------------------------------------
/// <summary>The capital of each strategy in euro; the reference one (SPEC 8.6) for a strategy that has none yet.</summary>
public Task<IReadOnlyDictionary<string, double>> CapitalsAsync(CancellationToken cancellationToken) => CapitalsAsync(db, clock, cancellationToken);
public static async Task<IReadOnlyDictionary<string, double>> CapitalsAsync(Database db, IClock clock, CancellationToken cancellationToken)
{
var capitals = new Dictionary<string, double>(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<IReadOnlyList<(string Strategy, decimal Capital)>> 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<IReadOnlySet<string>> 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..];
}
+229 -35
View File
@@ -10,9 +10,71 @@ using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.Learning;
/// <summary>Where the learning cycle is: whether the model counts, whether it is set aside and why, what ran last.</summary>
public sealed record CycleState
{
public const string Key = "cycle";
/// <summary>When the criteria of SPEC 11.5 were met: from then on the model shrinks operations. Null: in observation.</summary>
public DateTimeOffset? ActivatedAt { get; init; }
/// <summary>Why the model is set aside on its own (<see cref="AsideCodes"/>); null when it is not.</summary>
public string? Aside { get; init; }
public DateTimeOffset? AsideAt { get; init; }
/// <summary>The last night checked and the last Sunday done, as dates in Rome.</summary>
public DateOnly? LastNight { get; init; }
public DateOnly? LastSunday { get; init; }
/// <summary>The labelled examples the last training saw.</summary>
public int TrainedOn { get; init; }
public HealthCheck? Health { get; init; }
}
/// <summary>Why a model is set aside on its own (SPEC 11.4).</summary>
public static class AsideCodes
{
public const string Precision = "precision";
public const string ErrorDrift = "error_drift";
public const string ClueDrift = "clue_drift";
}
/// <summary>What a model says of a new example. <see cref="Multiplier"/> is what it would apply; it counts only when the gate says so.</summary>
public sealed record ModelEstimate(ModelRow Row, double Probability, double BaseRate, double Multiplier, bool InCharge);
/// <summary>What decides about the operations at a decision: the model in charge, the one on trial, and whether it counts.</summary>
public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, MultiplierRule Rule, IReadOnlyDictionary<string, double> BaseRates, bool Counts)
{
/// <summary>Without a model, or without a base rate for the strategy, there is no estimate (ADR 0018).</summary>
public IReadOnlyList<ModelEstimate> Estimate(Example example)
{
ArgumentNullException.ThrowIfNull(example);
if (!BaseRates.TryGetValue(example.Strategy, out var rate))
{
return [];
}
var estimates = new List<ModelEstimate>();
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;
}
}
/// <summary>
/// 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.
/// </summary>
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
/// <summary>The file of the first model; the one built into the program unless a test gives another.</summary>
public FirstModelFile? First { get; init; } = FirstModel.Embedded;
public IReadOnlyDictionary<string, double> BaseRates => First?.BaseRates ?? new Dictionary<string, double>();
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<CycleState> CycleAsync(CancellationToken cancellationToken) => await Store.StateAsync<CycleState>(CycleState.Key, cancellationToken).ConfigureAwait(false) ?? new CycleState();
public async Task<ModelGate> 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);
}
/// <summary>What the decision of <paramref name="day"/> needs from learning; null when it could not be prepared.</summary>
public async Task<LearningTurn?> PrepareAsync(string strategy, string stage, DateOnly day, BacktestDataset data, Func<IStrategy> create, IReadOnlyDictionary<string, DateOnly>? earnings,
CancellationToken cancellationToken)
@@ -81,20 +155,20 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
try
{
var latest = new Dictionary<string, Example>(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);
}
/// <summary>The learning side of one decision: the steps it adds and what it saves.</summary>
public sealed class LearningTurn
/// <summary>
/// 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).
/// </summary>
public sealed class ModelFilter(Func<StrategyContext, string, double> multiplierOf) : IIntentStage
{
private readonly string _stage;
private readonly DateOnly _day;
private readonly IReadOnlyDictionary<string, Example> _latest;
private readonly IClock _clock;
private readonly CaseCollector _collector;
/// <summary>An increase smaller than this share of the reduced size is not made: it would be chasing the rounding every day.</summary>
public const decimal Band = 0.20m;
internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyDictionary<string, Example> latest, OutsideView outside, IClock clock)
public string Name => "model_filter";
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> 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)];
}
/// <summary>The correctives with the steps of learning around them: the examples are noted on what the strategy proposed.</summary>
public IReadOnlyList<IIntentStage> Around(IReadOnlyList<IIntentStage> 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);
/// <summary>Saves the examples in the transaction of the decision.</summary>
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;
}
}
/// <summary>A step of learning that, when it fails, changes nothing (SPEC 11: the strategies go on without the model).</summary>
internal sealed class SafeStage(IIntentStage inner, Action<Exception> failed) : IIntentStage
{
public string Name => inner.Name;
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
{
try
{
return inner.Apply(context, intents);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed(ex);
return intents;
}
}
}
/// <summary>The learning side of one decision: the steps it adds and what it saves.</summary>
public sealed class LearningTurn
{
private readonly string _strategy;
private readonly string _stage;
private readonly DateOnly _day;
private readonly ILookup<string, Example> _live;
private readonly ModelGate _gate;
private readonly IClock _clock;
private readonly Action<Exception> _failed;
private readonly CaseCollector _collector;
private readonly Dictionary<string, IReadOnlyList<ModelEstimate>> _estimates = new(StringComparer.Ordinal);
internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyList<Example> live, OutsideView outside, ModelGate gate, IClock clock, Action<Exception> 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);
}
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<IIntentStage> Around(IReadOnlyList<IIntentStage> 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<ModelEstimate> 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;
/// <summary>Saves the examples, their estimates and the row of the decision, in the transaction of the decision.</summary>
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<ModelEstimate> 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<string, object?>
{
["probability"] = estimate.Probability,
["base_rate"] = estimate.BaseRate,
["multiplier"] = estimate.Multiplier,
["applied"] = applied,
["version"] = estimate.Row.Version,
["counts"] = _gate.Counts,
}, now), cancellationToken).ConfigureAwait(false);
}
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System.Globalization;
using Anubis.Core;
namespace Anubis.Learning;
/// <summary>The settings of the model (SPEC 13.5): the thresholds of the multiplier and the manual set-aside.</summary>
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<SettingDefinition> 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");
}
}
+11 -10
View File
@@ -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";
/// <summary>Saves an example as part of the decision that made it. An example already there (same day) stays as it is.</summary>
public static async Task<Guid> AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
/// <summary>Saves an example as part of the decision that made it. One already there (same day) stays as it is: null.</summary>
public static async Task<Guid?> 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<List<Example>> 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);
/// <summary>The latest live example of each instrument of a strategy: the one its operation was born with.</summary>
public async Task<IReadOnlyDictionary<string, Example>> 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);
}
/// <summary>The live examples of a strategy, oldest first.</summary>
public Task<List<Example>> 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<long> CountAsync(string source, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l", ("l", source)), cancellationToken);
+3
View File
@@ -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";
/// <summary>The learning model made the operation smaller (SPEC 11.1).</summary>
public const string ModelFilter = "model_filter";
}
/// <summary>Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them.</summary>
+3
View File
@@ -9,6 +9,9 @@ public static class DecisionStages
{
public const string Strategy = "strategy";
public const string Correctives = "correctives";
/// <summary>What the learning model estimated of an entry (SPEC 11.5), whether it counts or not.</summary>
public const string Model = "model";
public const string Sizing = "sizing";
public const string Risk = "risk";
public const string Order = "order";
+40 -3
View File
@@ -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
/// <summary>The bars of a decision, its universe and what is missing on the day of the close.</summary>
private sealed record Loaded(BacktestDataset? Data, IReadOnlySet<string> Missing, bool MarketMissing);
private async Task<Loaded> LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken)
/// <summary>
/// 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.
/// </summary>
public async Task<Anubis.Learning.LabelData?> LabelDataAsync(string strategy, IReadOnlyList<Anubis.Learning.Example> 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<DateOnly?>().FirstOrDefault();
}
private async Task<Loaded> LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken, IReadOnlyList<string>? 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<string>(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<BacktestInstrument>();
var missing = new HashSet<string>(StringComparer.Ordinal);
var currency = crypto ? "EUR" : "USD";
+1
View File
@@ -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.",
+10
View File
@@ -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
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
public LiveEngine Engine { get; }
/// <summary>The nightly and weekly cycle of the model (SPEC 11.4).</summary>
public Anubis.Learning.LearningCycle Cycle { get; }
private readonly SettingsStore? _settings;
/// <summary>Learning beside the decisions (SPEC 11).</summary>
@@ -514,6 +518,11 @@ public sealed partial class TradingService : IDisposable
}
}
/// <summary>The night of the model: once, however long the absence (SPEC 5.6), and beside the others because it is long.</summary>
public static ScheduledJob ModelJob(Func<CancellationToken, Task> 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<ScheduledJob> 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<ScheduledJob>() :
[