Files
Anubis/tests/Anubis.Tests/LearningCycleTests.cs
T
Alby96andClaude Opus 5.5 df21962da3 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>
2026-12-01 12:02:55 +01:00

647 lines
36 KiB
C#

using Anubis.Backtest;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The model in the decisions and its cycle: shadow, promotion, drift, set-aside, start (SPEC 11.1, 11.4, 11.5; issue #64).</summary>
[TestClass]
[TestCategory(Category.Integration)]
public sealed class LearningCycleTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateOnly From = new(2026, 6, 1);
/// <summary>A model that always answers <paramref name="probability"/>.</summary>
internal static TrainedModel Always(double probability) => new()
{
Clues = [Clues.Strength],
Learned = new Learned { Learner = LearnerNames.Logistic, Linear = new LinearBody(Odds.Logit(probability), [0], [0], [1]) },
Ranges = new Dictionary<string, ClueRange> { [Clues.Strength] = new(0, 1, 100) },
Strategies = [StrategyNames.CryptoTrend],
};
private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 } };
internal static Task<ModelRow> AddModelAsync(Database db, IClock clock, TrainedModel model, string status, int examples = 500) =>
db.WriteAsync(s => ModelStore.RegisterAsync(s, clock, model, new ModelReport { Examples = examples, Attempts = [new Attempt(LearnerNames.Logistic, new Scores(), new Scores(), true)] }, status, "test", clock.UtcNow, _none), _none);
private static Task StateAsync(Database db, IClock clock, CycleState state) => db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, _none), _none);
// ---- In the decisions -------------------------------------------------------------------------------------------
private sealed record Run(IReadOnlyList<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> Fills, IReadOnlyList<Example> Examples, IReadOnlyList<PredictionRow> Predictions,
IReadOnlyList<DecisionRow> Rows, int Failures);
private static async Task<Run> LiveAsync(TrainedModel? champion, bool active, TrainedModel? challenger = null, FirstModelFile? rates = null, string stage = StrategyStages.Simulation, int days = 20,
Func<LiveRig, DateOnly, Task>? before = null)
{
var last = From.AddDays(days);
await using var rig = await LiveRig.CreateAsync(From, last, stage: stage).ConfigureAwait(false);
rig.UseFirst(rates ?? Rates);
if (champion is not null)
{
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, champion, ModelStatuses.Champion).ConfigureAwait(false);
}
if (challenger is not null)
{
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, challenger, ModelStatuses.Challenger).ConfigureAwait(false);
}
if (active)
{
await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }).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);
}
var fills = 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"))).ConfigureAwait(false);
var rows = await rig.Rig.QueryAsync("SELECT symbol, stage, outcome, data FROM decisions WHERE stage = 'model' ORDER BY created_at",
r => new DecisionRow(Guid.Empty, "", null, r.TextOrNull("symbol"), r.Text("stage"), r.Text("outcome"), [], new Dictionary<string, object?> { ["json"] = r.TextOrNull("data") }, default)).ConfigureAwait(false);
return new Run([.. fills], await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false), await rig.Learning.Models.PredictionsAsync(_none).ConfigureAwait(false), [.. rows], rig.Failures);
}
private static string Text(IEnumerable<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> fills) => string.Join('\n', fills.Select(f => $"{f.Symbol} {f.Side} {f.Quantity} {f.At:MM-dd HH:mm}"));
/// <summary>SPEC 11.5: until it counts, the model notes its estimates beside each operation and changes nothing.</summary>
[TestMethod]
[DataRow(StrategyStages.Simulation)]
[DataRow(StrategyStages.Observation)]
public async Task InObservationItNotesItsEstimatesAndChangesNothing(string stage)
{
var without = await LiveAsync(null, active: false, stage: stage).ConfigureAwait(false);
var with = await LiveAsync(Always(0.1), active: false, Always(0.6), stage: stage).ConfigureAwait(false);
Assert.AreEqual(Text(without.Fills), Text(with.Fills));
Assert.IsGreaterThan(1, with.Examples.Count);
Assert.IsTrue(with.Examples.All(e => e.Multiplier == 1));
// Two estimates for each signal: the one in charge, with the multiplier it would apply, and the one on trial.
Assert.HasCount(2 * with.Examples.Count, with.Predictions);
Assert.IsTrue(with.Predictions.Where(p => p.InCharge).All(p => p is { Multiplier: 0, BaseRate: 0.4 } && Math.Abs(p.Probability - 0.1) < 1e-6));
Assert.IsTrue(with.Predictions.Where(p => !p.InCharge).All(p => p.Multiplier == 1));
Assert.HasCount(with.Examples.Count, with.Rows);
Assert.IsTrue(with.Rows.All(r => r.Outcome == DecisionOutcomes.Passed));
Assert.Contains("in osservazione, non cambia niente", Anubis.Server.ReasonTexts.Model((string)with.Rows[0].Data!["json"]!)!);
Assert.HasCount(0, without.Predictions);
}
/// <summary>When it counts: nothing is ever bigger, exits are the same, the multiplier of birth holds for the increases.</summary>
[TestMethod]
public async Task WhenItCountsItOnlyMakesOperationsSmaller()
{
var full = await LiveAsync(Always(0.4), active: true).ConfigureAwait(false);
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
Assert.AreEqual(Text(none.Fills), Text(full.Fills), "who always answers the base rate leaves everything as it is");
var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
Assert.IsTrue(half.Examples.All(e => Math.Abs(e.Multiplier - 0.5) < 1e-3));
Assert.IsTrue(half.Rows.All(r => r.Outcome == DecisionOutcomes.Reduced));
Assert.Contains("acquisto ridotto al 50%", Anubis.Server.ReasonTexts.Model((string)half.Rows[0].Data!["json"]!)!);
decimal Bought(Run run, string symbol) => run.Fills.Where(f => f.Symbol == symbol && f.Side == "buy").Sum(f => f.Quantity);
foreach (var symbol in full.Fills.Select(f => f.Symbol).Distinct())
{
// The first purchase is half, or more where the limits had already cut the whole one.
Assert.IsInRange(0.47, 1, (double)(half.Fills.First(f => f.Symbol == symbol).Quantity / full.Fills.First(f => f.Symbol == symbol).Quantity), symbol);
Assert.IsLessThanOrEqualTo(Bought(full, symbol), Bought(half, symbol), symbol);
}
Assert.AreEqual(0.5, (double)(half.Fills[0].Quantity / full.Fills[0].Quantity), 0.01, "where no limit cuts");
// The full exits come on the same days.
string Exits(Run run) => string.Join(' ', run.Fills.Where(f => f.Side == "sell").Select(f => f.Symbol + DateOnly.FromDateTime(f.At.UtcDateTime)).Distinct().Order());
Assert.Contains(Exits(half), Exits(full), StringComparison.Ordinal);
var zero = await LiveAsync(Always(0.2), active: true).ConfigureAwait(false);
Assert.HasCount(0, zero.Fills);
Assert.AreEqual(string.Join(',', full.Examples.Select(e => e.Symbol + e.Day)), string.Join(',', zero.Examples.Select(e => e.Symbol + e.Day)), "the examples do not depend on the model");
Assert.IsTrue(zero.Rows.All(r => r.Outcome == DecisionOutcomes.Refused));
}
/// <summary>The multiplier is fixed at birth: a model that changes its mind, or is set aside, does not touch an operation already open.</summary>
[TestMethod]
public async Task TheMultiplierIsFixedAtBirth()
{
async Task Swap(LiveRig rig, DateOnly day)
{
// After 10 days the model is set aside: new operations are whole again, the ones already born are not.
if (day == From.AddDays(10))
{
await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow, Aside = AsideCodes.Precision }).ConfigureAwait(false);
}
}
var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
var swapped = await LiveAsync(Always(0.35), active: true, before: Swap).ConfigureAwait(false);
Assert.IsTrue(swapped.Examples.Any(e => e.Day >= From.AddDays(9)) && swapped.Fills.Count > 0 && swapped.Examples.Any(e => e.Day < From.AddDays(9)));
foreach (var example in swapped.Examples)
{
Assert.AreEqual(example.Day < From.AddDays(9) ? 0.5 : 1, example.Multiplier, 1e-3, $"{example.Symbol} {example.Day}");
}
// The operations born halved trade exactly as if the model were still there, increases included.
foreach (var symbol in swapped.Examples.GroupBy(e => e.Symbol).Where(g => g.All(e => e.Day < From.AddDays(9))).Select(g => g.Key))
{
Assert.AreEqual(Text(half.Fills.Where(f => f.Symbol == symbol)), Text(swapped.Fills.Where(f => f.Symbol == symbol)));
}
}
/// <summary>Set aside by the user, or without a base rate for the strategy: multiplier 1, and without a base rate not even an estimate.</summary>
[TestMethod]
public async Task WithoutABaseRateThereIsNoEstimate()
{
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
var run = await LiveAsync(Always(0.1), active: true, rates: new FirstModelFile()).ConfigureAwait(false);
Assert.AreEqual(Text(none.Fills), Text(run.Fills));
Assert.HasCount(0, run.Predictions);
Assert.IsTrue(run.Examples.All(e => e.Multiplier == 1));
}
/// <summary>A model that breaks never stops a decision: the strategy goes on as if there were none.</summary>
[TestMethod]
public async Task ABrokenModelNeverStopsADecision()
{
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
// A tree that points outside itself throws at every estimate.
var broken = Always(0.1) with
{
Learned = new Learned { Learner = LearnerNames.Boosting, Trees = new TreesBody(0, 1, false, [new Tree([0], [0.5], [7], [9], [true], [0])]) },
};
var run = await LiveAsync(broken, active: true).ConfigureAwait(false);
Assert.AreEqual(Text(none.Fills), Text(run.Fills));
Assert.AreEqual(0, run.Failures);
Assert.HasCount(0, run.Predictions);
Assert.HasCount(none.Examples.Count, run.Examples);
}
/// <summary>The filter on its own: never bigger, exits and decreases untouched, no chasing of the rounding.</summary>
[TestMethod]
public void TheFilterNeverMakesAnOrderBigger() => Property.ForAll(
gen => (Target: gen.Bool() ? (decimal?)gen.Decimal(0m, 0.5m, 4) : null, Multiplier: gen.Pick([double.NaN, -3, 0, 0.2, 0.5, 0.99, 1, 1.7, 50, double.PositiveInfinity])),
x =>
{
var data = LearningCasesTests.Coins(300, 1);
var seen = new List<(Intent Before, Intent After)>();
var strategy = new Fixed(x.Target);
BacktestEngine.Run(strategy, data, new BacktestOptions
{
From = data.Sessions[250],
To = data.Sessions[256],
Correctives = [new Spy(i => seen.Add((i, i))), new ModelFilter((_, _) => x.Multiplier), new Spy(i => seen[^1] = (seen[^1].Before, i))],
});
foreach (var (before, after) in seen)
{
Assert.IsTrue(after.TargetWeight is null || after.TargetWeight <= before.TargetWeight, $"{before.TargetWeight} -> {after.TargetWeight}");
if (before.TargetWeight is null or 0m || x.Multiplier >= 1 || double.IsNaN(x.Multiplier))
{
Assert.AreEqual(before.TargetWeight, after.TargetWeight);
}
}
}, 60);
private sealed class Fixed(decimal? target) : IStrategy
{
public string Id => "fixed";
public string Version => "t";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
public IReadOnlyList<Intent> Decide(StrategyContext context) => [new Intent("BTC-EUR", target, "x")];
}
private sealed class Spy(Action<Intent> seen) : IIntentStage
{
public string Name => "spy";
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
{
foreach (var intent in intents)
{
seen(intent);
}
return intents;
}
}
// ---- The nightly cycle ------------------------------------------------------------------------------------------
/// <summary>An archive with a model in charge, and what the cycle needs to run on it.</summary>
private sealed class Night : IAsyncDisposable
{
private int _count;
public TradingRig Rig { get; private set; } = null!;
public LearningDesk Desk { get; private set; } = null!;
public LearningCycle Cycle { get; private set; } = null!;
public ModelRow Champion { get; private set; } = null!;
public static async Task<Night> CreateAsync()
{
var night = new Night { Rig = await TradingRig.CreateAsync().ConfigureAwait(false) };
night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero)); // A Wednesday, 03:00 in Rome.
night.Desk = new LearningDesk(night.Rig.Db, night.Rig.Clock) { First = Rates };
night.Cycle = new LearningCycle(night.Rig.Db, night.Rig.Clock, night.Desk, (_, _, _) => Task.FromResult<LabelData?>(null));
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { LastSunday = new DateOnly(2027, 2, 28) }).ConfigureAwait(false);
night.Champion = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
return night;
}
/// <summary>A closed signal with what each model said when it was born, the first one in charge.</summary>
public async Task CaseAsync(bool win, double result = 0.02, string stage = StrategyStages.Simulation, IReadOnlyDictionary<string, double>? features = null, params (ModelRow Model, double P)[] said)
{
var day = new DateOnly(2025, 1, 1).AddDays(_count++);
await Rig.Db.WriteAsync(async s =>
{
var id = (await LearningStore.AddAsync(s, Rig.Clock, new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
"trend_entry", 0.2m, null, null, features ?? new Dictionary<string, double> { [Clues.Strength] = 0.5 })
{ Stage = stage, Label = new CaseLabel(win, win ? result : -result, day.AddDays(1), day.AddDays(1), "x") }, _none).ConfigureAwait(false))!.Value;
foreach (var (model, p) in said)
{
await ModelStore.AddPredictionAsync(s, Rig.Clock, new PredictionRow(id, model.Id, p, 0.4, MultiplierRule.Standard.Of(p, 0.4), model.Id == Champion.Id), _none).ConfigureAwait(false);
}
}, _none).ConfigureAwait(false);
}
public async Task<string> RunAsync()
{
await Cycle.RunAsync(_none).ConfigureAwait(false);
return (await DiaryAsync().ConfigureAwait(false)).LastOrDefault() ?? "";
}
public void ToSunday() => Rig.Clock.Set(new DateTimeOffset(2027, 3, 7, 2, 0, 0, TimeSpan.Zero));
public Task<List<string>> DiaryAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE kind = 'Apprendimento' ORDER BY occurred_at, id", r => r.Text("message")), _none);
public Task<List<string>> NotificationsAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT kind FROM notifications ORDER BY created_at, id", r => r.Text("kind")), _none);
public async Task<string> StatusAsync(Guid id) => (await Desk.Models.AllAsync(_none).ConfigureAwait(false)).Single(m => m.Id == id).Status;
public ValueTask DisposeAsync() => Rig.DisposeAsync();
}
/// <summary>SPEC 11.4, 5.6: one run labels what matured and says once that nothing is wrong.</summary>
[TestMethod]
public async Task TheNightLabelsWhatMaturedAndSaysItOnce()
{
var last = From.AddDays(24);
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
rig.UseFirst(Rates);
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
for (var day = From; day <= last; day = day.AddDays(1))
{
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
var open = (await rig.Learning.Store.OpenAsync(_none).ConfigureAwait(false)).Count;
await cycle.RunAsync(_none).ConfigureAwait(false);
await cycle.RunAsync(_none).ConfigureAwait(false);
var after = await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false);
Assert.IsGreaterThan(0, open - after.Count(e => e.Label is null));
// The labels are those of the history on the same bars.
var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR");
foreach (var example in after)
{
Assert.AreEqual(CaseLabels.Of(example, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, last.AddDays(-1)), example.Label);
}
var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
Assert.AreEqual("Controllo del modello: nessuna anomalia.", diary.Single());
}
/// <summary>SPEC 5.6: off for three nights, the job of the model runs once at the return, labels what matured meanwhile and says one line.</summary>
[TestMethod]
public async Task AfterThreeDaysOffLabelsAndCheckAreMadeOnce()
{
var off = From.AddDays(14);
var last = From.AddDays(24);
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
rig.UseFirst(Rates);
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
for (var day = From; day <= off; day = day.AddDays(1))
{
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
}
var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
await cycle.RunAsync(_none).ConfigureAwait(false);
var labelled = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null);
var went = rig.Rig.Clock.UtcNow;
// Back on the fourth day, with the bars of the meantime already there: the real job of the engine, as it is registered.
for (var day = off; day < last; day = day.AddDays(1))
{
await rig.StoreBarAsync(day).ConfigureAwait(false);
}
rig.Rig.Clock.Set(new DateTimeOffset(last.ToDateTime(new TimeOnly(9, 0)), TimeSpan.Zero));
var runs = 0;
var scheduler = new Scheduler(rig.Rig.Clock, new EventBus());
scheduler.Add(TradingService.ModelJob(async ct =>
{
await cycle.RunAsync(ct).ConfigureAwait(false);
runs++;
}), went);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
for (var i = 0; i < 600 && runs == 0; i++)
{
await Task.Delay(50, _none).ConfigureAwait(false);
}
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
Assert.AreEqual(1, runs, "one run for all the missed nights");
var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
Assert.HasCount(2, diary, "one line before and one at the return");
Assert.IsGreaterThan(labelled, (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null), "what matured meanwhile has its label");
}
/// <summary>The challenger replaces the one in charge only at a threshold and only when the advantage is not chance; one click takes it back.</summary>
[TestMethod]
public async Task AChallengerThatIsReallyBetterIsPromotedAtAThreshold()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
var gen = new Gen(3);
for (var i = 0; i < 99; i++)
{
var win = gen.Double() < 0.4;
await night.CaseAsync(win, said: [(night.Champion, 0.4), (challenger, win ? 0.6 : 0.25)]).ConfigureAwait(false);
}
night.ToSunday();
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "99 cases: no decision yet");
await night.CaseAsync(true, said: [(night.Champion, 0.4), (challenger, 0.6)]).ConfigureAwait(false);
night.Rig.Clock.Advance(TimeSpan.FromDays(3));
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "100 cases but not a Sunday");
night.Rig.Clock.Advance(TimeSpan.FromDays(4));
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
Assert.AreEqual(ModelStatuses.Retired, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_promoted");
Assert.IsTrue(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false));
Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
Assert.IsFalse(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false), "only once");
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "what the user took back does not come back");
}
/// <summary>An advantage that is chance never promotes; after 300 cases the challenger is discarded. Between thresholds nothing is decided.</summary>
[TestMethod]
public async Task AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
var gen = new Gen(8);
night.ToSunday();
for (var i = 0; i < 300; i++)
{
await night.CaseAsync(gen.Double() < 0.4, said: [(night.Champion, 0.4), (challenger, 0.4 + (gen.Double() * 0.1) - 0.05)]).ConfigureAwait(false);
if (i is 99 or 120 or 260)
{
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
await night.RunAsync().ConfigureAwait(false);
var row = (await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false))!;
Assert.AreEqual(i switch { 99 or 120 => 100, _ => 250 }, row.ThresholdDone);
}
}
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(ModelStatuses.Discarded, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
Assert.IsTrue((await night.DiaryAsync().ConfigureAwait(false)).Any(d => d.StartsWith("Scartata la versione", StringComparison.Ordinal)));
}
/// <summary>On Sunday, without a challenger and with new outcomes, one is trained; a Sunday missed while off is done at the next run, once.</summary>
[TestMethod]
public async Task OnSundayAChallengerIsTrainedOnce()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
await night.Rig.Db.WriteAsync(async s =>
{
foreach (var example in LearningModelTests.Cases(300, x => Odds.Probability(x[1]), source: CaseSources.Live))
{
await LearningStore.AddAsync(s, night.Rig.Clock, example, _none).ConfigureAwait(false);
}
}, _none).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNull(await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false), "a Wednesday");
// Off from Wednesday to the Tuesday after two Sundays: one training at the return.
night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 16, 9, 0, 0, TimeSpan.Zero));
await night.RunAsync().ConfigureAwait(false);
var challenger = await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
Assert.AreEqual((2, 300), (challenger!.Version, challenger.Examples));
await night.RunAsync().ConfigureAwait(false);
var all = await night.Desk.Models.AllAsync(_none).ConfigureAwait(false);
Assert.HasCount(4, all, "champion, challenger and its two attempts");
Assert.HasCount(1, all.Where(m => m.Status == ModelStatuses.Challenger));
// On trial it is never retrained, and without new outcomes the next one is not trained either.
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
await night.RunAsync().ConfigureAwait(false);
await night.Rig.Db.WriteAsync(s => ModelStore.SetStatusAsync(s, night.Rig.Clock, challenger.Id, ModelStatuses.Discarded, _none), _none).ConfigureAwait(false);
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
await night.RunAsync().ConfigureAwait(false);
Assert.HasCount(4, await night.Desk.Models.AllAsync(_none).ConfigureAwait(false));
}
/// <summary>Precision under 50% on at least 40 cases: set aside, said once, until it comes back.</summary>
[TestMethod]
public async Task ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
for (var i = 0; i < 39; i++)
{
// Always wrong: what it says is likely loses.
await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.35 : 0.42)]).ConfigureAwait(false);
}
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
await night.CaseAsync(false, said: [(night.Champion, 0.42)]).ConfigureAwait(false);
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
Assert.Contains("lo metto da parte", (await night.RunAsync().ConfigureAwait(false)).ToLowerInvariant());
Assert.AreEqual(AsideCodes.Precision, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
Assert.Contains("resta da parte", await night.RunAsync().ConfigureAwait(false));
for (var i = 0; i < 60; i++)
{
await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.45 : 0.35)]).ConfigureAwait(false);
}
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
Assert.Contains("rientrata dopo 2 giorni", await night.RunAsync().ConfigureAwait(false));
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
CollectionAssert.AreEqual(new[] { "model_set_aside", "model_back" }, await night.NotificationsAsync().ConfigureAwait(false));
}
/// <summary>While it is set aside, by itself or by the user, the gate lets everything through.</summary>
[TestMethod]
public async Task SetAsideMeansMultiplierOne()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
var settings = new SettingsStore(night.Rig.Db, night.Rig.Clock, new EventBus());
var desk = new LearningDesk(night.Rig.Db, night.Rig.Clock, settings) { First = Rates };
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "in observation");
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow }).ConfigureAwait(false);
Assert.IsTrue((await desk.GateAsync(_none).ConfigureAwait(false)).Counts);
await settings.SetAsync(LearningSettings.Aside.Key, "on", "test", _none).ConfigureAwait(false);
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by the user");
await settings.SetAsync(LearningSettings.Aside.Key, "off", "test", _none).ConfigureAwait(false);
await settings.SetAsync(LearningSettings.Zero.Key, "20", "test", _none).ConfigureAwait(false);
Assert.AreEqual(new MultiplierRule(0, 0.20), (await desk.GateAsync(_none).ConfigureAwait(false)).Rule);
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow, Aside = AsideCodes.ClueDrift }).ConfigureAwait(false);
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by itself");
}
/// <summary>The error rises: ADWIN sees it and the model is set aside.</summary>
[TestMethod]
public async Task ARisingErrorSetsTheModelAside()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
for (var i = 0; i < 120; i++)
{
var win = i % 5 < 2;
await night.CaseAsync(win, said: [(night.Champion, win ? 0.95 : 0.05)]).ConfigureAwait(false);
}
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
for (var i = 0; i < 24; i++)
{
// Still more right than wrong on the last 60, but suddenly much worse.
var win = i % 5 < 2;
await night.CaseAsync(win, said: [(night.Champion, win ? 0.1 : 0.9)]).ConfigureAwait(false);
}
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
await night.RunAsync().ConfigureAwait(false);
Assert.AreEqual(AsideCodes.ErrorDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
}
/// <summary>The clues leave what the model studied: set aside, naming them. The clues not in use do not count.</summary>
[TestMethod]
public async Task CluesNeverStudiedSetTheModelAside()
{
await using var night = await Night.CreateAsync().ConfigureAwait(false);
for (var i = 0; i < 60; i++)
{
await night.CaseAsync(i % 5 < 2, features: new Dictionary<string, double> { [Clues.Strength] = i < 48 ? 0.5 : 3, [Clues.Vix] = 900 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
}
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false), "a fifth is not more than a fifth");
for (var i = 0; i < 4; i++)
{
await night.CaseAsync(false, features: new Dictionary<string, double> { [Clues.Strength] = 3 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
}
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
Assert.Contains("forza della tendenza", await night.RunAsync().ConfigureAwait(false));
Assert.AreEqual(AsideCodes.ClueDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
}
/// <summary>SPEC 11.5: it starts to count with 300 signals, good calibration and a gain that is not chance, and only all three.</summary>
[TestMethod]
public async Task ItStartsToCountOnlyWithAllThreeCriteria()
{
// 40% of wins: 48% among those estimated 0.48, 28% among those estimated 0.28.
async Task Fill(Night night, int count, Func<int, double> said, string stage = StrategyStages.Simulation)
{
for (var i = 0; i < count; i++)
{
var high = i % 5 < 3;
var win = high ? i % 25 is 0 or 1 or 5 or 6 or 10 or 11 or 15 : i % 25 is 3 or 8 or 13;
await night.CaseAsync(win, stage: stage, said: [(night.Champion, said(i))]).ConfigureAwait(false);
}
}
static double Calibrated(int i) => i % 5 < 3 ? 0.47 : 0.30;
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
{
await Fill(night, 299, Calibrated).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "299 signals");
await Fill(night, 1, Calibrated).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNotNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt);
CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_activated");
}
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
{
await Fill(night, 320, i => i % 5 < 3 ? 0.75 : 0.15).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "badly calibrated");
}
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
{
await Fill(night, 320, _ => 0.41).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no improvement");
}
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
{
await Fill(night, 320, Calibrated, StrategyStages.Observation).ConfigureAwait(false);
await night.RunAsync().ConfigureAwait(false);
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no signal of a strategy with capital");
}
}
/// <summary>ADWIN on known cases: a jump is seen, its direction too, noise alone is not.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AdwinSeesAJumpAndNotTheNoise()
{
var alarms = 0;
for (var seed = 0; seed < 50; seed++)
{
var gen = new Gen(seed);
var adwin = new Adwin();
alarms += Enumerable.Range(0, 400).Any(_ => adwin.Add(gen.Double()) != 0) ? 1 : 0;
}
Assert.IsLessThanOrEqualTo(2, alarms, "false alarms on noise");
var up = new Adwin();
var random = new Gen(1);
var found = Enumerable.Range(0, 200).Select(i => (i, Change: up.Add((i < 100 ? 0.2 : 0.6) + (random.Double() * 0.2)))).First(x => x.Change != 0);
Assert.AreEqual(1, found.Change);
Assert.IsTrue(found.i is >= 100 and < 140, $"{found.i}");
Assert.IsLessThan(40, up.Count - (200 - found.i - 1), "the older part is dropped");
var down = new Adwin();
Assert.AreEqual(-1, Enumerable.Range(0, 200).Select(i => down.Add(i < 100 ? 0.8 : 0.2)).First(c => c != 0));
}
}