Judge the variant in use and count the shadow cases for what they are

The quarterly review judged the best variant of the grid instead of the one
that trades: the plan now fixes the variant in use and the protocol measures
that one, while the tries are still those of the grid. A failure while the
history is prepared is a reason in the report and no longer stops the review,
and a strategy whose protocol does not exist says so when its data are there.

The volatility improvement compared books of different days and stages: the
book keeps its stage and its previous day, and a case without a book valid on
its day is left out. Fewer than six months give no interval, the others use
the clustered error with the Student t.

The restriction balance counts a case in the period in which its outcome
became known, so no case is lost or counted twice between two reviews.

The contact given to the SEC travels only on the client that never follows a
redirect, so it cannot reach another site.

refs #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 22:26:06 +01:00
1 parent 24e20584d4
commit 3543f29aba
23 files changed
+577 -126

No files matched your search

+179 -9
View File
@@ -35,22 +35,25 @@ public sealed class QuarterlyReviewTests
}
// A report of the protocol on those coins, whose verdict each test chooses.
private static readonly Lazy<Task<BacktestReport>> _report = new(async () =>
private static readonly Lazy<Task<BacktestReport>> _report = new(async () => (await TrialAsync(null).ConfigureAwait(false)).Report);
private static async Task<(BacktestReport Report, TrialSummary Summary)> TrialAsync(string? judged)
{
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 plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan with
{ Judged = judged };
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;
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5));
}
finally
{
TempFolder.Delete(folder);
}
});
}
private sealed class ReviewRig : IAsyncDisposable
{
@@ -64,6 +67,8 @@ public sealed class QuarterlyReviewTests
public string? Missing { get; set; }
public Exception? Failure { get; set; }
public List<DateOnly> Prepared { get; } = [];
public Database Db => Live.Rig.Db;
@@ -96,7 +101,7 @@ public sealed class QuarterlyReviewTests
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
{
Prepared.Add(to);
return Task.FromResult(Missing);
return Failure is { } failure ? Task.FromException<string?>(failure) : Task.FromResult(Missing);
});
Lab.ReviewTrialEnded = Review.ConcludeAsync;
}
@@ -226,6 +231,33 @@ public sealed class QuarterlyReviewTests
Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnErrorWhilePreparingTheHistoryIsAMissingReasonLikeTheOthers()
{
await using var rig = await ReviewRig.CreateAsync(history: false);
await rig.NightAsync(At(2026, 12, 10));
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
await rig.NightAsync(At(2027, 1, 5));
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
// A wait that ran out is an error too; the stop of the program is not, and the review stays as it is.
rig.Failure = new TaskCanceledException();
await rig.NightAsync(At(2027, 1, 6));
rig.Clock.Set(At(2027, 1, 17));
using var stop = new CancellationTokenSource();
await stop.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => rig.Review.RunIfDueAsync(stop.Token));
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
await rig.NightAsync(At(2027, 1, 18));
var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
Assert.AreEqual(ReviewStatuses.Done, done.Status);
Assert.AreEqual("lo storico non si è potuto preparare per un errore", done.Report!.Missing);
Assert.AreEqual("Non riprovata, dati mancanti: lo storico non si è potuto preparare per un errore. Resta valido l'esito precedente.", done.Report.Strategies.Single().Text);
}
// ---- The run ----------------------------------------------------------------------------------------------------
/// <summary>The real trials, with a restart in the middle: each trial counts once, the review concludes once.</summary>
@@ -406,6 +438,78 @@ public sealed class QuarterlyReviewTests
Assert.IsTrue((await DemotionAsync()).Met);
}
// ---- The variant in use -----------------------------------------------------------------------------------------
/// <summary>The grid says how much was searched; the figures, the checks and the curve are those of the variant the strategy works with.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ATrialJudgesTheVariantInUseAndCountsTheSameTries()
{
var chosen = await _report.Value;
Assert.IsNull(chosen.Judged);
var used = chosen.Variants.First(v => !v.Chosen && v.NetResult != chosen.Metrics.NetResult);
var (report, summary) = await TrialAsync(used.Parameters);
Assert.AreEqual((used.Parameters, chosen.Chosen), (report.Judged, report.Chosen));
Assert.AreEqual((used.NetResult, used.MaxDrawdown), (report.Metrics.NetResult, report.Metrics.MaxDrawdown));
Assert.AreEqual(used.NetResult, report.Costs.Single(c => c.Multiplier == 1m).NetResult);
Assert.AreNotEqual(chosen.Costs.Single(c => c.Multiplier == 2m).NetResult, report.Costs.Single(c => c.Multiplier == 2m).NetResult);
Assert.AreEqual(used.MaxDrawdown, report.Checks.Single(c => c.Key == ReportCheckKeys.Drawdown).Value);
Assert.AreEqual(used.Sharpe, report.DeflatedSharpe.Sharpe);
Assert.AreEqual(report.DeflatedSharpe.Value, report.Checks.Single(c => c.Key == ReportCheckKeys.DeflatedSharpe).Value);
Assert.AreEqual(CryptoTrendProtocol.Capital + used.NetResult, report.Curve[^1].Equity, 0.01m);
CollectionAssert.AreNotEqual(chosen.ExpectedPathP5!.ToList(), report.ExpectedPathP5!.ToList());
Assert.AreEqual((used.Parameters, used.NetResult), (summary.Chosen, summary.NetResult));
// What the grid decided stays.
CollectionAssert.AreEqual(chosen.Variants.ToList(), report.Variants.ToList());
Assert.AreEqual(chosen.Overfitting, report.Overfitting);
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark), (report.TrialsCounted, report.DeflatedSharpe.Benchmark));
Assert.IsFalse(report.Limitations.Any(l => l.Contains("griglia", StringComparison.Ordinal)));
// Not among the variants of the grid: judged all the same, and it says so.
var (outside, tries) = await TrialAsync("coin_vol=12;max_stop=20");
var added = outside.Variants.Single(v => v.OutsideGrid);
Assert.AreEqual(("coin_vol=12;max_stop=20", false), (added.Parameters, added.Chosen));
Assert.AreEqual((added.NetResult, added.MaxDrawdown), (outside.Metrics.NetResult, outside.Metrics.MaxDrawdown));
CollectionAssert.AreEqual(chosen.Variants.ToList(), outside.Variants.Where(v => !v.OutsideGrid).ToList());
Assert.HasCount(chosen.Variants.Count, tries.VariantSharpes);
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark, chosen.Overfitting), (outside.TrialsCounted, outside.DeflatedSharpe.Benchmark, outside.Overfitting));
Assert.Contains("La variante in uso non è nella griglia", string.Join(" ", outside.Limitations));
}
[TestMethod]
[TestCategory(Category.Integration)]
[DataRow(StrategyStages.Observation, "coin_vol=10;max_stop=20", null)]
[DataRow(StrategyStages.Simulation, "coin_vol=10;max_stop=20", "coin_vol=10;max_stop=20")]
[DataRow(StrategyStages.Simulation, "coin_vol=12.0;max_stop=20", "coin_vol=12;max_stop=20")]
[DataRow(StrategyStages.Simulation, null, "coin_vol=15;max_stop=15")]
public async Task ThePlanOfAReviewFixesTheVariantInUse(string stage, string? parameters, string? judged)
{
await using var rig = await ReviewRig.CreateAsync(stage, qualification: Old(true) with { Parameters = parameters });
var review = await rig.OpenAsync();
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(Old(true) with { Parameters = "coin_vol=20;max_stop=20" }, Qualification.Json)))), _none);
rig.Start();
var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none);
Assert.HasCount(2, trials);
Assert.IsTrue(trials.All(t => t.PlanIntact && t.Plan.Judged == judged && t.Variants == 9), string.Join(" ", trials.Select(t => t.Plan.Judged)));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheVerdictOnAStrategyWithCapitalIsOfTheVariantInUse()
{
const string used = "coin_vol=12;max_stop=20";
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true) with { Parameters = used });
var review = await rig.ReviewAsync(passed: true, r => r with { Judged = used, Variants = [.. r.Variants, new ReportVariant(used, 0.05, 0, 321m, 0.11, 7, false) { OutsideGrid = true }] });
var line = review.Report!.Strategies.Single();
Assert.AreEqual((ReviewVerdicts.Passed, ReviewActions.Confirmed), (line.Verdict, line.Action));
Assert.AreEqual("Revisione del 1º trimestre 2027: protocollo superato su entrambi gli universi con la variante in uso. La variante in uso non è nella griglia: è giudicata lo stesso.", line.Text);
Assert.AreEqual((used, 321m, true), (line.InUse!.Parameters, line.InUse.NetResult, line.InUse.OutsideGrid));
Assert.AreEqual((await _report.Value).Chosen, line.Chosen!.Parameters);
var outcome = JsonSerializer.Deserialize<Qualification>((await rig.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT qualification FROM review_outcomes", r => r.Json("qualification").Text), _none))!, Qualification.Json)!;
Assert.AreEqual(used, outcome.Parameters, "the parameters the figures are of");
}
internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s =>
{
var id = Ids.NewId(clock);
@@ -433,6 +537,21 @@ public sealed class QuarterlyReviewTests
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));
Assert.AreEqual((false, "non riprovata, mancano i dati"), (stock.NoProtocol, QuarterlyReview.ActionText(stock)));
// With the bars collected what is missing is the protocol, not the data.
var share = await new InstrumentCatalog(rig.Db, rig.Clock).EnsureAsync(StrategyData.Share("AAA"), _none);
await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(share.Id, [new DailyBar(new DateOnly(2027, 1, 4), 50, 51, 49, 50, 1000)], "test", _none);
await rig.NightAsync(At(2027, 4, 5));
await rig.EndAsync((await QuarterlyReview.ListAsync(rig.Db, _none))[0], passed: false);
await rig.Review.ConcludeAsync(_none);
stock = (await QuarterlyReview.ListAsync(rig.Db, _none))[0].Report!.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
const string text = "non riprovata: il protocollo per le azioni arriva con una versione successiva";
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None, true), (stock.Verdict, stock.Action, stock.NoProtocol));
Assert.AreEqual(text, QuarterlyReview.ActionText(stock));
Assert.StartsWith("Non riprovata: il protocollo per le azioni", stock.Text);
Assert.Contains(text, (await NewsRulesTests.DiaryAsync(rig.Db)).Last(m => m.StartsWith("Revisione trimestrale pronta (2º", StringComparison.Ordinal)));
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review' AND message LIKE '%versione successiva%'"));
}
// ---- Base rates -------------------------------------------------------------------------------------------------
@@ -619,6 +738,50 @@ public sealed class QuarterlyReviewTests
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
}
/// <summary>A block is of the period in which its outcome became known, so the periods add up to the whole.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePeriodsOfTheBalanceAddUpToTheWhole()
{
var first = _t0.AddDays(3);
var second = _t0.AddDays(30);
var early = Case("AAA", true, 0.05, 2) with { LabelledAt = _t0.AddDays(2.5) };
var lost = Case("BBB", false, -0.1, 5) with { LabelledAt = _t0.AddDays(6) };
var off = Case("CCC", false, -0.2, 2) with { LabelledAt = first.AddDays(1) };
var open = Case("DDD", null, null, null, labelled: false);
var bought = Case("EEE", false, -0.2, 5) with { LabelledAt = _t0.AddDays(6) };
var seen = Case("FFF", false, -0.2, 5, stage: StrategyStages.Observation) with { LabelledAt = _t0.AddDays(6) };
var never = Case("GGG", null, null, 1) with { LabelledAt = _t0.AddDays(1) };
IReadOnlyList<BlockedEntry> blocks =
[
.. new[] { early, lost, off, open, bought, never }.Select(e => Block(e, NewsReasons.Severe)), Block(seen, CorrectiveReasons.CalendarEvent, postponed: true),
new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, _t0), new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, first.AddDays(2)),
];
RestrictionReport Of(DateTimeOffset from, DateTimeOffset until) => RestrictionBalance.Of(blocks, [early, lost, off, open, bought, seen, never], [new HeldTrade(Crypto, "EEE", _t0.AddDays(4), null)], _capital, from, until);
RestrictionLine? Line(RestrictionReport r, string code) => r.Lines.SingleOrDefault(l => l.Code == code);
var (one, two, ever) = (Of(DateTimeOffset.UnixEpoch, first), Of(first, second), Of(DateTimeOffset.UnixEpoch, second));
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 1, 0m, 40m, 4, 1, 0, 1), Line(one, NewsReasons.Severe), "what was not known yet is open");
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 240m, 0m, 1, 0, 1, 1), Line(two, NewsReasons.Severe), "known after the first review, even what closed before it");
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 3, 240m, 40m, 1, 1, 1, 2), Line(ever, NewsReasons.Severe));
Assert.AreEqual(1, Line(one, CorrectiveReasons.CalendarEvent)!.Open);
Assert.AreEqual((1, 0), (Line(two, CorrectiveReasons.CalendarEvent)!.Delayed, Line(two, CorrectiveReasons.CalendarEvent)!.Open));
Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstReviewCountsTheRestrictionsFromTheStart()
{
await using var rig = await ReviewRig.CreateAsync();
rig.Clock.Set(new DateTimeOffset(2026, 8, 15, 10, 0, 0, TimeSpan.Zero));
await rig.Db.WriteAsync(s => DecisionLog.WriteAsync(s, rig.Clock, new DecisionRow(Guid.NewGuid(), Crypto, null, "ETH-EUR", DecisionStages.Order, DecisionOutcomes.Refused, [NewsReasons.Severe],
new Dictionary<string, object?>(), rig.Clock.UtcNow), _none), _none);
var report = (await rig.ReviewAsync(passed: false)).Report!;
Assert.AreEqual(1, report.RestrictionsEver.Lines.Single().Increases);
Assert.AreEqual(report.RestrictionsEver.Lines.Single(), report.Restrictions.Lines.SingleOrDefault());
Assert.AreEqual(new DateOnly(2026, 8, 15), report.RestrictionsFrom);
}
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
@@ -634,10 +797,13 @@ public sealed class QuarterlyReviewTests
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);
var first = live.Rig.Clock.UtcNow;
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _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);
// The outcomes arrive after the first review.
live.Rig.Clock.Set(first.AddDays(20));
foreach (var e in cases)
{
var loses = e.Symbol == "ETH-EUR";
@@ -645,11 +811,15 @@ public sealed class QuarterlyReviewTests
}
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);
var now = live.Rig.Clock.UtcNow;
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, now, _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);
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, now, now.AddDays(1), _none)).IsEmpty, "each outcome in one period only");
var since = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, first, now, _none);
Assert.AreEqual((r.Avoided, r.GivenUp), (since.Avoided, since.GivenUp), "blocked before the first review, known after it");
Assert.AreEqual(2, (await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none)).Lines.Sum(l => l.Open));
}
}