One example for the first entry intent of a strategy, executed or not and also in observation, saved in the transaction of the decision with the clues known at that moment. The label is the operation simulated alone at full size, net of costs, so it does not depend on what the bot did with the signal (ADR 0018). refs #62 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
275 lines
16 KiB
C#
275 lines
16 KiB
C#
using Anubis.Backtest;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Learning;
|
|
using Anubis.Strategies;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>The archive of the examples and their labels (SPEC 11.2, issue #62).</summary>
|
|
[TestClass]
|
|
public sealed class LearningCasesTests
|
|
{
|
|
private static readonly DateOnly First = new(2023, 1, 1);
|
|
|
|
internal static BacktestDataset Coins(int days = 900, int coins = 3)
|
|
{
|
|
var names = new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR", "ADA-EUR", "XRP-EUR" };
|
|
return new BacktestDataset(Enumerable.Range(0, coins).Select(i =>
|
|
new BacktestInstrument(MarketDataStoreTests.Okx(names[i]) with { ListedAt = null }, LiveRig.Synthetic(First, days, 100 * (i + 1), (uint)(7 + i)))), "EUR");
|
|
}
|
|
|
|
internal static IReadOnlyList<Example> History(BacktestDataset data) =>
|
|
HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data,
|
|
StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = First.AddDays(420) }));
|
|
|
|
/// <summary>Criterion of the phase: no clue changes when data after the decision is added.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void NoClueUsesDataAfterTheDecision()
|
|
{
|
|
var data = Coins();
|
|
var full = History(data);
|
|
Assert.IsGreaterThan(20, full.Count);
|
|
foreach (var cut in new[] { 500, 600, 700, 800, 890 }.Select(d => First.AddDays(d)))
|
|
{
|
|
var known = History(data.Through(cut));
|
|
var before = full.Where(e => e.Day <= cut).ToList();
|
|
Assert.HasCount(before.Count, known, $"cut {cut}");
|
|
foreach (var (a, b) in before.Zip(known))
|
|
{
|
|
Assert.AreEqual((a.Symbol, a.Day, a.Weight, a.Stop), (b.Symbol, b.Day, b.Weight, b.Stop));
|
|
Assert.AreEqual(Text(a), Text(b), $"{a.Symbol} {a.Day}");
|
|
|
|
// The outcome is known only once the operation is closed, and then it is the final one.
|
|
Assert.AreEqual(a.Label is { ClosedDay: { } closed } && closed <= cut ? a.Label : null, b.Label);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static string Text(Example e) => string.Join(';', e.Features.Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
|
|
|
|
/// <summary>The same for what comes from outside the bars: only values already dated, saved and read.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task NothingSavedOrDatedAfterTheDecisionIsRead()
|
|
{
|
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
|
var none = CancellationToken.None;
|
|
var at = rig.Clock.UtcNow;
|
|
var mood = new MoodStore(rig.Db, rig.Clock);
|
|
var reader = new OutsideReader(rig.Db, rig.Clock);
|
|
var specs = new Dictionary<string, InstrumentSpec> { ["BTC-EUR"] = TradingRig.Btc };
|
|
await mood.UpsertAsync([new(MoodIndicators.FearGreed, at.AddHours(-20), 30, null, "t"), new(MoodIndicators.Vix, at.AddDays(-1), 18, null, "t"),
|
|
new(MoodIndicators.BtcFunding, at.AddHours(-3), 0.0001, null, "t"), .. Enumerable.Range(1, 10).Select(i => new MoodReading(MoodIndicators.BtcOpenInterest, at.AddDays(-i), 100, null, "t")),
|
|
new(MoodIndicators.FearGreed, at.AddHours(1), 99, null, "t")], none).ConfigureAwait(false);
|
|
await StoryAsync(rig, "Nota prima", at.AddHours(-5), at.AddHours(-4), 0.5).ConfigureAwait(false);
|
|
var before = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false);
|
|
Assert.AreEqual(30d, before.FearGreed);
|
|
Assert.AreEqual(18d, before.Vix);
|
|
Assert.AreEqual(1d, before.BtcOpenInterest);
|
|
Assert.AreEqual(1, before.Stories3Days["BTC-EUR"]);
|
|
Assert.AreEqual(0.5, before.News["BTC-EUR"].Tone1Day);
|
|
|
|
// Later: values dated before the decision but saved after it (published late), and a story published before and
|
|
// read after. The past must look the same.
|
|
rig.Clock.Advance(TimeSpan.FromHours(6));
|
|
await mood.UpsertAsync([new(MoodIndicators.Vix, at.AddHours(-2), 44, null, "t"), new(MoodIndicators.FearGreed, at.AddHours(-1), 5, null, "t"),
|
|
new(MoodIndicators.BtcFunding, at.AddMinutes(-1), 0.9, null, "t"), new(MoodIndicators.BtcOpenInterest, at.AddMinutes(-1), 900, null, "t")], none).ConfigureAwait(false);
|
|
await StoryAsync(rig, "Letta dopo", at.AddHours(-1), at.AddHours(2), -0.9).ConfigureAwait(false);
|
|
var again = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false);
|
|
Assert.AreEqual((before.FearGreed, before.Vix, before.BtcFunding, before.BtcOpenInterest), (again.FearGreed, again.Vix, again.BtcFunding, again.BtcOpenInterest));
|
|
Assert.AreEqual(before.Stories3Days["BTC-EUR"], again.Stories3Days["BTC-EUR"]);
|
|
Assert.AreEqual(before.News["BTC-EUR"].Tone3Days, again.News["BTC-EUR"].Tone3Days);
|
|
|
|
// A value too old is no value: the source stopped.
|
|
rig.Clock.Advance(TimeSpan.FromDays(40));
|
|
var late = await reader.ReadAsync(rig.Clock.UtcNow, specs, null, none).ConfigureAwait(false);
|
|
Assert.IsNull(late.FearGreed);
|
|
Assert.IsNull(late.Vix);
|
|
Assert.IsNull(late.BtcOpenInterest);
|
|
}
|
|
|
|
private static async Task StoryAsync(TradingRig rig, string title, DateTimeOffset published, DateTimeOffset seen, double score)
|
|
{
|
|
var id = Ids.NewId(rig.Clock);
|
|
await rig.Db.WriteAsync(async s =>
|
|
{
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " +
|
|
"VALUES (@id, @t, @t, @p, @f, @f, 1, @yes, @s, 1, @f, @f)", ("id", id), ("t", title), ("p", published), ("f", seen), ("yes", true), ("s", score)).ConfigureAwait(false);
|
|
await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', 'okx:BTC-EUR', 'name', @f)",
|
|
("id", Ids.NewId(rig.Clock)), ("st", id), ("f", seen)).ConfigureAwait(false);
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Enters while not held, on a fixed day leaves; every day proposes again what it does not hold.</summary>
|
|
private sealed class Stubborn(DateOnly from, DateOnly exit, decimal weight = 0.3m, decimal? stop = null) : 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)
|
|
{
|
|
if (context.Day < from)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
if (context.Portfolio.Holds("BTC-EUR"))
|
|
{
|
|
return context.Day == exit ? [new Intent("BTC-EUR", 0m, "trend_exit")] : [new Intent("BTC-EUR", weight * 2, "trend_increase")];
|
|
}
|
|
|
|
return [new Intent("BTC-EUR", weight, "trend_entry") { Strength = 0.5, Stop = stop }];
|
|
}
|
|
}
|
|
|
|
private sealed class RefuseAll : IIntentStage
|
|
{
|
|
public string Name => "refuse";
|
|
|
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => [.. intents.Where(i => i.TargetWeight is 0m)];
|
|
}
|
|
|
|
private sealed class HalveAll : IIntentStage
|
|
{
|
|
public string Name => "halve";
|
|
|
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => [.. intents.Select(i => i with { TargetWeight = i.TargetWeight / 2 })];
|
|
}
|
|
|
|
/// <summary>One example for the first entry, even refused: proposals repeated and increases make none until it closes.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void OneExampleForEachFirstEntryEvenWhenNothingIsBought()
|
|
{
|
|
var data = Coins(400, 1);
|
|
var (from, exit) = (First.AddDays(100), First.AddDays(130));
|
|
IReadOnlyList<Example> Build(params IIntentStage[] stages) =>
|
|
HistoryCases.Build(StrategyNames.CryptoTrend, () => new Stubborn(from, exit), data, new BacktestOptions { To = First.AddDays(140), Correctives = stages });
|
|
|
|
var executed = Build();
|
|
var refused = Build(new RefuseAll());
|
|
var halved = Build(new HalveAll());
|
|
Assert.AreEqual(from, executed[0].Day);
|
|
Assert.AreEqual(exit.AddDays(1), executed[0].Label!.ClosedDay, "sold at the open after the exit");
|
|
|
|
// After the exit the strategy enters again: a second example, still open at the end.
|
|
Assert.HasCount(2, executed);
|
|
Assert.IsNull(executed[1].Label);
|
|
foreach (var other in new[] { refused, halved })
|
|
{
|
|
// The same examples and the same label whatever the bot did with the signal.
|
|
Assert.HasCount(2, other);
|
|
Assert.AreEqual((executed[0].Day, executed[0].Weight), (other[0].Day, other[0].Weight));
|
|
Assert.AreEqual(executed[0].Label, other[0].Label);
|
|
}
|
|
|
|
Assert.AreEqual(0.5, executed[0].Features[Clues.Strength]);
|
|
Assert.AreEqual(1d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.CryptoTrend]);
|
|
Assert.AreEqual(0d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.EquityMeanrev]);
|
|
}
|
|
|
|
/// <summary>The label: the result of the operation alone, net of every cost, with the exits and the stop of its strategy.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheLabelIsTheOperationAloneNetOfCosts()
|
|
{
|
|
var spec = MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null };
|
|
DailyBar Bar(int i, double open, double low, double close) => new(First.AddDays(i), open, Math.Max(open, close), low, close, 1e6);
|
|
var bars = new List<DailyBar> { Bar(0, 100, 99, 100), Bar(1, 100, 99, 100), Bar(2, 100, 99, 100), Bar(3, 100.4, 99, 100.4), Bar(4, 100.4, 99, 100.4), Bar(5, 100, 80, 85), Bar(6, 85, 84, 85) };
|
|
var data = new BacktestDataset([new BacktestInstrument(spec, bars)], "EUR");
|
|
var example = new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.History, First.AddDays(1), default, "trend_entry", 0.2m, null, null, new Dictionary<string, double>());
|
|
|
|
// Bought at the open of day 2, sold at the open of day 4: +0.4% gross, a loss once fees and slippage are paid.
|
|
var label = CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6))!;
|
|
Assert.AreEqual((First.AddDays(2), First.AddDays(4), "trend_exit"), (label.OpenedDay, label.ClosedDay, label.ExitReason));
|
|
Assert.IsFalse(label.Win);
|
|
Assert.IsLessThan(0d, label.Result!.Value);
|
|
Assert.IsTrue(CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6), new CostModel(0m))!.Win);
|
|
|
|
// The stop of the intent closes it on day 5, and before that day the label is not known.
|
|
var stopped = example with { Stop = 90m };
|
|
var never = () => (IStrategy)new Stubborn(First.AddDays(1), DateOnly.MaxValue);
|
|
Assert.AreEqual(First.AddDays(5), CaseLabels.Of(stopped, never, data, First.AddDays(6))!.ClosedDay);
|
|
Assert.IsNull(CaseLabels.Of(stopped, never, data, First.AddDays(4)));
|
|
Assert.IsNull(CaseLabels.Of(example, never, data, First.AddDays(6)), "an operation still open has no label");
|
|
|
|
// One that can never start (below the minimum of the market) has no outcome and never trains.
|
|
var tooBig = new BacktestDataset([new BacktestInstrument(spec with { MinSize = 1_000_000m }, bars)], "EUR");
|
|
var empty = CaseLabels.Of(example, never, tooBig, First.AddDays(6))!;
|
|
Assert.IsNull(empty.Win);
|
|
Assert.IsFalse((example with { Label = empty }).IsLabelled);
|
|
Assert.IsTrue((example with { Label = label }).IsLabelled);
|
|
}
|
|
|
|
/// <summary>Saved and read back the same on both engines; a label is written once.</summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheArchiveReadsBackTheSame()
|
|
{
|
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
|
var none = CancellationToken.None;
|
|
var store = new LearningStore(rig.Db, rig.Clock);
|
|
var example = new Example(Guid.Empty, StrategyNames.EquityMeanrev, "AAPL", CaseSources.Live, First, rig.Clock.UtcNow, "meanrev_entry", 0.123456m, null, 4.25m,
|
|
new Dictionary<string, double> { [Clues.Strength] = 0.1 + 0.2, [Clues.Breadth] = 1 })
|
|
{ Stage = StrategyStages.Observation, DecisionId = Ids.NewId(rig.Clock), Multiplier = 0.4 };
|
|
var id = await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false);
|
|
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false);
|
|
var read = (await store.AllAsync(none).ConfigureAwait(false)).Single();
|
|
Assert.AreEqual((id, example.Symbol, example.Weight, example.Stop, example.StopOffset, example.Stage, example.DecisionId, example.Multiplier),
|
|
(read.Id, read.Symbol, read.Weight, read.Stop, read.StopOffset, read.Stage, read.DecisionId, read.Multiplier));
|
|
CollectionAssert.AreEqual(example.Features.ToList(), read.Features.OrderBy(f => f.Key, StringComparer.Ordinal).Reverse().ToList());
|
|
Assert.HasCount(1, await store.OpenAsync(none).ConfigureAwait(false));
|
|
|
|
var label = new CaseLabel(true, 0.0123, First.AddDays(1), First.AddDays(4), "meanrev_exit_rsi");
|
|
await store.AddLabelAsync(id, label, none).ConfigureAwait(false);
|
|
await store.AddLabelAsync(id, label with { Win = false }, none).ConfigureAwait(false);
|
|
Assert.AreEqual(label, (await store.AllAsync(none).ConfigureAwait(false)).Single().Label);
|
|
Assert.HasCount(0, await store.OpenAsync(none).ConfigureAwait(false));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Live: the examples are those of the history on the same days, with the same clues, both for a strategy that trades
|
|
/// and for one in observation; a restart in the middle adds none.
|
|
/// </summary>
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
[DataRow(StrategyStages.Simulation)]
|
|
[DataRow(StrategyStages.Observation)]
|
|
public async Task TheLiveEngineSavesTheSameExamplesAsTheHistory(string stage)
|
|
{
|
|
var from = new DateOnly(2026, 6, 1);
|
|
var last = from.AddDays(40);
|
|
await using var rig = await LiveRig.CreateAsync(from, last, stage: stage).ConfigureAwait(false);
|
|
for (var day = from; day <= last; day = day.AddDays(1))
|
|
{
|
|
await rig.DayAsync(day, morning: 6).ConfigureAwait(false);
|
|
if (day == from.AddDays(17))
|
|
{
|
|
await rig.RestartAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR");
|
|
var expected = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data,
|
|
StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = from.AddDays(-1) }));
|
|
var live = await new LearningStore(rig.Rig.Db, rig.Rig.Clock).AllAsync(CancellationToken.None).ConfigureAwait(false);
|
|
Assert.IsGreaterThan(1, expected.Count);
|
|
Assert.AreEqual(string.Join(", ", expected.Select(e => $"{e.Symbol} {e.Day:MM-dd}")), string.Join(", ", live.Select(e => $"{e.Symbol} {e.Day:MM-dd}")));
|
|
foreach (var (a, b) in expected.Zip(live))
|
|
{
|
|
Assert.AreEqual(stage, b.Stage);
|
|
Assert.AreEqual(Text(a), string.Join(';', b.Features.Where(f => a.Features.ContainsKey(f.Key)).OrderBy(f => f.Key, StringComparer.Ordinal)
|
|
.Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture))));
|
|
}
|
|
}
|
|
}
|