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

+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()