Files
Anubis/tests/Anubis.Tests/LearningReviewTests.cs
Alby96andClaude Opus 5.5 c7e462b6f4
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
Fix what a second independent reading of the Phase 8 fixes found
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>
2026-12-01 14:27:03 +01:00

465 lines
27 KiB
C#

using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>What the independent review of Phase 8 found (issue #67): each defect has the case that shows it.</summary>
[TestClass]
public sealed class LearningReviewTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4, [StrategyNames.EquityMomentum] = 0.5 } };
/// <summary>The same stretch of days as the tests of the cycle, with entries inside.</summary>
private static readonly DateOnly From = LearningCycleTests.From;
/// <summary>With few winners the lowest step is one or two losses: it must not become the floor of every other one.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheIsotonicCalibrationOrdersEvenWhenWinnersAreFew()
{
var gen = new Gen(23);
var scores = Enumerable.Range(0, 1800).Select(_ => gen.Normal()).ToList();
double Truth(double s) => 0.03 + (0.30 * Odds.Probability(2 * s));
var wins = scores.Select(s => gen.Double() < Truth(s)).ToList();
// The two smallest scores lose and the largest wins, as in the history that was shipped.
scores.AddRange([-9, -8, 9]);
wins.AddRange([false, false, true]);
var fitted = Calibration.Fit(scores, wins);
Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind);
Assert.AreEqual((double)wins.Count(w => w) / wins.Count, scores.Average(fitted.Probability), 0.01, "on the whole it says the base rate");
foreach (var s in new[] { -1.5, -0.5, 0, 0.5, 1.5 })
{
Assert.AreEqual(Truth(s), fitted.Probability(s), 0.07, $"at {s}");
}
Assert.IsTrue(fitted.Probability(-20) is > 0.02 and < 0.15 && fitted.Probability(20) is > 0.2 and < 0.5, "one case at the edge says nothing");
}
/// <summary>The model shipped must tell signals apart, and be as well calibrated as 11.5 asks on cases it had not studied.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFirstModelTellsSignalsApart()
{
var file = FirstModel.Embedded!;
var rate = file.BaseRates[StrategyNames.CryptoTrend];
var said = file.Examples.Where(e => e.IsLabelled).Select(e => file.Model!.Probability(e.Features)).ToList();
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p < rate - 0.01));
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p > rate + 0.01));
Assert.AreEqual(rate, said.Average(), 0.02);
var verified = file.Report!.Chosen!.Combined;
Assert.IsLessThan(ActivationCheck.MaxCalibrationError, verified.CalibrationError!.Value);
Assert.AreEqual(file.Report.Examples, verified.Bands.Sum(b => b.Cases), 10, "an example verified five times is one case");
}
/// <summary>Five combinations verify the same thirty examples: the band has thirty cases, not one hundred and fifty.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AnExampleVerifiedFiveTimesIsOneCase()
{
var cases = Enumerable.Range(0, 30).Select(i => Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with { Label = new CaseLabel(i < 6, 0.1, From.AddDays(i + 1), From.AddDays(i + 9), "x") }).ToList();
var band = Judge.Bands([.. Enumerable.Range(0, 5).SelectMany(_ => cases.Select(c => new Estimate(c, 0.22, 0.2, 1)))]).Single();
Assert.AreEqual(30, band.Cases);
Assert.AreEqual(0.2, band.Observed, 1e-9);
}
/// <summary>SPEC 11.1: who knows nothing of a strategy leaves its operations as they are, even when it has a base rate.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AModelEstimatesOnlyTheStrategiesItStudied()
{
ModelRow Row(string status, params string[] studied) => new(Guid.NewGuid(), 1, LearnerNames.Logistic, status, "test", default, 500, 0, null, LearningCycleTests.Always(0.1) with { Strategies = studied }, new ModelReport());
Example Case(string strategy) => new(Guid.NewGuid(), strategy, "X", CaseSources.Live, From, default, "x", 0.2m, null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
var gate = new ModelGate(Row(ModelStatuses.Champion, StrategyNames.CryptoTrend), Row(ModelStatuses.Challenger, StrategyNames.CryptoTrend, StrategyNames.EquityMomentum), MultiplierRule.Standard, Rates.BaseRates, true);
Assert.HasCount(2, gate.Estimate(Case(StrategyNames.CryptoTrend)));
var only = gate.Estimate(Case(StrategyNames.EquityMomentum)).Single();
Assert.IsFalse(only.InCharge, "the one in charge has nothing to say");
Assert.HasCount(0, gate.Estimate(Case(StrategyNames.EquityMeanrev)), "no base rate");
}
private static async Task<string> FillsAsync(LiveRig rig) => string.Join('\n', await rig.Rig.QueryAsync(
"SELECT i.symbol, f.side, f.quantity, f.executed_at FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, i.symbol",
r => $"{r.Text("symbol")} {r.Text("side")} {r.Money("quantity")} {r.Moment("executed_at"):MM-dd HH:mm}").ConfigureAwait(false));
private static async Task<(string Fills, int Failures)> RunAsync(Func<LiveRig, DateOnly, Task>? before = null)
{
var last = From.AddDays(20);
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
rig.UseFirst(Rates);
await LearningCycleTests.AddModelAsync(rig.Rig.Db, rig.Rig.Clock, LearningCycleTests.Always(0.35), ModelStatuses.Champion).ConfigureAwait(false);
await rig.Rig.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, rig.Rig.Clock, CycleState.Key, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }, _none), _none).ConfigureAwait(false);
for (var day = From; day <= last; day = day.AddDays(1))
{
if (before is not null)
{
await before(rig, day).ConfigureAwait(false);
}
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
return (await FillsAsync(rig).ConfigureAwait(false), rig.Failures);
}
private static Task<int> ExecuteAsync(LiveRig rig, string sql, params (string, object?)[] parameters) => rig.Rig.Db.WriteAsync(s => s.ExecuteAsync(sql, _none, parameters), _none);
/// <summary>
/// SPEC 11.1: the multiplier of birth holds to the close. The world outside cannot be read any more, or the clues of the
/// archive are damaged: operations born halved must trade as before, not be bought whole.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFailureOfLearningNeverForgetsTheMultiplierOfBirth()
{
var (whole, _) = await RunAsync().ConfigureAwait(false);
var (blind, failures) = await RunAsync((rig, day) => day == From.AddDays(10) ? ExecuteAsync(rig, "ALTER TABLE market_mood RENAME TO market_mood_away") : Task.CompletedTask).ConfigureAwait(false);
Assert.AreEqual((whole, 0), (blind, failures), "without the outside");
var (damaged, again) = await RunAsync((rig, day) => day >= From.AddDays(10) ? ExecuteAsync(rig, "UPDATE ml_features SET features = @j", ("j", new DbJson("\"damaged\""))) : Task.CompletedTask)
.ConfigureAwait(false);
Assert.AreEqual((whole, 0), (damaged, again), "with damaged clues");
}
/// <summary>ADR 0018, point 2: a failure while saving the examples takes back only the examples, on both engines.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnExampleThatCannotBeSavedNeverStopsTheDecision()
{
var runs = 0L;
var kept = 0L;
var (fills, failures) = await RunAsync(async (rig, day) =>
{
if (day == From)
{
await ExecuteAsync(rig, "ALTER TABLE ml_predictions RENAME TO ml_predictions_away").ConfigureAwait(false);
}
runs = await rig.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM engine_runs"), _none).ConfigureAwait(false);
kept = await rig.Learning.Store.CountAsync(CaseSources.Live, _none).ConfigureAwait(false);
}).ConfigureAwait(false);
Assert.AreEqual(0, failures);
Assert.IsGreaterThan(15, runs, "one decision a day");
Assert.AreEqual(0, kept, "the examples were taken back whole");
Assert.IsGreaterThan(0, fills.Length);
}
/// <summary>SPEC 11.2, 5.6: a decision recovered in the afternoon must not know more than the operation that started at midnight.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue()
{
var last = From.AddDays(20);
DateOnly born;
await using (var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false))
{
rig.UseFirst(Rates);
for (var day = From; day <= last; day = day.AddDays(1))
{
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
born = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day > From.AddDays(2)).Day;
}
await using var late = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
late.UseFirst(Rates);
for (var day = From; day <= born; day = day.AddDays(1))
{
await late.DayAsync(day, morning: 8).ConfigureAwait(false);
}
// Off until the afternoon after the close: at noon a value of the mood was published and saved.
var midnight = new DateTimeOffset(born.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
await late.StoreBarAsync(born).ConfigureAwait(false);
var mood = new MoodStore(late.Rig.Db, late.Rig.Clock);
await mood.UpsertAsync([new(MoodIndicators.Vix, midnight.AddHours(-10), 18, null, "t")], _none).ConfigureAwait(false);
late.Rig.Clock.Set(midnight.AddHours(12));
await mood.UpsertAsync([new(MoodIndicators.FearGreed, midnight.AddHours(11), 99, null, "t")], _none).ConfigureAwait(false);
late.Rig.Clock.Set(midnight.AddHours(15));
late.Quotes(born.AddDays(1), b => b.Close);
await late.MinutesAsync(5).ConfigureAwait(false);
var example = (await late.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day == born);
Assert.IsFalse(example.Features.ContainsKey(Clues.FearGreed), "published after the operation had started");
Assert.AreEqual(18d, example.Features[Clues.Vix], "known when it was due");
}
/// <summary>A strategy whose labels cannot be made must not keep a model that counts from being checked.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ALabelThatFailsDoesNotStopTheCheck()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero));
var desk = new LearningDesk(rig.Db, rig.Clock) { First = Rates };
await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From), _none), _none).ConfigureAwait(false);
var cycle = new LearningCycle(rig.Db, rig.Clock, desk, (_, _, _) => throw new InvalidDataException("bars"));
await Assert.ThrowsExactlyAsync<AggregateException>(() => cycle.RunAsync(_none)).ConfigureAwait(false);
var state = await desk.CycleAsync(_none).ConfigureAwait(false);
Assert.AreEqual(new DateOnly(2027, 3, 3), state.LastNight);
Assert.AreEqual(1, state.Health!.Version);
Assert.IsNotNull(state.LastSunday);
}
private static Example Open(string strategy, string symbol, DateOnly day) => new(Guid.Empty, strategy, symbol, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "x", 0.2m,
null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
/// <summary>SPEC 5.6: the computer slept for twenty hours with the process alive; the night is made once at the waking.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheNightIsMadeAfterALongSleep()
{
var clock = new ManualClock(new DateTimeOffset(2027, 3, 3, 0, 0, 0, TimeSpan.Zero));
var runs = 0;
var scheduler = new Scheduler(clock, new EventBus());
scheduler.Add(TradingService.ModelJob(_ =>
{
runs++;
return Task.CompletedTask;
}), clock.UtcNow);
clock.Set(new DateTimeOffset(2027, 3, 3, 22, 0, 0, TimeSpan.Zero));
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
for (var i = 0; i < 200 && runs == 0; i++)
{
await Task.Delay(20, _none).ConfigureAwait(false);
}
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
Assert.AreEqual(1, runs);
}
/// <summary>SPEC 11.2: one example for each potential operation, even when a newer history reaches days already lived.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ANewerHistoryDoesNotCountTwiceWhatWasLived()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From) with { Label = new CaseLabel(true, 0.1, From.AddDays(1), From.AddDays(20), "x") }, _none), _none)
.ConfigureAwait(false);
Example Past(string symbol, int from, int to) => Open(StrategyNames.CryptoTrend, symbol, From.AddDays(from)) with
{
Id = Guid.NewGuid(),
Source = CaseSources.History,
Label = new CaseLabel(false, -0.1, From.AddDays(from + 1), From.AddDays(to), "x"),
};
var desk = new LearningDesk(rig.Db, rig.Clock)
{
First = new FirstModelFile { Examples = [Past("BTCEUR", 1, 19), Past("BTCEUR", -3, 5), Past("BTCEUR", -30, 0), Past("BTCEUR", 20, 30), Past("ETHEUR", 1, 19)] },
};
await desk.PrepareHistoryAsync(_none).ConfigureAwait(false);
var kept = (await desk.Store.AllAsync(_none).ConfigureAwait(false)).Where(e => e.Source == CaseSources.History).Select(e => e.Symbol + (e.Day.DayNumber - From.DayNumber)).Order(StringComparer.Ordinal);
Assert.AreEqual("BTCEUR-30 BTCEUR20 ETHEUR1", string.Join(' ', kept));
}
/// <summary>The label leaves before the report the decision knew of, whatever the calendar says months later.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportOfALabelIsTheOneKnownAtTheDecision()
{
Example With(string strategy, double? days) => Open(strategy, "AAPL", From) with { Features = days is { } d ? new Dictionary<string, double> { [Clues.EarningsDays] = d } : [] };
Assert.AreEqual(From.AddDays(6), Clues.ReportOf(With(StrategyNames.EquityMeanrev, 6)));
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, Clues.FarReport)));
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, null)));
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()
{
Assert.AreEqual((49, 49, 50, 45, 56), (Health.Shown(0.4999), Health.Shown(0.496), Health.Shown(0.5), Health.Shown(0.451), Health.Shown(0.556)));
Assert.AreEqual("Precisione scesa al 49% su 41 casi.", LearningCycle.AsideText(AsideCodes.Precision, new HealthCheck { Precision = 0.4967, Cases = 41 }));
}
}