Review the base strategies every three months

Every quarter the base strategies are tried again on the longer history with
the slippage in force, compared with how they did live, and the report is
published in the laboratory with the base rates measured again and the balance
of the restrictions of 10.5. In observation the outcome replaces the old one and
a strategy that passed goes to simulation after its 90 days; with capital
nothing moves but the demotion condition of 12.3. A restart halfway goes on and
the review concludes once; the outcome of a review survives a restart with an
older build.

refs #74

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 20:59:20 +01:00
1 parent 79bb194de0
commit 2257c3e16c
34 files changed
+2308 -87

No files matched your search

+655
View File
@@ -0,0 +1,655 @@
using System.Text.Json;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.News;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The quarterly review of SPEC 12.2 and the balance of the restrictions of 10.5 (issue #74).</summary>
[TestClass]
public sealed class QuarterlyReviewTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateOnly Through = new(2026, 12, 31);
private const string Crypto = StrategyNames.CryptoTrend;
private static DateTimeOffset At(int year, int month, int day) => new(year, month, day, 2, 10, 0, TimeSpan.Zero);
// ---- The rig ----------------------------------------------------------------------------------------------------
private static async Task WriteHistoryAsync(string folder)
{
var store = new ResearchStore(folder);
var seed = 21u;
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" })
{
var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
(decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList();
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false);
}
}
// A report of the protocol on those coins, whose verdict each test chooses.
private static readonly Lazy<Task<BacktestReport>> _report = new(async () =>
{
var folder = TempFolder.Create("review-report");
try
{
await WriteHistoryAsync(folder).ConfigureAwait(false);
var (plan, _) = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
CryptoTrendProtocol.Capital, null), At(2027, 1, 5));
var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false);
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5)).Report;
}
finally
{
TempFolder.Delete(folder);
}
});
private sealed class ReviewRig : IAsyncDisposable
{
public required LiveRig Live { get; init; }
public required string Folder { get; init; }
public required Laboratory Lab { get; set; }
public required QuarterlyReview Review { get; set; }
public string? Missing { get; set; }
public List<DateOnly> Prepared { get; } = [];
public Database Db => Live.Rig.Db;
public ManualClock Clock => Live.Rig.Clock;
public static async Task<ReviewRig> CreateAsync(string stage = StrategyStages.Observation, DateOnly? since = null, Qualification? qualification = null, bool history = true)
{
var from = since ?? new DateOnly(2026, 9, 1);
var live = await LiveRig.CreateAsync(from, from.AddDays(5), stage: stage).ConfigureAwait(false);
live.UseFirst(Rates(new DateOnly(2026, 10, 31)));
var folder = TempFolder.Create("review");
if (history)
{
await WriteHistoryAsync(folder).ConfigureAwait(false);
}
await live.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(qualification ?? Old(false), Qualification.Json)))), _none)
.ConfigureAwait(false);
var rig = new ReviewRig { Live = live, Folder = folder, Lab = null!, Review = null! };
rig.Start();
return rig;
}
/// <summary>A new process on the same database.</summary>
public void Start()
{
Lab?.Dispose();
Lab = new Laboratory(Db, Clock, Folder);
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
{
Prepared.Add(to);
return Task.FromResult(Missing);
});
Lab.ReviewTrialEnded = Review.ConcludeAsync;
}
public async Task NightAsync(DateTimeOffset at)
{
Clock.Set(at);
await Review.RunIfDueAsync(_none).ConfigureAwait(false);
}
/// <summary>The baseline in December, then the review of January.</summary>
public async Task<Review> OpenAsync()
{
await NightAsync(At(2026, 12, 10)).ConfigureAwait(false);
await NightAsync(At(2027, 1, 5)).ConfigureAwait(false);
return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single();
}
/// <summary>The whole review, its trials ended with the given verdict.</summary>
public async Task<Review> ReviewAsync(bool passed, Func<BacktestReport, BacktestReport>? change = null)
{
var review = await OpenAsync().ConfigureAwait(false);
await EndAsync(review, passed, change).ConfigureAwait(false);
await Review.ConcludeAsync(_none).ConfigureAwait(false);
return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single(r => r.Id == review.Id);
}
public async Task EndAsync(Review review, bool passed, Func<BacktestReport, BacktestReport>? change = null)
{
var report = await _report.Value.ConfigureAwait(false);
report = report with
{
Passed = passed,
Checks = [.. report.Checks.Select((c, i) => c with { Passed = passed || i > 0, Value = c.Value ?? 0 })],
};
report = change?.Invoke(report) ?? report;
foreach (var trial in await Lab.Trials.OfReviewAsync(review.Id, _none).ConfigureAwait(false))
{
Assert.IsTrue(await Lab.Trials.StartAsync(trial.Id, _none).ConfigureAwait(false));
var summary = new TrialSummary("EUR", report.Chosen, 1m, 0.1, 1, 0.1, 10, 0.95, 0.1, [.. report.Variants.Select(v => v.Sharpe)]);
await Lab.Trials.FinishAsync(trial.Id, "x", summary, (report with { TrialId = trial.Id }).ToJson(), passed, _none).ConfigureAwait(false);
}
}
public async Task<StrategyStage> StageAsync() => (await Live.Stages.GetAsync(Crypto, _none).ConfigureAwait(false))!;
public Task<int> CountAsync(string sql) => Db.ReadAsync(async s => (int)await s.CountAsync(sql).ConfigureAwait(false), _none);
public async ValueTask DisposeAsync()
{
Lab.Dispose();
await Live.DisposeAsync().ConfigureAwait(false);
TempFolder.Delete(Folder);
}
}
private static Qualification Old(bool passed) => new()
{
Passed = passed,
Verdict = passed ? "superato" : "non superato",
Report = CryptoTrendProtocol.ReportPath,
Parameters = "coin_vol=10;max_stop=20",
MaxDrawdown = 0.2m,
ExpectedSlippageBp = 7m,
Through = new DateOnly(2026, 10, 31),
StrategyVersion = "1",
};
private static FirstModelFile Rates(DateOnly through, double rate = 0.4) => new() { BaseRates = new Dictionary<string, double> { [Crypto] = rate }, Through = through };
// ---- When -------------------------------------------------------------------------------------------------------
[TestMethod]
[TestCategory(Category.Unit)]
public void AReviewIsDueOnceAQuarterFromTheFifthDay()
{
Assert.AreEqual("2026-Q4", QuarterlyReview.QuarterOf(new DateOnly(2026, 12, 31)));
Assert.AreEqual("2027-Q1", QuarterlyReview.QuarterOf(new DateOnly(2027, 1, 1)));
Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 20), null), "the first quarter is only noted");
Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 4), "2026-Q4"));
Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2026-Q4"));
Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 3, 31), "2026-Q4"));
Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2027-Q1"));
Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 8, 1), "2026-Q4"), "several quarters missed");
Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), "2026-Q4"));
Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), null));
Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2027, 2, 1), "2026-Q4"), "already due");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ItWaitsForTheArchiveUntilTheFifteenthThenPublishesWithoutIt()
{
await using var rig = await ReviewRig.CreateAsync(history: false);
rig.Missing = "gli archivi di Binance non si scaricano";
await rig.NightAsync(At(2027, 1, 20));
Assert.IsEmpty(rig.Prepared, "the first night only notes the quarter");
await rig.NightAsync(At(2027, 4, 4));
Assert.IsEmpty(rig.Prepared);
await rig.NightAsync(At(2027, 4, 5));
await rig.NightAsync(At(2027, 4, 15));
CollectionAssert.AreEqual(new[] { new DateOnly(2027, 3, 31), new DateOnly(2027, 3, 31) }, rig.Prepared);
var waiting = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
Assert.AreEqual(ReviewStatuses.Preparing, waiting.Status);
Assert.AreEqual(0, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
await rig.NightAsync(At(2027, 4, 16));
var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
Assert.AreEqual((waiting.Id, ReviewStatuses.Done, "2027-Q2"), (done.Id, done.Status, done.Quarter));
var line = done.Report!.Strategies.Single();
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (line.Verdict, line.Action));
Assert.Contains("dati mancanti: gli archivi di Binance non si scaricano", line.Text);
Assert.IsNull(done.Report.RatesAfter);
Assert.IsEmpty(await rig.Lab.Trials.ListAsync(10, _none));
Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict, "the outcome before stays");
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none));
// The same quarter never twice; three quarters off make one review.
await rig.NightAsync(At(2027, 4, 20));
Assert.HasCount(4, rig.Prepared.Append(default).ToList());
rig.Missing = "mancano i cambi della BCE";
await rig.NightAsync(At(2028, 2, 20));
await rig.NightAsync(At(2028, 2, 21));
var all = await QuarterlyReview.ListAsync(rig.Db, _none);
CollectionAssert.AreEqual(new[] { "2028-Q1", "2027-Q2" }, all.Select(r => r.Quarter).ToList());
Assert.AreEqual(new DateOnly(2028, 1, 31), all[0].Through);
Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
}
// ---- The run ----------------------------------------------------------------------------------------------------
/// <summary>The real trials, with a restart in the middle: each trial counts once, the review concludes once.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ARestartHalfwayGoesOnAndTheReviewConcludesOnce()
{
await using var rig = await ReviewRig.CreateAsync();
await rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, @tier, @st, 5, 12, 12, 10, 14, 40, @t, @t)", _none,
("id", Ids.NewId(rig.Clock)), ("tier", SlippageTiers.All[0]), ("st", CostStatuses.Applied), ("t", rig.Clock.UtcNow)), _none);
var review = await rig.OpenAsync();
Assert.AreEqual(ReviewStatuses.Running, review.Status);
Assert.AreEqual(Through, review.Through);
var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none);
Assert.HasCount(2, trials);
Assert.HasCount(4, trials[0].Plan.Data.Symbols);
CollectionAssert.AreEqual(CryptoTrendProtocol.Narrow.ToList(), trials[1].Plan.Data.Symbols.ToList());
Assert.IsTrue(trials.All(t => t is { Status: TrialStatuses.Planned, Plan.Priors: ReviewPriors.All, Plan.Slippage: not null } && t.Plan.Slippage.Of(SlippageTiers.All[0]) == 12m && t.Plan.Data.From == CryptoTrendProtocol.From));
// The same night again plans nothing more.
await rig.NightAsync(At(2027, 1, 6));
Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none));
// The process dies with the first trial done and the second running.
await rig.Lab.ProcessAsync(trials[0].Id, _none);
Assert.AreEqual(TrialStatuses.Done, (await rig.Lab.Trials.GetAsync(trials[0].Id, _none))!.Status);
Assert.IsTrue(await rig.Lab.Trials.StartAsync(trials[1].Id, _none));
rig.Start();
using var stop = new CancellationTokenSource();
var run = rig.Lab.RunAsync(stop.Token);
Review done;
for (var deadline = DateTime.UtcNow.AddMinutes(4); ; await Task.Delay(100))
{
done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
if (done.Status == ReviewStatuses.Done || DateTime.UtcNow > deadline)
{
break;
}
}
Assert.AreEqual(ReviewStatuses.Done, done.Status);
await Task.WhenAll(rig.Review.ConcludeAsync(_none), rig.Review.ConcludeAsync(_none));
await stop.CancelAsync();
try
{
await run;
}
catch (OperationCanceledException)
{
}
Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none));
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM review_outcomes"));
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review'"));
var reports = new List<BacktestReport>();
foreach (var t in trials)
{
reports.Add(BacktestReport.FromJson((await rig.Lab.Trials.ReportJsonAsync(t.Id, _none))!));
}
var n = reports[0].Variants.Count;
Assert.AreEqual(3 * n, reports[0].TrialsCounted, "in observation: its own and those of the protocol that turned it down");
Assert.AreEqual(4 * n, reports[1].TrialsCounted);
var line = done.Report!.Strategies.Single();
Assert.AreEqual(reports.All(r => r.Passed) ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, line.Verdict);
CollectionAssert.AreEqual(trials.Select(t => t.Id).ToList(), line.Trials.ToList());
Assert.AreEqual(reports[0].Chosen, line.Chosen!.Parameters);
// The outcome of the strategy and the base rates come from the longer history.
var q = (await rig.StageAsync()).Qualification!;
Assert.AreEqual((Through, "/laboratorio/revisione/" + done.Id, reports[0].Chosen), (q.Through, q.Report, q.Parameters));
Assert.AreEqual(reports[0].ExpectedSlippageBp, q.ExpectedSlippageBp);
var rates = await rig.Live.Learning.BaseRatesAsync(_none);
Assert.AreEqual(0.4, done.Report.RatesBefore[Crypto]);
Assert.AreEqual(done.Report.RatesAfter![Crypto], rates[Crypto]);
var history = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList();
Assert.IsNotEmpty(history);
Assert.AreEqual(Trainer.SharesOf(history)[Crypto], rates[Crypto], 1e-12);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ATrialThatFailsLeavesTheOutcomeInForce()
{
await using var rig = await ReviewRig.CreateAsync();
var review = await rig.OpenAsync();
var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none);
await rig.Lab.Trials.FailAsync(trials[0].Id, "guasto", _none);
await rig.Review.ConcludeAsync(_none);
Assert.AreEqual(ReviewStatuses.Running, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status, "one is still to run");
await rig.Lab.Trials.FailAsync(trials[1].Id, "guasto", _none);
await rig.Review.ConcludeAsync(_none);
var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
Assert.AreEqual((ReviewVerdicts.Error, ReviewActions.None), (done.Report!.Strategies.Single().Verdict, done.Report.Strategies.Single().Action));
Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict);
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none));
}
// ---- What it does to a strategy ---------------------------------------------------------------------------------
[TestMethod]
[TestCategory(Category.Integration)]
[DataRow("2026-11-01", false, ReviewActions.TooEarly)]
[DataRow("2026-09-01", false, ReviewActions.Promoted)]
[DataRow("2026-09-01", true, ReviewActions.UserChoice)]
public async Task AStrategyInObservationThatPassesGoesToSimulationAfterNinetyDays(string since, bool byUser, string action)
{
await using var rig = await ReviewRig.CreateAsync(since: DateOnly.Parse(since, System.Globalization.CultureInfo.InvariantCulture));
if (byUser)
{
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, 'simulation', 'observation', 'user · utente', @t)",
_none, ("id", Ids.NewId(rig.Clock)), ("s", Crypto), ("t", rig.Clock.UtcNow)), _none);
}
var review = await rig.ReviewAsync(passed: true);
Assert.AreEqual((ReviewVerdicts.Passed, action), (review.Report!.Strategies.Single().Verdict, review.Report.Strategies.Single().Action));
var stage = await rig.StageAsync();
Assert.AreEqual(action == ReviewActions.Promoted ? StrategyStages.Simulation : StrategyStages.Observation, stage.Stage);
Assert.IsTrue(stage.Qualification!.Passed);
Assert.AreEqual(Through, stage.Qualification.Through);
Assert.AreEqual(action == ReviewActions.Promoted ? 1 : 0, await rig.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE reason LIKE 'quarterly_review%'"));
StringAssert.Contains((await NewsRulesTests.DiaryAsync(rig.Db)).Single(m => m.StartsWith("Revisione trimestrale pronta", StringComparison.Ordinal)),
QuarterlyReview.ActionText(review.Report.Strategies.Single()));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStrategyInObservationThatDoesNotPassStaysWithTheNewVerdict()
{
await using var rig = await ReviewRig.CreateAsync();
var review = await rig.ReviewAsync(passed: false);
Assert.AreEqual(ReviewActions.Stays, review.Report!.Strategies.Single().Action);
var stage = await rig.StageAsync();
Assert.AreEqual(StrategyStages.Observation, stage.Stage);
Assert.StartsWith("Revisione del 1º trimestre 2027: protocollo non superato. Universo ampio:", stage.Qualification!.Verdict);
Assert.IsFalse(stage.Qualification.Verdict.Contains("Resta in osservazione", StringComparison.Ordinal));
// A restart with the older outcome of the program does not bring it back; a newer one, or new rules, do.
await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false), _none);
await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { Through = null, StrategyVersion = null }, _none);
Assert.AreEqual(Through, (await rig.StageAsync()).Qualification!.Through);
await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { StrategyVersion = "2", Verdict = "regole nuove" }, _none);
Assert.AreEqual("regole nuove", (await rig.StageAsync()).Qualification!.Verdict);
Assert.AreEqual(StrategyStages.Observation, (await rig.StageAsync()).Stage, "only the first start moves a strategy by itself");
await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false) with { Through = Through.AddMonths(3), Verdict = "storico più lungo" }, _none);
Assert.AreEqual("storico più lungo", (await rig.StageAsync()).Qualification!.Verdict);
// An outcome written before the reviews still reads.
var old = JsonSerializer.Deserialize<Qualification>("""{"passed":true,"verdict":"x","report":"y"}""", Qualification.Json)!;
Assert.IsNull(old.Through);
Assert.IsFalse(old.Outlives(Old(false)));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStrategyInSimulationKeepsItsFiguresAndCannotAdvanceUntilAReviewPasses()
{
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true));
async Task<Requirement> DemotionAsync() => (await rig.Live.Stages.RequirementsAsync(Crypto, _none)).Single(r => r.Key == "demotion");
Assert.IsTrue((await DemotionAsync()).Met);
var review = await rig.ReviewAsync(passed: false, r => r with { Variants = [.. r.Variants.Select((v, i) => v with { Parameters = i == 0 && !v.Chosen ? "coin_vol=10;max_stop=20" : v.Parameters })] });
var line = review.Report!.Strategies.Single();
Assert.AreEqual((StrategyStages.Simulation, ReviewActions.Held), (line.Stage, line.Action));
Assert.IsTrue((await rig.Lab.Trials.OfReviewAsync(review.Id, _none)).All(t => t.Plan.Priors == ReviewPriors.Review), "already qualified: the same grid measured again");
var stage = await rig.StageAsync();
Assert.AreEqual(StrategyStages.Simulation, stage.Stage);
Assert.AreEqual(JsonSerializer.Serialize(Old(true), Qualification.Json), JsonSerializer.Serialize(stage.Qualification, Qualification.Json));
Assert.Contains("non è stata superata", (await DemotionAsync()).Value);
Assert.IsFalse((await DemotionAsync()).Met);
Assert.IsEmpty(await rig.Live.Stages.CheckDemotionsAsync(_none), "nothing to demote in simulation");
// The next one that waits for data leaves it in force; one that passes clears it.
await NextAsync(rig, ReviewVerdicts.Waiting, new DateOnly(2027, 3, 31));
Assert.IsFalse((await DemotionAsync()).Met);
await NextAsync(rig, ReviewVerdicts.Passed, new DateOnly(2027, 6, 30));
Assert.IsTrue((await DemotionAsync()).Met);
}
internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s =>
{
var id = Ids.NewId(clock);
await s.ExecuteAsync("INSERT INTO quarterly_reviews (id, quarter, through, status, created_at, updated_at) VALUES (@id, @q, @d, 'done', @t, @t)", _none,
("id", id), ("q", "x" + through.ToString("yyyyMM", System.Globalization.CultureInfo.InvariantCulture)), ("d", BarStore.DayText(through)), ("t", clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO review_outcomes (id, review_id, strategy, stage, verdict, action, through, trials, data, created_at) VALUES (@id, @r, @s, 'x', @v, 'none', @d, @j, @o, @t)", _none,
("id", Ids.NewId(clock)), ("r", id), ("s", Crypto), ("v", verdict), ("d", BarStore.DayText(through)), ("j", new DbJson("[]")), ("o", new DbJson("{}")), ("t", clock.UtcNow)).ConfigureAwait(false);
}, _none);
private static Task NextAsync(ReviewRig rig, string verdict, DateOnly through) => NextAsync(rig.Db, rig.Clock, verdict, through);
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheStockStrategiesWaitAndTheCandidatesAreLeftOut()
{
await using var rig = await ReviewRig.CreateAsync();
foreach (var (name, stage) in new[] { (StrategyNames.EquityMomentum, StrategyStages.Observation), (StrategyNames.Candidates[0].Name, StrategyStages.Observation) })
{
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 0, @t)",
_none, ("id", Ids.NewId(rig.Clock)), ("s", name), ("a", rig.Live.Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow)), _none);
}
var review = await rig.ReviewAsync(passed: false);
CollectionAssert.AreEquivalent(new[] { Crypto, StrategyNames.EquityMomentum }, review.Report!.Strategies.Select(l => l.Strategy).ToList());
var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action));
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none));
}
// ---- Base rates -------------------------------------------------------------------------------------------------
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheBaseRatesOfAReviewSurviveARestartAndGiveWayToANewerProgram()
{
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true));
var file = FirstModel.Train(LearningModelTests.Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), _none);
rig.Live.UseFirst(file);
rig.Start();
await rig.Live.Learning.PrepareHistoryAsync(_none);
var champion = await rig.Live.Learning.Models.FindAsync(ModelStatuses.Champion, _none);
await LearningStoreAddLiveAsync(rig);
var review = await rig.ReviewAsync(passed: true);
var rate = review.Report!.RatesAfter![Crypto];
Assert.AreNotEqual(file.BaseRates[Crypto], rate);
var examples = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList();
Assert.IsTrue(examples.All(e => e.Strategy == Crypto && e.Day <= Through));
Assert.IsFalse(examples.Any(e => e.Symbol == "BTCEUR" && e.Day == _liveDay), "the same operation is there as a live one");
// A restart with the same program, or an older one, changes nothing.
foreach (var first in new[] { file, FirstModel.Train(LearningModelTests.Cases(310, x => Odds.Probability(x[1])), new DateOnly(2026, 11, 30), _none) })
{
var desk = new LearningDesk(rig.Db, rig.Clock) { First = first };
await desk.PrepareHistoryAsync(_none);
Assert.AreEqual(rate, (await desk.BaseRatesAsync(_none))[Crypto]);
Assert.AreEqual(examples.Count, await desk.Store.CountAsync(CaseSources.History, _none));
Assert.AreEqual(champion!.Id, (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!.Id, "the model is not replaced");
}
// One built on a longer history wins; a strategy only a review measured keeps its rate.
var newer = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(LearningModelTests.Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), _none) };
await newer.PrepareHistoryAsync(_none);
Assert.AreEqual(newer.First.BaseRates[Crypto], (await newer.BaseRatesAsync(_none))[Crypto]);
Assert.AreEqual(320, await newer.Store.CountAsync(CaseSources.History, _none));
Assert.AreEqual(0.3, LearningDesk.Merge(new Dictionary<string, double> { ["a"] = 0.3, ["b"] = 0.2 }, new Dictionary<string, double> { ["b"] = 0.5 })["a"]);
}
private static DateOnly _liveDay;
// A live example equal to one the history will give.
private static async Task LearningStoreAddLiveAsync(ReviewRig rig)
{
var data = await FirstModel.DataAsync(rig.Folder, Through, _none);
var same = FirstModel.ExamplesOf(data, Old(true).Parameters, Through, null, _none).First(e => e.Symbol == "BTCEUR");
_liveDay = same.Day;
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, same with { Id = Guid.Empty, Symbol = "BTC-EUR", Source = CaseSources.Live, Stage = StrategyStages.Simulation }, _none), _none);
}
// ---- Priors, universe, archives ---------------------------------------------------------------------------------
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AQualifiedStrategyCountsTheSameTriesAtEveryReviewAndOneInObservationMore()
{
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true));
var review = await rig.ReviewAsync(passed: true);
async Task<List<int>> CountsAsync(Guid id)
{
var counts = new List<int>();
foreach (var t in await rig.Lab.Trials.OfReviewAsync(id, _none))
{
// As each one was run: what came later does not exist yet.
counts.Add((await rig.Lab.Trials.PriorOfAsync(t, _none)).Trials);
}
return counts;
}
CollectionAssert.AreEqual(new[] { 1, 1 }, await CountsAsync(review.Id), "the other of the same review, never the past");
await rig.NightAsync(At(2027, 4, 5));
var second = (await QuarterlyReview.ListAsync(rig.Db, _none))[0];
CollectionAssert.AreEqual(new[] { 0, 0 }, await CountsAsync(second.Id));
await rig.EndAsync(second, passed: false);
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none);
await rig.Review.ConcludeAsync(_none);
await rig.NightAsync(At(2027, 7, 5));
var third = (await QuarterlyReview.ListAsync(rig.Db, _none))[0];
CollectionAssert.AreEqual(new[] { 6, 6 }, await CountsAsync(third.Id), "four in the register and two of the protocol");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ASeriesOutsideTheArchivesNeverChangesTheUniverse()
{
var folder = TempFolder.Create("review-universe");
try
{
await WriteHistoryAsync(folder);
var store = new ResearchStore(folder);
var bars = new List<ResearchBar> { new(new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero), 1m, 1m, 1m, 1m, 1m) };
foreach (var other in new[] { "ICP", "APT" })
{
await store.WriteAsync(EuroHistory.Venue, other + "EUR", Timeframes.Day, bars, _none);
await store.WriteAsync(Venues.Binance, other + "USDT", Timeframes.Day, bars, _none);
}
await store.WriteAsync(Venues.Binance, "BTCUSDT", Timeframes.Day, bars, _none);
CollectionAssert.AreEqual(new[] { "BTCEUR", "ETHEUR", "SOLEUR", "XRPEUR" }, (await CryptoTrendProtocol.BroadAsync(store, Through, _none)).Order(StringComparer.Ordinal).ToList());
var rates = new List<FxRate> { new("EUR", "USD", new DateOnly(2026, 11, 30), 1.1m, "ecb") };
CollectionAssert.AreEqual(new[] { "BTCEUR" }, (await EuroHistory.ConvertAllAsync(store, rates, _none, CryptoTrendProtocol.Archives)).ToList());
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheReportOfABaseStrategyKeepsItsExpectedPathAndSlippage()
{
var report = await _report.Value;
Assert.IsTrue(report.ExpectedSlippageBp > 0m);
Assert.HasCount(CryptoTrendProtocol.PathDays, report.ExpectedPathP5!);
var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan;
Assert.IsFalse(plan.ToJson().Contains("priors", StringComparison.OrdinalIgnoreCase), "a plan that is not of a review keeps its text, and its hash");
Assert.AreNotEqual(TrialPlan.Hash(plan.ToJson()), TrialPlan.Hash((plan with { Priors = ReviewPriors.All }).ToJson()));
}
// ---- The balance of the restrictions ----------------------------------------------------------------------------
private static readonly DateTimeOffset _t0 = new(2027, 1, 10, 0, 5, 0, TimeSpan.Zero);
private static Example Case(string symbol, bool? win, double? result, int? closedIn, double multiplier = 1, string stage = StrategyStages.Simulation, bool labelled = true) =>
new(Guid.NewGuid(), Crypto, symbol, CaseSources.Live, new DateOnly(2027, 1, 9), _t0, "trend_entry", 0.2m, null, null, new Dictionary<string, double>())
{
Stage = stage,
DecisionId = Guid.NewGuid(),
Multiplier = multiplier,
Label = labelled ? new CaseLabel(win, result, new DateOnly(2027, 1, 10), closedIn is { } d ? new DateOnly(2027, 1, 10).AddDays(d) : null, "x") : null,
};
private static BlockedEntry Block(Example e, string code, bool postponed = false, int minutes = 0) => new(e.DecisionId!.Value, Crypto, e.Symbol, code, postponed, e.At.AddMinutes(minutes));
private static readonly Dictionary<string, double> _capital = new() { [Crypto] = 4_000 };
[TestMethod]
[TestCategory(Category.Unit)]
public void TheBalanceSaysWhatWasAvoidedAndWhatItCost()
{
var lost = Case("AAA", false, -0.1, 5);
var won = Case("BBB", true, 0.05, 5, multiplier: 0.5);
var open = Case("CCC", null, null, null, labelled: false);
var never = Case("DDD", null, null, null);
var later = Case("EEE", false, -0.2, 5);
var held = Case("FFF", false, -0.2, 5);
var r = RestrictionBalance.Of(
[
Block(lost, NewsReasons.Severe), Block(won, NewsReasons.Severe), Block(open, NewsReasons.Severe), Block(never, NewsReasons.Severe),
Block(later, CorrectiveReasons.CalendarEvent, postponed: true), Block(held, NewsReasons.Negative),
new BlockedEntry(Guid.NewGuid(), Crypto, "GGG", NewsReasons.Negative, false, _t0), Block(lost, "altro"),
],
[lost, won, open, never, later, held],
[new HeldTrade(Crypto, "EEE", _t0.AddMinutes(40), null), new HeldTrade(Crypto, "FFF", _t0.AddDays(-3), null)], _capital);
var severe = r.Lines.Single(l => l.Code == NewsReasons.Severe);
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 80m, 20m, 1, 1, 0, 0), severe);
Assert.AreEqual(1, r.Lines.Single(l => l.Code == CorrectiveReasons.CalendarEvent).Delayed, "bought at the end of the window");
Assert.AreEqual(2, r.Lines.Single(l => l.Code == NewsReasons.Negative).Increases, "one already open, one without an example");
Assert.AreEqual((80m, 20m), (r.Avoided, r.GivenUp));
Assert.IsTrue(RestrictionBalance.Of([], [lost], [], _capital).IsEmpty, "a row switched off blocks nothing");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ARepeatedBlockIsOneCaseUnderItsStrictestRow()
{
var e = Case("AAA", false, -0.033333, 9);
var again = Block(e, NewsReasons.Severe, minutes: 24 * 60) with { DecisionId = Guid.NewGuid() };
var r = RestrictionBalance.Of([Block(e, CorrectiveReasons.CalendarEvent, postponed: true), again], [e], [], _capital);
var line = r.Lines.Single();
Assert.AreEqual((NewsReasons.Severe, 1, 26.67m), (line.Code, line.Stopped, line.Avoided));
// After the simulated close a new block of the same instrument is no longer that example.
var late = again with { At = _t0.AddDays(20) };
Assert.AreEqual(1, RestrictionBalance.Of([late], [e], [], _capital).Lines.Single().Increases);
// In observation nothing is bought: an entry only put off is one made later, one stopped is out.
var seen = Case("BBB", false, -0.1, 5, stage: StrategyStages.Observation);
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, CorrectiveReasons.CalendarEvent, postponed: true)], [seen], [], _capital).Lines.Single().Delayed);
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
}
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePurchasesTheEngineHeldBackAreInTheBalance()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39));
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9,
"CoinDesk", trusted: true);
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero),
3, -0.8, "CoinDesk", trusted: true);
await live.DayAsync(day);
var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList();
Assert.HasCount(2, cases);
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open);
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open);
foreach (var e in cases)
{
var loses = e.Symbol == "ETH-EUR";
await live.Rig.Db.WriteAsync(s => LearningStore.AddLabelAsync(s, live.Rig.Clock, e.Id, new CaseLabel(!loses, loses ? -0.1 : 0.04, e.Day.AddDays(1), e.Day.AddDays(9), "x"), _none), _none);
}
var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto];
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2);
Assert.IsGreaterThan(0m, r.Avoided);
Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m);
Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m);
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, live.Rig.Clock.UtcNow.AddDays(1), _none)).IsEmpty);
}
}