using Anubis.Backtest; using Anubis.Core; using Anubis.Data; using Anubis.Db; using Anubis.Learning; using Anubis.Strategies; using Anubis.Trading; namespace Anubis.Tests; /// The improvements in observation of SPEC 8.7 (issue #74): computed, measured, shown, and never acting. [TestClass] public sealed class ShadowTests { private static readonly CancellationToken _none = CancellationToken.None; private static readonly DateOnly Monday = new(2025, 1, 6); private static readonly IReadOnlyList _days = StrategyData.BusinessDays(Monday, 260); private static DateOnly Today => _days[^1]; private static BacktestInstrument Stock(string symbol, Func close) => new(StrategyData.Share(symbol), [.. _days.Select((d, i) => new DailyBar(d, close(i), close(i) * 1.01, close(i) * 0.99, close(i), 100_000))]); private static StrategyContext Context(IReadOnlyList stocks, IReadOnlyDictionary? holdings = null, DateOnly? day = null) { var data = new BacktestDataset(stocks.Any(s => s.Symbol == StrategyNames.MarketSymbol) ? stocks : [.. stocks, Stock(StrategyNames.MarketSymbol, _ => 400)], "USD"); var at = day ?? Today; return new StrategyContext(at, new DateTimeOffset(at.ToDateTime(new TimeOnly(20, 20)), TimeSpan.Zero), [.. stocks.Select(s => s.Symbol)], new PortfolioView(10_000m, 10_000m, holdings ?? new Dictionary()), s => data[s]!.SeriesThrough(at), s => data[s]?.Spec) { PeriodsPerYear = 252 }; } private static Intent Entry(string symbol, double strength = 0, decimal weight = 0.1m) => new(symbol, weight, "entry") { StopOffset = 1m, Strength = strength }; private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList intents, ShadowInput? input = null, Func? probability = null, string stage = StrategyStages.Observation) { var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day); var turn = new ShadowTurn(strategy, stage, context.Day, collector, input ?? ShadowInput.Nothing, probability ?? ((_, _) => null), () => new EquityMeanrev()); Assert.AreSame(intents, collector.Apply(context, intents)); Assert.AreSame(intents, turn.OnProposals.Apply(context, intents), "the very same list: nothing changes"); Assert.AreSame(intents, turn.OnFinal.Apply(context, intents)); return turn; } [TestMethod] [TestCategory(Category.Unit)] public void TheFifthStockOfASectorWouldNotBeBought() { var stocks = "ABCDEFG".Select(c => Stock(c.ToString(), i => 50 + (i * 0.1))).ToList(); var held = new Dictionary { ["A"] = new(1m, 50m, null, Monday), ["B"] = new(1m, 50m, null, Monday) }; var context = Context(stocks, held); var sectors = "ABCDEF".ToDictionary(c => c.ToString(), _ => "73"); // B leaves: A and the three strongest fill the four places, F is the fifth. G has no known sector. var turn = Turn(StrategyNames.EquityMomentum, context, [new Intent("B", 0m, "exit"), Entry("C", 4), Entry("D", 3), Entry("E", 2), Entry("F", 1), Entry("G", 0.5)], new ShadowInput([], sectors)); var found = turn.Cases.Where(c => c.Improvement == Improvements.SectorCap).ToDictionary(c => c.Symbol, c => c.Factor); CollectionAssert.AreEquivalent(new[] { "C", "D", "E", "F", "G" }, found.Keys); Assert.AreEqual(0.0, found["F"]); Assert.IsTrue(found.Where(f => f.Key != "F").All(f => f.Value == 1)); Assert.IsFalse(Turn(StrategyNames.EquityMomentum, context, [Entry("C", 4)]).Cases.Any(c => c.Improvement == Improvements.SectorCap), "without any sector there is nothing to say"); } [TestMethod] [TestCategory(Category.Unit)] public void TheMarketFilterLooksAtSpyAgainstItsAverage() { foreach (var (slope, expected) in new[] { (0.3, 1.0), (-0.3, 0.0) }) { var context = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 + (i * slope))]); var made = Turn(StrategyNames.EquityMeanrev, context, [Entry("AAA")]).Cases.Single(c => c.Improvement == Improvements.MarketFilter); Assert.AreEqual(expected, made.Factor); } // Another day of the run says nothing. var other = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 - i)], day: _days[^2]); var collector = new CaseCollector(StrategyNames.EquityMeanrev, (_, _) => true, null, Today); var turn = new ShadowTurn(StrategyNames.EquityMeanrev, StrategyStages.Observation, Today, collector, ShadowInput.Nothing, (_, _) => null, () => new EquityMeanrev()); turn.OnProposals.Apply(other, collector.Apply(other, [Entry("AAA")])); Assert.IsEmpty(turn.Cases); } [TestMethod] [TestCategory(Category.Unit)] public void TheVolatilityOfTheWholePortfolioShrinksTheNewEntries() { // A stock that moves 2% up and down every day: 32% a year. At 100% of the momentum, 45% of the capital, it makes 14%. var stocks = new[] { Stock("AAA", i => i % 2 == 0 ? 100 : 102), Stock("BBB", i => 50) }; var context = Context(stocks); var alone = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 1m)]); var own = ShadowBook.Volatility([alone.Book!])!.Value; Assert.AreEqual(0.45 * 0.02 * Math.Sqrt(252), own, 0.002); var made = alone.Cases.Single(c => c.Improvement == Improvements.VolatilityCap); Assert.AreEqual(Improvements.MaxVolatility / own, made.Factor, 1e-6); // A small entry is left alone, unless the others already move the whole. var small = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 0.2m)]); Assert.AreEqual(1.0, small.Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor); var crowded = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 0.2m)], new ShadowInput([alone.Book!], new Dictionary())); Assert.IsLessThan(1.0, crowded.Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor); // A candidate is no part of the portfolio. var candidate = Turn(StrategyNames.StockAthBreakout, context, [Entry("AAA", weight: 1m)]); Assert.IsNull(candidate.Book); Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement); } private static readonly IReadOnlyList _moving = [Stock("AAA", i => i % 2 == 0 ? 100 : 102)]; private static Task DecideAsync(TradingRig rig, string strategy, string stage, DateOnly day) => rig.Db.WriteAsync(s => ShadowDesk.WriteAsync(s, rig.Clock, Guid.NewGuid(), Turn(strategy, Context(_moving, day: day), [Entry("AAA", weight: 1m)], stage: stage), strategy, _none), _none); [TestMethod] [TestCategory(Category.Integration)] public async Task AStrategyThatTradesCountsOnlyWhatTheOthersReallyHold() { await using var rig = await TradingRig.CreateAsync(); var desk = new LearningDesk(rig.Db, rig.Clock).Shadow; async Task BooksAsync(string stage) => string.Join(",", (await desk.InputAsync(StrategyNames.CryptoTrend, stage, Today, _none)).OtherBooks.Select(b => b.Stage).Order(StringComparer.Ordinal)); await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, Today); await DecideAsync(rig, StrategyNames.EquityMeanrev, StrategyStages.Simulation, Today); Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Simulation)); Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Real)); Assert.AreEqual("observation,simulation", await BooksAsync(StrategyStages.Observation), "one that only observes is measured on the three"); // The entry of one that trades is not shrunk by what another only looks at. async Task FactorAsync(string stage) => Turn(StrategyNames.EquityMeanrev, Context(_moving), [Entry("AAA", weight: 0.2m)], await desk.InputAsync(StrategyNames.EquityMeanrev, stage, Today, _none), stage: stage).Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor; Assert.AreEqual(1.0, await FactorAsync(StrategyStages.Simulation)); Assert.IsLessThan(1.0, await FactorAsync(StrategyStages.Observation)); // From the first decision it makes after its promotion, it counts. await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Simulation, Today); Assert.AreEqual("simulation,simulation", await BooksAsync(StrategyStages.Reduced)); } [TestMethod] [TestCategory(Category.Integration)] public async Task ADecisionRecoveredLateNeverSeesABookOfALaterDay() { await using var rig = await TradingRig.CreateAsync(); var desk = new LearningDesk(rig.Db, rig.Clock).Shadow; Task DecideOnAsync(DateOnly day) => DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, day); async Task SeenAsync(DateOnly day) => await desk.InputAsync(StrategyNames.EquityMeanrev, StrategyStages.Observation, day, _none) is var i && i.Whole ? string.Join(",", i.OtherBooks.Select(b => b.Day)) : "unknown"; Assert.AreEqual("", await SeenAsync(Today), "no decision yet, nothing held"); await DecideOnAsync(_days[^4]); await DecideOnAsync(Today); Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today)); Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2]), "the one in force that day"); Assert.AreEqual("unknown", await SeenAsync(_days[^5])); Assert.AreEqual("", await SeenAsync(Today.AddDays(ShadowBook.MaxAgeDays + 1)), "too old to say what it holds"); // The same day again keeps the one before; a late decision of the same strategy never takes the place of a newer one. await DecideOnAsync(Today); Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2])); await DecideOnAsync(_days[^3]); Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today)); Assert.AreEqual(BarStore.DayText(_days[^3]), await SeenAsync(_days[^2])); // Without the whole portfolio there is no case, but the book is there for the others. var turn = Turn(StrategyNames.EquityMomentum, Context(_moving), [Entry("AAA", weight: 1m)], ShadowInput.Nothing with { Whole = false }); Assert.IsNotNull(turn.Book); Assert.IsFalse(turn.Cases.Any(c => c.Improvement == Improvements.VolatilityCap)); } [TestMethod] [TestCategory(Category.Unit)] public void TheModelWouldChooseOtherCandidates() { // Four stocks fall for three days above their long average; three places. double Dip(int i, double speed) => i < 257 ? 50 + (i * 0.3) : 50 + (256 * 0.3) - ((i - 256) * speed); var stocks = new[] { ("AAA", 3.0), ("BBB", 2.5), ("CCC", 2.0), ("DDD", 1.5) }.Select(s => Stock(s.Item1, i => Dip(i, s.Item2))).Append(Stock(StrategyNames.MarketSymbol, i => 400 + i)).ToList(); var context = Context(stocks); var candidates = new EquityMeanrev().Candidates(context); Assert.HasCount(4, candidates); var proposed = new EquityMeanrev().Decide(context); Assert.HasCount(3, proposed); var left = candidates.Single(c => proposed.All(p => p.Symbol != c.Symbol)).Symbol; var worst = proposed[0].Symbol; var turn = Turn(StrategyNames.EquityMeanrev, context, proposed, probability: (_, i) => i.Symbol == worst ? 0.3 : i.Symbol == left ? 0.8 : 0.5); var cases = turn.Cases.Where(c => c.Improvement == Improvements.ModelChoice).ToDictionary(c => c.Symbol, c => c); Assert.AreEqual(0.0, cases[worst].Factor); Assert.AreEqual(left, cases[worst].Instead!.Symbol); Assert.AreEqual(2, cases.Values.Count(c => c.Factor == 1 && c.Instead is null)); // Without a probability for each of them there is no comparison. Assert.IsFalse(Turn(StrategyNames.EquityMeanrev, context, proposed, probability: (_, i) => i.Symbol == left ? null : 0.5).Cases.Any(c => c.Improvement == Improvements.ModelChoice)); } [TestMethod] [TestCategory(Category.Unit)] public void TheEffectCountsTheMonthsNotTheSignals() { Assert.IsNull(ShadowDesk.Summary(null, []).Mean); Assert.IsNull(ShadowDesk.Summary(null, [(Monday, 0.01)]).Interval); // Ten equal signals in each of six months: the spread between months is what counts, not the sixty signals. ImprovementLine Months(int months) => ShadowDesk.Summary(null, [.. Enumerable.Range(0, months * 10).Select(i => (Monday.AddMonths(i / 10), (i / 10) % 2 == 0 ? 0.02 : -0.01))]); var many = Months(6); Assert.AreEqual((60, 6), (many.Cases, many.Months)); Assert.AreEqual(0.005, many.Mean!.Value, 1e-9); Assert.AreEqual(Math.Sqrt(6 * 0.15 * 0.15 * 6 / 5) / 60, many.Error!.Value, 1e-9); Assert.IsGreaterThan(3 * 0.015 / Math.Sqrt(59), many.Error.Value, "three times the error of independent signals"); Assert.AreEqual(0.005 + (2.5706 * many.Error.Value), many.Interval!.Value.High, 1e-5, "five degrees of freedom, not the normal"); Assert.IsNull(many.Missing); var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 12, 0.004, 0.001)], "", false, null); Assert.AreEqual("un indizio discreto", view.Trust); Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 12, 0, 0.1)] }).Trust); Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 12, 0, 0.1)] }).Trust); var said = ShadowDesk.Discoveries([view]).Single(); StringAssert.EndsWith(said.Title, "avrebbe aiutato"); StringAssert.Contains(said.Detail, "+0,40%"); Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [new ImprovementLine(null, 9, 12, 0.1, 0.01)] }])); // With fewer months there is a mean and nothing else, however many the signals. foreach (var months in new[] { 1, 2, 5 }) { var few = Months(months); Assert.AreEqual(months * 10, few.Cases); Assert.IsNotNull(few.Mean); Assert.IsNull(few.Error); Assert.IsNull(few.Interval); Assert.AreEqual($"troppo pochi mesi per un intervallo: {months}, ne servono 6", few.Missing); Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [few] }])); Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [few with { Cases = 500 }] }).Trust); } Assert.IsNull(ShadowDesk.Summary(null, []).Missing); } [TestMethod] [TestCategory(Category.Unit)] public void TheQuantilesOfStudentMatchTheTables() { foreach (var (freedom, expected) in new[] { (5, 2.5706), (6, 2.4469), (7, 2.3646), (10, 2.2281), (11, 2.2010), (23, 2.0687), (30, 2.0423), (60, 2.0003), (120, 1.9799) }) { Assert.AreEqual(expected, StudentT.Quantile(0.975, freedom), 0.0005); Assert.AreEqual(-expected, StudentT.Quantile(0.025, freedom), 0.0005); } Assert.AreEqual(Normal.Quantile(0.975), StudentT.Quantile(0.975, 1_000_000), 1e-5); } /// The same decisions with and without the shadow, also when it cannot be written; then its measure. [TestMethod] [TestCategory(Category.Integration)] public async Task TheShadowChangesNoDecisionAndIsMeasuredOnce() { var from = new DateOnly(2026, 6, 1); var last = from.AddDays(21); var fills = new List(); foreach (var mode in new[] { "without", "with", "broken" }) { await using var rig = await StockRig.CreateAsync(from, last); var desk = new LearningDesk(rig.Rig.Db, rig.Rig.Clock) { First = null }; if (mode != "without") { rig.UseLearning(desk); } if (mode == "broken") { await rig.Rig.Db.WriteAsync(s => s.ExecuteAsync("DROP TABLE shadow_cases", _none), _none); } for (var day = from; day <= last; day = day.AddDays(1)) { await rig.SessionAsync(day); } fills.Add(string.Join("; ", await rig.Rig.Db.ReadAsync(s => s.QueryAsync("SELECT i.symbol, f.quantity, f.price FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, f.id", r => $"{r.Text("symbol")} {r.Money("quantity")} {r.Money("price")}"), _none))); if (mode == "broken") { Assert.IsGreaterThan(0L, await desk.Store.CountAsync(CaseSources.Live, _none), "the examples are saved all the same"); } else if (mode == "with") { await MeasureAsync(rig, desk); } } Assert.IsGreaterThan(50, fills[0].Length); Assert.AreEqual(fills[0], fills[1]); Assert.AreEqual(fills[0], fills[2]); } private static async Task MeasureAsync(StockRig rig, LearningDesk desk) { var db = rig.Rig.Db; var before = await desk.Shadow.LoadAsync(true, true, false, _none); var time = before.Single(v => v.Improvement.Key == Improvements.EntryTime); Assert.AreEqual((int)await desk.Store.CountAsync(CaseSources.Live, _none), time.Examined, "every signal is examined"); Assert.AreEqual(time.Examined, before.Single(v => v.Improvement.Key == Improvements.MarketFilter).Examined); Assert.IsGreaterThan(0, time.Examined); Assert.AreEqual("In attesa di un modello per la mean reversion", before.Single(v => v.Improvement.Key == Improvements.ModelChoice).State); // As if the filter had stopped them all. Then the outcomes of the night and the measure, with prices that rise 1% by // a quarter past and 2% by half past. await db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET factor = 0, effect = NULL, measured_at = NULL WHERE improvement = @i", _none, ("i", Improvements.MarketFilter)), _none); await new LearningCycle(db, rig.Rig.Clock, desk, rig.Engine.LabelDataAsync).LabelAsync(_none); Task> Minutes(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken ct) => Task.FromResult>( [.. Enumerable.Range(0, 35).Select(m => new Bar(start.AddMinutes(m), m < 15 ? 100 : m < 30 ? 101 : 102, 103, 99, 100, 10))]); Assert.IsGreaterThan(0, await desk.Shadow.MeasureAsync(rig.Engine.LabelDataAsync, new WeekdayCalendar(), Minutes, _none)); Assert.AreEqual(0, await desk.Shadow.MeasureAsync(rig.Engine.LabelDataAsync, new WeekdayCalendar(), Minutes, _none), "once and for all"); var after = await desk.Shadow.LoadAsync(true, true, false, _none); time = after.Single(v => v.Improvement.Key == Improvements.EntryTime); Assert.AreEqual((100.0 / 101) - 1, time.Lines[0].Mean!.Value, 1e-6); Assert.AreEqual((100.0 / 102) - 1, time.Lines[1].Mean!.Value, 1e-6); StringAssert.Contains(time.Note, "0,00% dopo 5 minuti, +1,00% dopo 15, +2,00% dopo 30"); var labelled = (await desk.Store.LiveAsync(StrategyNames.EquityMeanrev, _none)).Where(e => e.Label?.Result is not null).ToList(); var filter = after.Single(v => v.Improvement.Key == Improvements.MarketFilter).Lines.Single(); Assert.AreEqual(labelled.Count, filter.Cases); Assert.AreEqual(-labelled.Average(e => e.Label!.Result!.Value), filter.Mean!.Value, 1e-6, "not entering gives up the result"); } [TestMethod] [TestCategory(Category.Integration)] public async Task TheSecIsAskedOnlyWithTheContactOfTheUser() { await using var rig = await TradingRig.CreateAsync(); var http = new FakeHttp() .On("company_tickers.json", """{"0":{"cik_str":320193,"ticker":"AAPL","title":"Apple Inc."},"1":{"cik_str":1067983,"ticker":"BRK-B","title":"Berkshire"}}""") .On("CIK0000320193.json", """{"sic":"3571","sicDescription":"Electronic Computers"}""") .On("CIK0001067983.json", """{"sic":"","sicDescription":""}"""); var bus = new EventBus(); var secrets = new SecretStore(rig.Db, rig.Clock, new byte[32]); using var market = new MarketDataService(rig.Db, rig.Clock, bus, new SettingsStore(rig.Db, rig.Clock, bus), secrets, null, http); await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none); Assert.IsEmpty(http.Requests, "no contact, no request"); Assert.IsFalse((await new SourceStateStore(rig.Db, rig.Clock).ListAsync(_none)).Single(s => s.Source == Edgar.Source).Enabled); await secrets.SetAsync(Edgar.ContactSecret, "prova@esempio.it", "test"); await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none); Assert.HasCount(3, http.Requests); foreach (var request in http.Requests) { StringAssert.EndsWith(request.RequestUri!.Host, ".sec.gov"); Assert.AreEqual($"Anubis/{AnubisInfo.Version} prova@esempio.it", string.Join(' ', request.Headers.NonValidated["User-Agent"])); } var groups = await new CompanySectors(rig.Db, rig.Clock).GroupsAsync(_none); Assert.AreEqual("35", groups.Single().Value, "a company without a code has no sector"); await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none); Assert.HasCount(3, http.Requests, "known for three months"); Assert.IsNull(Edgar.UserAgent("due parole")); Assert.IsNull(Edgar.UserAgent("a\r\nX-Altro:b")); } [TestMethod] [TestCategory(Category.Integration)] public async Task TheLaboratoryShowsTheImprovementsAndWhatTheyWaitFor() { var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", System.Net.HttpStatusCode.NotFound)); await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); await server.SignInFirstTimeAsync(); var page = System.Net.WebUtility.HtmlDecode(await server.TextAsync("/laboratorio")); foreach (var improvement in Improvements.All) { StringAssert.Contains(page, improvement.Name); } StringAssert.Contains(page, "In attesa delle chiavi Alpaca"); StringAssert.Contains(page, "In osservazione"); StringAssert.Contains(await server.TextAsync("/impostazioni"), "Contatto per la SEC"); } }