Fix what a second independent reading of the Phase 8 fixes found
ci / test (postgres) (push) Failing after 6m9s
ci / test (sqlite) (push) Successful in 7m6s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Successful in 5m51s
ci / test (sqlite) (pull_request) Successful in 7m3s
ci / image (pull_request) Successful in 1m51s

One funded signal was enough to start the model for good, because the interval
of a few cases had no width: it now takes a hundred, weighed among themselves.
A computer always off at 03:00 never made the night of the model: a job to make
up for counts from the first start that knows it, and the night waits for the
bars of the absence. Stories are seen as they were when the decision was due, a
report already out does not close a label, an undone promotion starts the trial
again, and the trade card finds the estimate of an example born earlier.

ADR 0018 point 18 has the list; each defect has its test.

refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 14:27:03 +01:00
1 parent 0b0f4a5e75
commit c7e462b6f4
18 files changed
+371 -26

No files matched your search

+13
View File
@@ -1,6 +1,7 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.Strategies;
using Anubis.Trading;
@@ -99,11 +100,23 @@ public sealed class LearningCasesTests
await s.ExecuteAsync(
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " +
"VALUES (@id, @t, @t, @p, @f, @f, 1, @yes, @s, 1, @f, @f)", ("id", id), ("t", title), ("p", published), ("f", seen), ("yes", true), ("s", score)).ConfigureAwait(false);
await ArticleAsync(s, rig, id, title, published, seen, score).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', 'okx:BTC-EUR', 'name', @f)",
("id", Ids.NewId(rig.Clock)), ("st", id), ("f", seen)).ConfigureAwait(false);
}).ConfigureAwait(false);
}
/// <summary>An article of a story, saved at a moment, from a source of its own.</summary>
internal static async Task ArticleAsync(DbSession s, TradingRig rig, Guid story, string title, DateTimeOffset published, DateTimeOffset saved, double score, int importance = 1)
{
var (source, item) = (Ids.NewId(rig.Clock), Ids.NewId(rig.Clock));
await s.ExecuteAsync("INSERT INTO news_sources (id, url, name, kind, trusted, enabled, failures, created_at, updated_at) VALUES (@id, @u, @u, 'rss', @yes, @yes, 0, @f, @f)",
("id", source), ("u", "https://t/" + source), ("yes", true), ("f", saved)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, language, published_at, score, importance, created_at) " +
"VALUES (@id, @st, @so, @u, @u, @pub, @t, 'en', @p, @s, @i, @f)", ("id", item), ("st", story), ("so", source), ("u", "https://t/a/" + item), ("pub", "t" + source), ("t", title), ("p", published), ("s", score),
("i", importance), ("f", saved)).ConfigureAwait(false);
}
/// <summary>Enters while not held, on a fixed day leaves; every day proposes again what it does not hold.</summary>
private sealed class Stubborn(DateOnly from, DateOnly exit, decimal weight = 0.3m, decimal? stop = null) : IStrategy
{
+185
View File
@@ -269,6 +269,191 @@ public sealed class LearningReviewTests
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMomentum, 6)));
}
private static Estimate Closed(int i, bool win, string stage, double p) => new(Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with
{
Id = Guid.NewGuid(),
Stage = stage,
Label = new CaseLabel(win, win ? 0.02 : -0.02, From.AddDays(i + 1), From.AddDays(i + 2), "x"),
}, p, 0.4, MultiplierRule.Standard.Of(p, 0.4));
private static readonly Dictionary<string, double> Money = new() { [StrategyNames.CryptoTrend] = 1000 };
/// <summary>SPEC 11.5: three hundred signals in observation and a handful with capital prove no gain, however lucky.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AFewFundedSignalsNeverStartTheModel()
{
List<Estimate> observed = [.. Enumerable.Range(0, 400).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
ActivationCheck With(int funded) => ActivationCheck.Of([.. observed, .. Enumerable.Range(0, funded).Select(i => Closed(1000 + i, i * 7 % 25 < 9, StrategyStages.Simulation, 0.36))], Rates.BaseRates, Money);
foreach (var few in new[] { 1, 5, 10, 30, 99 })
{
var check = With(few);
Assert.AreEqual((few, true, true), (check.Funded, check.Enough, check.Calibrated));
Assert.IsFalse(check.Improves || check.Passed, $"{few} signals");
}
Assert.IsTrue(With(100).Passed, "the same advantage on enough of them");
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), Judge.Interval([1, 1, 1], [1, 1, 1], 0.9), "nothing can be said of three");
}
/// <summary>SPEC 11.4: the signals with capital are weighed among themselves, not with the older ones in observation.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheGainIsWeighedOnTheSignalsItIsMeasuredOn()
{
List<Estimate> observed = [.. Enumerable.Range(0, 200).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
// Of those with capital only the losses have matured so far, nearly: without weights the filter would look good.
List<Estimate> funded = [.. Enumerable.Range(0, 100).Select(i => Closed(1000 + i, i % 10 == 0, StrategyStages.Simulation, 0.36))];
var check = ActivationCheck.Of([.. observed, .. funded], Rates.BaseRates, Money);
var alone = Judge.Score(Judge.Weigh(funded, Rates.BaseRates), Money);
Assert.AreEqual(alone.GainWithout, check.Scores.GainWithout, 1e-9);
Assert.AreEqual(alone.GainWith, check.Scores.GainWith, 1e-9);
Assert.AreEqual((0.4 * 0.02 * 200) - (0.6 * 0.02 * 200), check.Scores.GainWithout, 1e-9, "wins and losses in the proportion of the base rate");
}
/// <summary>A report already out when the operation starts is not one to leave before (ADR 0017, point 5).</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AReportAlreadyOutDoesNotCloseTheLabel()
{
var bars = Enumerable.Range(0, 10).Select(i => new DailyBar(From.AddDays(i), 100, 101, 99, 100, 1e6)).ToList();
var data = new BacktestDataset([new BacktestInstrument(MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null }, bars)], "EUR");
var example = Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(1));
DateOnly? ClosedWith(int report) => CaseLabels.Of(example, () => new LeavesBeforeReports(), data, From.AddDays(9), earnings: From.AddDays(report))?.ClosedDay;
Assert.IsNull(ClosedWith(1), "the evening of the decision");
Assert.IsNull(ClosedWith(2), "the day of the purchase");
Assert.AreEqual(From.AddDays(4), ClosedWith(4), "sold at the open of the day of the report");
Assert.AreEqual(From.AddDays(7), ClosedWith(7));
}
private sealed class LeavesBeforeReports : IStrategy
{
public string Id => StrategyNames.CryptoTrend;
public string Version => "t";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
public IReadOnlyList<Intent> Decide(StrategyContext context) =>
!context.Portfolio.Holds("BTC-EUR") ? [new Intent("BTC-EUR", 0.2m, "x") { Strength = 0.5 }]
: context.NextEarnings?.Invoke("BTC-EUR") is { } report && context.NextSession is { } next && report <= next ? [new Intent("BTC-EUR", 0m, "report")] : [];
}
/// <summary>SPEC 5.6: a computer off every night from the day of the installation still makes the night at its return.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AJobNeverMadeCountsFromTheFirstStart()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true).ConfigureAwait(false);
var rows = await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE name IN ('modello', 'backup')",
r => (Name: r.Text("name"), Due: r.MomentOrNull("last_due_at"))), _none).ConfigureAwait(false);
Assert.HasCount(2, rows);
Assert.IsTrue(rows.All(r => r.Due is not null), "the next start has something to count from");
var clock = new ManualClock(rows[0].Due!.Value.AddDays(2));
var scheduler = new Scheduler(clock, new EventBus());
var runs = 0;
scheduler.Add(TradingService.ModelJob(_ => Task.FromResult(runs++)), rows.First(r => r.Name == "modello").Due);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
await scheduler.BesideAsync().ConfigureAwait(false);
Assert.AreEqual(1, runs);
}
/// <summary>SPEC 5.6, 9.4: the night made up for at the return waits for the bars of the absence, but not for ever.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheNightWaitsForTheBars()
{
var midnight = new DateTimeOffset(2027, 3, 8, 0, 0, 0, TimeSpan.Zero);
var clock = new ManualClock(midnight.AddHours(8));
DateTimeOffset? last = midnight.AddDays(-3);
var asked = 0;
Task Ready() => TradingService.BarsReadyAsync(clock, () => last, () => Task.FromResult(asked++), _none);
var waiting = Ready();
clock.Advance(TimeSpan.FromMinutes(5));
await Task.Delay(50, _none).ConfigureAwait(false);
Assert.IsFalse(waiting.IsCompleted);
last = clock.UtcNow;
await AdvanceAsync(waiting).ConfigureAwait(false);
Assert.AreEqual(1, asked);
await Ready().ConfigureAwait(false);
Assert.AreEqual(1, asked, "the bars of today are there");
// No network: after half an hour it goes on.
last = null;
var offline = Ready();
clock.Advance(TimeSpan.FromMinutes(29));
await Task.Delay(50, _none).ConfigureAwait(false);
Assert.IsFalse(offline.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(2));
await AdvanceAsync(offline).ConfigureAwait(false);
async Task AdvanceAsync(Task task)
{
for (var i = 0; i < 100 && !task.IsCompleted; i++)
{
clock.Advance(TimeSpan.FromSeconds(10));
await Task.Delay(20, _none).ConfigureAwait(false);
}
Assert.IsTrue(task.IsCompletedSuccessfully);
}
}
/// <summary>SPEC 11.4: with the promotion taken back, the one on trial is judged again from the first threshold.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnUndonePromotionStartsTheTrialAgain()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var old = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.3), ModelStatuses.Retired).ConfigureAwait(false);
var champion = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
var trial = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
await rig.Db.WriteAsync(async s =>
{
await ModelStore.SetReplacedAsync(s, rig.Clock, champion.Id, old.Id, _none).ConfigureAwait(false);
await ModelStore.SetThresholdAsync(s, rig.Clock, trial.Id, 150, _none).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
Assert.IsTrue(await LearningCycle.UndoPromotionAsync(rig.Db, rig.Clock, _none).ConfigureAwait(false));
var after = await new ModelStore(rig.Db).FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
Assert.AreEqual((trial.Id, 0), (after!.Id, after.ThresholdDone));
}
/// <summary>SPEC 11.2: a story that grew after the decision was due is seen as it was then, articles, links and verdict.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStoryIsSeenAsItWasWhenTheDecisionWasDue()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var at = rig.Clock.UtcNow;
var story = Ids.NewId(rig.Clock);
Task LinkAsync(Database db, string target, DateTimeOffset when) => db.WriteAsync(s => s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', @t, 'name', @f)",
("id", Ids.NewId(rig.Clock)), ("st", story), ("t", target), ("f", when)), _none);
await rig.Db.WriteAsync(async s =>
{
// The row as it is now, grown: negative, serious, linked to one more coin.
await s.ExecuteAsync("INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, severe, importance, created_at, updated_at) " +
"VALUES (@id, 't', 't', @p, @f, @l, 2, @yes, -0.4, 'fraud', 4, @f, @l)", _none, ("id", story), ("p", at.AddHours(-5)), ("f", at.AddHours(-4)), ("l", at.AddHours(8)), ("yes", true)).ConfigureAwait(false);
await LearningCasesTests.ArticleAsync(s, rig, story, "first", at.AddHours(-5), at.AddHours(-4), 0.1).ConfigureAwait(false);
await LearningCasesTests.ArticleAsync(s, rig, story, "later", at.AddHours(3), at.AddHours(8), -0.9, 4).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
await LinkAsync(rig.Db, "okx:BTC-EUR", at.AddHours(-4)).ConfigureAwait(false);
await LinkAsync(rig.Db, "okx:ETH-EUR", at.AddHours(8)).ConfigureAwait(false);
rig.Clock.Set(at.AddHours(9));
var reader = new OutsideReader(rig.Db, rig.Clock);
var specs = new Dictionary<string, InstrumentSpec> { ["BTC-EUR"] = TradingRig.Btc, ["ETH-EUR"] = TradingRig.Btc with { Symbol = "ETH-EUR" } };
var then = await reader.ReadAsync(at, specs, null, _none).ConfigureAwait(false);
Assert.AreEqual(0.1, then.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
Assert.IsNull(then.News["BTC-EUR"].Active);
Assert.AreEqual((1, 0), (then.Stories3Days["BTC-EUR"], then.Stories3Days["ETH-EUR"]));
var now = await reader.ReadAsync(at.AddHours(9), specs, null, _none).ConfigureAwait(false);
Assert.AreEqual(-0.4, now.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
Assert.AreEqual(4, now.News["BTC-EUR"].Active!.Story.RuleImportance);
Assert.AreEqual(1, now.Stories3Days["ETH-EUR"]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APrecisionUnderTheAlarmNeverReadsFiftyPercent()
+19
View File
@@ -67,6 +67,17 @@ public sealed class LearningScreenTests
{ DecisionId = earlier }, _none);
}, _none);
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
// Born the evening before, with the simulated operation closed on the day of the purchase: still the one bought.
var opened = (await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT t.opened_at FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE i.symbol = 'MSFT' AND t.status = 'closed' ORDER BY t.opened_at DESC LIMIT 1", r => (DateTimeOffset?)r.Moment("opened_at")), _none))!.Value;
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE decisions SET created_at = @at WHERE decision_id = @d", _none, ("at", opened.AddHours(-10)), ("d", earlier));
var example = (await s.FirstOrDefaultAsync("SELECT id FROM ml_features WHERE decision_id = @d", r => (Guid?)r.Id("id"), ("d", earlier)))!.Value;
var day = DateOnly.FromDateTime(opened.UtcDateTime);
await LearningStore.AddLabelAsync(s, clock, example, new CaseLabel(false, -0.01, day.AddDays(-2), day, "x"), _none);
}, _none);
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
using var post = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
Assert.AreEqual("/apprendimento?errore=motore", ServerHarness.Location(post));
using var settings = await server.PostFormAsync("/impostazioni", "/azioni/modello", (LearningSettings.Aside.Key, "on"));
@@ -316,6 +327,10 @@ public sealed class LearningScreenTests
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":true"), ": era messo da parte, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":false"), ": solo osservazione, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":true,\"aside\":false"), ": taglia piena");
string Reduced(string applied) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":" + applied + "}")!;
StringAssert.EndsWith(Reduced("0.996"), ": acquisto ridotto al 99%");
StringAssert.EndsWith(Reduced("0.004"), ": acquisto ridotto al 1%");
StringAssert.EndsWith(Reduced("0"), ": acquisto non fatto");
}
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
@@ -332,6 +347,10 @@ public sealed class LearningScreenTests
LearningView.BandsWords([B(30, 1, 0), B(45, 30, 20)]));
StringAssert.EndsWith(LearningView.BandsWords([B(30, 30, 30), B(35, 3, 30), B(45, 30, 47)]), "Nelle fasce di mezzo con meno di 20 casi ha visto solo 3 casi, troppo pochi per contarci.");
Assert.AreEqual("Nessuna fascia ha ancora 20 casi: troppo pochi per contarci.", LearningView.BandsWords([B(30, 19, 30)]));
// The judge is the error of the criterion to start counting, as the rest of the page says it.
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 20)], 0.01), "è andata bene il 20% delle volte: è ben tarato.");
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 47)], 0.06), "non è ancora ben tarato, in media sbaglia di 6,0 punti.");
}
/// <summary>The clues after the ninth are "Tutto il resto", the whole stays 100; the sentence about the news follows the numbers.</summary>