Files
Anubis/src/Anubis/Learning/LearningStore.cs
T
Alby96andClaude Opus 5.5 0b0f4a5e75
ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s
Fix what the independent review of Phase 8 found and close the phase
Two reviewers with a clean context read the engine and the screens. The
isotonic calibration took its floor from the first step, even of two cases, so
with few winners it flattened every estimate: the first model is rebuilt with
the fix. Learning failures no longer forget the multiplier an operation was
born with, nor stop a decision or the nightly check; recovered decisions read
the outside world as it was when due; models estimate only the strategies they
studied; a newer history does not repeat what was lived. The screens count
examples instead of verifications, show the next threshold and never round an
alarm to 50%; two forms now check the antiforgery token.

Each defect has its test, on both engines. ADR 0018 point 17 has the list.

refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:36:26 +01:00

117 lines
7.6 KiB
C#

using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Learning;
/// <summary>The archive of the examples and of their labels (SPEC 11.2), and the small state of the learning cycle.</summary>
public sealed class LearningStore(Database db, IClock clock)
{
private const string Columns =
"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. 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;
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);
}
return id;
}
/// <summary>The label of an example, once and for all: a label never changes.</summary>
public static Task<int> AddLabelAsync(DbSession s, IClock clock, Guid example, CaseLabel label, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(label);
return s.ExecuteAsync(
"INSERT INTO ml_labels (id, feature_id, label, result, opened_day, closed_day, exit_reason, created_at) VALUES (@id, @f, @l, @r, @o, @c, @e, @now) ON CONFLICT (feature_id) DO NOTHING",
cancellationToken, ("id", Ids.NewId(clock)), ("f", example), ("l", label.Win is { } win ? (win ? 1 : 0) : null), ("r", label.Result),
("o", label.OpenedDay is { } opened ? BarStore.DayText(opened) : null), ("c", label.ClosedDay is { } closed ? BarStore.DayText(closed) : null), ("e", label.ExitReason),
("now", clock.UtcNow));
}
public Task AddLabelAsync(Guid example, CaseLabel label, CancellationToken cancellationToken) =>
db.WriteAsync(s => AddLabelAsync(s, clock, example, label, cancellationToken), cancellationToken);
/// <summary>The whole archive, oldest first.</summary>
public Task<List<Example>> AllAsync(CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " ORDER BY f.decided_at, f.strategy, f.symbol", Read), cancellationToken);
/// <summary>The live examples whose simulated operation is still open, oldest first.</summary>
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 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);
/// <summary>The same without reading the clues: what the multipliers of the operations already born need.</summary>
public Task<List<Example>> BornAsync(string strategy, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT f.symbol, f.decided_day, f.multiplier, l.id AS label_id, l.closed_day FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id "
+ "WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_day, f.decided_at",
r => new Example(Guid.Empty, strategy, r.Text("symbol"), CaseSources.Live, BarStore.ParseDay(r.Text("decided_day")), DateTimeOffset.MinValue, "", 0m, null, null, new Dictionary<string, double>())
{
Multiplier = r.Measure("multiplier"),
Label = r.IsNull("label_id") ? null : new CaseLabel(null, null, null, Day(r, "closed_day"), ""),
}, ("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);
// ---- State --------------------------------------------------------------------------------------------------
public async Task<T?> StateAsync<T>(string key, CancellationToken cancellationToken)
where T : class
{
var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)), cancellationToken).ConfigureAwait(false);
return json is null ? null : JsonSerializer.Deserialize<T>(json);
}
public static async Task SaveStateAsync<T>(DbSession s, IClock clock, string key, T value, CancellationToken cancellationToken)
where T : class
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
await s.ExecuteAsync(
"INSERT INTO ml_state (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @now, @now) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", new DbJson(JsonSerializer.Serialize(value))), ("now", clock.UtcNow)).ConfigureAwait(false);
}
private static Example Read(DbRow r)
{
var label = r.IsNull("label_id")
? null
: new CaseLabel(r.IsNull("label") ? null : r.Number("label") == 1, r.IsNull("result") ? null : r.Measure("result"), Day(r, "opened_day"), Day(r, "closed_day"), r.Text("exit_reason"));
return new Example(r.Id("id"), r.Text("strategy"), r.Text("symbol"), r.Text("source"), BarStore.ParseDay(r.Text("decided_day")), r.Moment("decided_at"), r.Text("reason"),
r.Money("weight"), r.MoneyOrNull("stop"), r.MoneyOrNull("stop_offset"), JsonSerializer.Deserialize<Dictionary<string, double>>(r.Json("features").Text) ?? [])
{
Stage = r.TextOrNull("stage"),
DecisionId = r.IdOrNull("decision_id"),
Multiplier = r.Measure("multiplier"),
Label = label,
};
}
private static DateOnly? Day(DbRow r, string column) => r.TextOrNull(column) is { } text ? BarStore.ParseDay(text) : null;
}