using System.Text.Json; using Anubis.Learning; using Anubis.Trading; namespace Anubis.Tests; /// The learners, their calibration, the purged validation and the choice (SPEC 11.1, 11.3; issue #63). [TestClass] [TestCategory(Category.Unit)] public sealed class LearningModelTests { private static readonly DateOnly First = new(2020, 1, 1); /// /// Examples whose outcome depends on what says of the clues. Wins pay 2%, losses cost 2%: /// a filter that avoids likely losses earns. /// internal static IReadOnlyList Cases(int count, Func chance, int seed = 5, string strategy = StrategyNames.CryptoTrend, int length = 8, string source = CaseSources.History) { var gen = new Gen(seed); return [ .. Enumerable.Range(0, count).Select(i => { var clues = new[] { gen.Double(), gen.Normal(), gen.Double(), gen.Normal() }; var win = gen.Double() < chance(clues); var day = First.AddDays(i * 2); var result = win ? 0.02 : -0.02; return new Example(Guid.NewGuid(), strategy, "C" + (i % 7), source, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "test", 0.2m, null, null, new Dictionary { [Clues.Strength] = clues[0], [Clues.Volatility] = clues[1], [Clues.Volume] = clues[2], [Clues.MarketTrend] = clues[3], }) { Label = new CaseLabel(win, result, day, day.AddDays(1 + (i % length)), "exit"), }; }), ]; } private static List Rows(IEnumerable cases) => [.. cases.Select(c => Trainer.Row([Clues.Strength, Clues.Volatility, Clues.Volume, Clues.MarketTrend], c.Features))]; private static List Wins(IEnumerable cases) => [.. cases.Select(c => c.Label!.Win == true)]; private static double Loss(Learned model, IReadOnlyList cases) => cases.Average(c => Judge.LogLoss(c.Label!.Win == true, Odds.Probability(model.Score(Rows([c])[0])))); /// Each learner finds a relation that is there: on new examples it is clearly better than the plain share of wins. [TestMethod] [DataRow(LearnerNames.Logistic)] [DataRow(LearnerNames.Boosting)] [DataRow(LearnerNames.Forest)] public void ALearnerFindsWhatIsThere(string learner) { static double Chance(double[] x) => Odds.Probability((4 * x[0]) - 2); var train = Cases(1200, Chance, 5); var fresh = Cases(1200, Chance, 6); var model = Learners.Fit(learner, Rows(train), Wins(train), 1); var share = Wins(train).Count(w => w) / 1200.0; var plain = fresh.Average(c => Judge.LogLoss(c.Label!.Win == true, share)); Assert.IsLessThan(plain - 0.03, Loss(model, fresh)); } /// The trees find what a straight line cannot: an exclusive or. [TestMethod] public void TheTreesFindWhatALineCannot() { static double Chance(double[] x) => (x[0] > 0.5) == (x[2] > 0.5) ? 0.85 : 0.15; var train = Cases(1500, Chance, 5); var fresh = Cases(1500, Chance, 6); var line = Loss(Learners.Fit(LearnerNames.Logistic, Rows(train), Wins(train), 1), fresh); var trees = Loss(Learners.Fit(LearnerNames.Boosting, Rows(train), Wins(train), 1), fresh); Assert.IsGreaterThan(0.65, line); Assert.IsLessThan(0.55, trees); } /// Same data and seed, same model, to the last digit; and it survives the database as it was. [TestMethod] [DataRow(LearnerNames.Logistic)] [DataRow(LearnerNames.Boosting)] [DataRow(LearnerNames.Forest)] public void TheSameDataGiveTheSameModel(string learner) { var cases = Cases(300, x => Odds.Probability(x[1])); var clues = Trainer.CluesOf(cases); var one = Trainer.Fit(learner, cases, clues, 3); var two = Trainer.Fit(learner, cases, clues, 3); Assert.AreEqual(JsonSerializer.Serialize(one), JsonSerializer.Serialize(two)); var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(one))!; foreach (var c in cases) { Assert.AreEqual(one.Probability(c.Features), back.Probability(c.Features)); } } /// A missing clue is no trouble, neither to learn nor to estimate, and tells what it tells. [TestMethod] [DataRow(LearnerNames.Logistic)] [DataRow(LearnerNames.Boosting)] [DataRow(LearnerNames.Forest)] public void AMissingClueIsNoTrouble(string learner) { var cases = Cases(600, x => Odds.Probability((4 * x[0]) - 2)).Select((c, i) => i % 3 > 0 ? c : c with { Features = c.Features.Where(f => f.Key != Clues.Strength).ToDictionary(f => f.Key, f => f.Value) }).ToList(); var model = Trainer.Fit(learner, cases, Trainer.CluesOf(cases), 3); foreach (var features in new[] { new Dictionary(), new Dictionary { [Clues.Strength] = double.NaN }, new Dictionary { [Clues.Strength] = 1e9, [Clues.Volatility] = -1e9 } }) { var p = model.Probability(features); Assert.IsTrue(p is > 0 and < 1, $"{p}"); } } /// Trees keep many examples in every leaf. [TestMethod] public void EveryLeafHasManyExamples() { var cases = Cases(800, x => Odds.Probability(x[1])); var rows = Rows(cases); Assert.AreEqual(40, Learners.MinLeaf(800)); foreach (var tree in Learners.Fit(LearnerNames.Boosting, rows, Wins(cases), 1).Trees!.Trees) { Assert.IsLessThanOrEqualTo(15, tree.Feature.Count, "no more than three levels"); } } [TestMethod] public void PlattBringsScoresBackToTheTruth() { // The scores are three times too sure: the calibration must bring them back. var gen = new Gen(9); var scores = Enumerable.Range(0, 900).Select(_ => gen.Normal() * 3).ToList(); var wins = scores.Select(s => gen.Double() < Odds.Probability(s / 3)).ToList(); var fitted = Calibration.Fit(scores, wins); Assert.AreEqual(Calibration.PlattKind, fitted.Kind); Assert.AreEqual(1.0 / 3, fitted.Slope, 0.07); // Scores that say the opposite, or nothing, become the plain share of wins. var upside = Calibration.Fit(scores, [.. wins.Select(w => !w)]); Assert.AreEqual(0, upside.Slope); Assert.AreEqual((double)wins.Count(w => !w) / wins.Count, upside.Probability(5), 0.01); Assert.AreEqual(0, Calibration.Platt([1, 1, 1, 1], [true, false, true, true]).Slope); } /// Isotonic on a known case: the classic pools, never down, never 0 or 1. [TestMethod] public void IsotonicNeverGoesDown() { var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true], 1); Assert.AreEqual(0.5, known.Probability(2.5), 1e-9); var gen = new Gen(4); var scores = Enumerable.Range(0, 1500).Select(_ => gen.Normal()).ToList(); var wins = scores.Select(s => gen.Double() < Odds.Probability(2 * s)).ToList(); var fitted = Calibration.Fit(scores, wins); Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind); var last = 0.0; for (var s = -6.0; s <= 6; s += 0.01) { var p = fitted.Probability(s); Assert.IsTrue(p >= last && p is > 0 and < 1, $"{s}: {p} after {last}"); last = p; } Assert.AreEqual(Odds.Probability(1), fitted.Probability(0.5), 0.08); } // ---- Validation ------------------------------------------------------------------------------------------------- /// No training example overlaps a test one in time, nor starts in the embargo after it; going forward, all is over before. [TestMethod] public void TrainingAndTestNeverOverlap() => Property.ForAll( gen => { var at = First; return Enumerable.Range(0, gen.Int(20, 80)).Select(i => { at = at.AddDays(gen.Int(0, 6)); return Cases(1, _ => 0.5)[0] with { Day = at, Symbol = "S" + i, Label = new CaseLabel(gen.Bool(), 0.01, at, at.AddDays(gen.Int(0, 90)), "x") }; }).ToList(); }, cases => { var splits = CaseSplits.Combinatorial(cases); Assert.HasCount(15, splits); foreach (var split in splits.Concat(CaseSplits.Folds(cases))) { foreach (var train in split.Train.Select(i => cases[i])) { foreach (var test in split.Test.Select(i => cases[i])) { Assert.IsTrue(train.Label!.ClosedDay < test.Day || train.Day > test.Label!.ClosedDay!.Value.AddDays(CaseSplits.Embargo), $"{train.Day}..{train.Label.ClosedDay} / {test.Day}..{test.Label!.ClosedDay}"); } } } // Each example is verified by as many splits as it should be: 5 of the 15. Assert.IsTrue(splits.SelectMany(s => s.Test).GroupBy(i => i).All(g => g.Count() == 5)); foreach (var split in CaseSplits.Forward(cases)) { var begins = split.Test.Min(i => cases[i].Day); Assert.IsTrue(split.Train.All(i => cases[i].Label!.ClosedDay < begins)); } }, 40); /// Known case: ten examples a month apart, each 40 days long. [TestMethod] public void ThePurgeOnAKnownCase() { var cases = Enumerable.Range(0, 6).Select(i => { var day = First.AddDays(i * 30); return Cases(1, _ => 0.5)[0] with { Day = day, Symbol = "S" + i, Label = new CaseLabel(true, 0.01, day, day.AddDays(40), "x") }; }).ToList(); // Groups of one example. Testing on example 2 (day 60 to 100, embargo to 110): 1 ends on day 70 and 3 starts on 90, so both go; 0 ends on day 40, 4 starts on 120. var split = CaseSplits.Folds(cases, 6)[2]; CollectionAssert.AreEqual(new[] { 0, 4, 5 }, split.Train.ToArray()); } // ---- Measures --------------------------------------------------------------------------------------------------- private static Estimate Of(bool win, double probability, double rate = 0.4, double multiplier = 1, double result = 0.02, string strategy = StrategyNames.CryptoTrend) => new(Cases(1, _ => 0.5, strategy: strategy)[0] with { Label = new CaseLabel(win, win ? result : -result, First, First, "x") }, probability, rate, multiplier); private static readonly Dictionary Capital = new() { [StrategyNames.CryptoTrend] = 1000, [StrategyNames.EquityMomentum] = 1000 }; /// Who always says the same stays at 50%, whatever the share of wins. [TestMethod] public void AlwaysTheSameAnswerIsFiftyPercent() { foreach (var answer in new[] { 0.1, 0.4, 0.9 }) { Assert.AreEqual(0.5, Judge.Precision([.. Enumerable.Range(0, 100).Select(i => Of(i < 37, answer))])); } Assert.AreEqual(1.0, Judge.Precision([Of(true, 0.6), Of(false, 0.2), Of(false, 0.1)])); Assert.IsNull(Judge.Precision([Of(true, 0.6)])); } /// The gain is divided by the proposed operations, not by those left: discarding nearly all cannot look good. [TestMethod] public void AModelThatDiscardsNearlyAllDoesNotLookBetter() { // 50 wins of 4 euro, 50 losses of 2: keeping a single win earns 4 a piece on what is left, but 0.04 per proposal. var all = Enumerable.Range(0, 100).Select(i => Of(i < 50, 0.4, result: i < 50 ? 0.02 : 0.01)).ToList(); var picky = all.Select((e, i) => e with { Multiplier = i == 0 ? 1 : 0 }).ToList(); Assert.AreEqual(1.0, Judge.Score(all, Capital).GainWith, 1e-9); Assert.AreEqual(0.04, Judge.Score(picky, Capital).GainWith, 1e-9); Assert.IsLessThan(0, Judge.Score(picky, Capital).Improvement); // Zeroing the signals of a strategy without capital is no merit. var other = Enumerable.Range(0, 100).Select(_ => Of(false, 0.1, multiplier: 0, strategy: StrategyNames.EquityMomentum)); Assert.AreEqual(0, Judge.Score([.. all, .. other], Capital, e => e.Strategy == StrategyNames.CryptoTrend).Improvement, 1e-9); } /// Losses mature first (SPEC 11.4): the weights give back the proportion of the base rate. [TestMethod] public void TheWeightsGiveBackTheProportionOfTheBaseRate() { var estimates = Enumerable.Range(0, 100).Select(i => Of(i < 20, 0.4)).ToList(); var weighed = Judge.Weigh(estimates, new Dictionary { [StrategyNames.CryptoTrend] = 0.4 }); Assert.AreEqual(0.4, weighed.Where(e => e.Win).Sum(e => e.Weight) / weighed.Sum(e => e.Weight), 1e-9); Assert.AreEqual(100, weighed.Sum(e => e.Weight), 1e-9); Assert.IsTrue(Judge.Weigh([.. estimates.Where(e => e.Win)], new Dictionary { [StrategyNames.CryptoTrend] = 0.4 }).All(e => e.Weight == 1)); } [TestMethod] public void TheCalibrationErrorCountsOnlyBandsWithEnoughCases() { // 20 cases at 42% with 8 wins (40%), 19 cases at 80% all lost: only the first band counts. var estimates = Enumerable.Range(0, 20).Select(i => Of(i < 8, 0.42)).Concat(Enumerable.Range(0, 19).Select(_ => Of(false, 0.8))).ToList(); var scores = Judge.Score(estimates, Capital); Assert.AreEqual(0.02, scores.CalibrationError!.Value, 1e-9); Assert.HasCount(2, scores.Bands); Assert.IsNull(Judge.Score([.. estimates.Take(19)], Capital).CalibrationError); } /// The interval contains the truth and knows that neighbours are not independent. [TestMethod] public void TheIntervalKeepsNeighboursTogether() { var gen = new Gen(3); var alone = Enumerable.Range(0, 400).Select(_ => gen.Normal() + 0.05).ToList(); var ones = alone.Select(_ => 1.0).ToList(); var (low, high) = Judge.Interval(alone, ones, 0.95); Assert.IsTrue(low < 0.05 && high > 0.05 && high - low is > 0.1 and < 0.3, $"{low} {high}"); var twins = alone.SelectMany(v => Enumerable.Repeat(v, 10)).Take(400).ToList(); var (from, to) = Judge.Interval(twins, ones, 0.95); Assert.IsGreaterThan(1.8 * (high - low), to - from); } // ---- Multiplier ------------------------------------------------------------------------------------------------- /// Criterion of the phase: whatever the numbers and the thresholds, the multiplier is between 0 and 1. [TestMethod] public void TheMultiplierNeverExceedsOne() { double[] odd = [double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1, 0, 1, 2, 1e300, -1e300]; Property.ForAll( gen => (P: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(), B: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(), Rule: new MultiplierRule(gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.2, gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.4)), x => { var m = x.Rule.Of(x.P, x.B); Assert.IsTrue(m is >= 0 and <= 1, $"{m}"); Assert.IsGreaterThanOrEqualTo(x.Rule.Of(x.P - 0.01, x.B) - 1e-4, m, "a better estimate never shrinks more"); }, 5000); Assert.AreEqual(1, MultiplierRule.Standard.Of(0.42, 0.42)); Assert.AreEqual(1, MultiplierRule.Standard.Of(0.9, 0.42)); Assert.AreEqual(0.5, MultiplierRule.Standard.Of(0.37, 0.42), 1e-4); Assert.AreEqual(0, MultiplierRule.Standard.Of(0.32, 0.42)); Assert.AreEqual(0, MultiplierRule.Standard.Of(0.01, 0.42)); } // ---- Training --------------------------------------------------------------------------------------------------- internal static TrainingInput Input(IReadOnlyList cases) => new(cases) { BaseRates = Trainer.SharesOf(cases), Capital = Capital, Funded = new HashSet { StrategyNames.CryptoTrend }, }; /// With something to learn the model earns on examples it had not studied, and it says what it looks at. [TestMethod] public void TrainingFindsTheClueThatCounts() { var cases = Cases(500, x => x[0] > 0.5 ? 0.75 : 0.25); var result = Trainer.Train(Input(cases))!; Assert.IsNotNull(result); var chosen = result.Report.Chosen!; Assert.IsGreaterThan(0.2, chosen.Combined.Improvement); Assert.IsGreaterThan(0.2, chosen.Forward.Improvement); Assert.IsLessThan(chosen.Combined.BaseLogLoss - 0.05, chosen.Combined.LogLoss); Assert.IsGreaterThan(0.65, chosen.Combined.Precision!.Value); Assert.AreEqual("Forza della tendenza", result.Report.Weights[0].Group); Assert.IsGreaterThan(80m, result.Report.Weights[0].Share); Assert.AreEqual(100m, result.Report.Weights.Sum(w => w.Share)); // Every attempt is in the report, with the same number of verified cases. CollectionAssert.AreEquivalent(LearnerNames.All.ToArray(), result.Report.Attempts.Select(a => a.Learner).ToArray()); Assert.HasCount(1, result.Report.Attempts.Where(a => a.Chosen)); Assert.HasCount(1, result.Report.Attempts.Select(a => a.Combined.Cases).Distinct()); Assert.IsFalse(result.Report.AllStrategiesCounted); } /// With nothing to learn it answers about the base rate: it does not invent a gain nor lose much. [TestMethod] public void WithNothingToLearnItChangesLittle() { var result = Trainer.Train(Input(Cases(500, _ => 0.42)))!; var chosen = result.Report.Chosen!; Assert.AreEqual(chosen.Combined.BaseLogLoss, chosen.Combined.LogLoss, 0.02); Assert.AreEqual(0.5, chosen.Combined.Precision!.Value, 0.07); foreach (var example in Cases(100, _ => 0.42, 77)) { Assert.AreEqual(0.42, result.Model.Probability(example.Features), 0.12); } } [TestMethod] public void TooFewExamplesOrOneOutcomeTrainNothing() { Assert.IsNull(Trainer.Train(Input(Cases(99, _ => 0.5)))); Assert.IsNull(Trainer.Train(Input(Cases(300, _ => 2)))); var open = Cases(300, _ => 0.5).Select((c, i) => i < 99 ? c : c with { Label = i % 2 == 0 ? null : new CaseLabel(null, null, null, c.Day, CaseOutcomes.NeverStarted) }).ToList(); Assert.IsNull(Trainer.Train(Input(open)), "an example without outcome never trains"); } /// SPEC 11.2: a clue without history waits for 200 live examples that contain it. [TestMethod] public void AClueWithoutHistoryWaitsForTwoHundredLiveExamples() { var history = Cases(300, _ => 0.5); IReadOnlyList With(int live, string source) => [ .. history, .. Cases(live, _ => 0.5, 8, source: source).Select((c, i) => c with { Features = new Dictionary(c.Features) { [Clues.FearGreed] = i } }), ]; Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(199, CaseSources.Live))); Assert.Contains(Clues.FearGreed, Trainer.CluesOf(With(200, CaseSources.Live))); Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(400, CaseSources.History))); Assert.DoesNotContain(Clues.Breadth, Trainer.CluesOf(history), "never seen"); } // ---- The first model ---------------------------------------------------------------------------------------------- /// /// The file in the program is whole: its base rates are the shares of its examples, its report counts them, and /// training again on them gives the same estimates (to the sixth digit: the platforms differ in the last ones). /// [TestMethod] public void TheFirstModelIsTheOneOfItsExamples() { var file = FirstModel.Embedded!; Assert.IsNotNull(file); var labelled = file.Examples.Where(e => e.IsLabelled).ToList(); Assert.IsGreaterThan(1000, labelled.Count); Assert.AreEqual(labelled.Count, file.Report!.Examples); foreach (var (strategy, rate) in Trainer.SharesOf(file.Examples)) { Assert.AreEqual(rate, file.BaseRates[strategy], 1e-12); } Assert.IsTrue(file.Examples.All(e => e.Source == CaseSources.History && e.Day <= file.Through && (e.Label?.ClosedDay is not { } closed || closed <= file.Through))); Assert.HasCount(3, file.Report.Attempts); var again = Trainer.Fit(file.Model!.Learned.Learner, [.. labelled.OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal)], file.Model.Clues, 11); foreach (var e in labelled) { Assert.AreEqual(file.Model.Probability(e.Features), again.Probability(e.Features), 1e-6); } Assert.Contains("parte in osservazione", FirstModel.Markdown(file, "x")); } /// At the first start the examples and the model are there, once; a new file replaces the examples and not the model. [TestMethod] [TestCategory(Category.Integration)] public async Task TheFirstModelTakesChargeAtTheFirstStart() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var none = CancellationToken.None; var file = FirstModel.Train(Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), none); var desk = new LearningDesk(rig.Db, rig.Clock) { First = file }; await desk.PrepareHistoryAsync(none).ConfigureAwait(false); await desk.PrepareHistoryAsync(none).ConfigureAwait(false); Assert.AreEqual(300, await desk.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false)); var models = await desk.Models.AllAsync(none).ConfigureAwait(false); Assert.HasCount(3, models, "the chosen one and the two attempts"); var champion = models.Single(m => m.Status == ModelStatuses.Champion); Assert.AreEqual((1, 300), (champion.Version, champion.Examples)); Assert.IsTrue(models.Where(m => m.Id != champion.Id).All(m => m is { Status: ModelStatuses.Tried, Version: null, Model: null } && m.Report.Attempts.Count == 1)); foreach (var e in file.Examples) { Assert.AreEqual(file.Model!.Probability(e.Features), champion.Model!.Probability(e.Features)); } Assert.HasCount(1, await desk.Models.EventsAsync(none).ConfigureAwait(false)); var later = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), none) }; await later.PrepareHistoryAsync(none).ConfigureAwait(false); Assert.AreEqual(320, await later.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false)); Assert.AreEqual(champion.Id, (await later.Models.FindAsync(ModelStatuses.Champion, none).ConfigureAwait(false))!.Id); Assert.HasCount(1, await later.Models.EventsAsync(none).ConfigureAwait(false)); } /// The rule of the choice, fixed before the numbers. [TestMethod] public void TheChoiceFollowsTheRule() { static Attempt A(string learner, double gain, double loss) => new(learner, new Scores(), new Scores { GainWith = gain, LogLoss = loss }, false); string Chosen(params Attempt[] attempts) => Trainer.Choose(attempts).Learner; Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.66))); Assert.AreEqual(LearnerNames.Forest, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.64))); Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 1, 0.60), A(LearnerNames.Logistic, 2, 0.65), A(LearnerNames.Forest, 1, 0.5))); Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 0, 0.66), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.5))); Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 0, 0.65), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.65))); } }