Files
Anubis/tests/Anubis.Tests/ShadowTests.cs
T
Alby96andClaude Opus 5.5 79bb194de0 Compute the improvements of 8.7 in shadow on the examples
Each improvement is measured on the signals the bot already collects, in its own
savepoint after the decision, so no order depends on it: the correlation filter,
the volatility cap, the sector cap, the market filter, the entry time and the
choice of the model. The laboratory shows how many cases each one has and how far
to trust it. Sectors come from the SEC only with a contact given by the user.

refs #74

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:31:15 +01:00

280 lines
16 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>The improvements in observation of SPEC 8.7 (issue #74): computed, measured, shown, and never acting.</summary>
[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<DateOnly> _days = StrategyData.BusinessDays(Monday, 260);
private static DateOnly Today => _days[^1];
private static BacktestInstrument Stock(string symbol, Func<int, double> 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<BacktestInstrument> stocks, IReadOnlyDictionary<string, Holding>? 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<string, Holding>()), 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<Intent> intents, ShadowInput? input = null, Func<StrategyContext, Intent, double?>? probability = null)
{
var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day);
var turn = new ShadowTurn(strategy, 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<string, Holding> { ["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, 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<string, string>()));
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);
}
[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 two months: the spread between months is what counts.
var many = ShadowDesk.Summary(null, [.. Enumerable.Range(0, 20).Select(i => (Monday.AddDays(i < 10 ? 0 : 40), i < 10 ? 0.02 : -0.01))]);
Assert.AreEqual(0.005, many.Mean!.Value, 1e-9);
Assert.IsGreaterThan(0.01, many.Error!.Value);
var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 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, 0, 0.1)] }).Trust);
Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 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, 0.1, 0.01)] }]));
}
/// <summary>The same decisions with and without the shadow, also when it cannot be written; then its measure.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheShadowChangesNoDecisionAndIsMeasuredOnce()
{
var from = new DateOnly(2026, 6, 1);
var last = from.AddDays(21);
var fills = new List<string>();
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<IReadOnlyList<Bar>> Minutes(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken ct) => Task.FromResult<IReadOnlyList<Bar>>(
[.. 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");
}
}