Fase 13 — Campionato: unità di lavoro, piano e statistica (#188)
ci / test (postgres) (push) Successful in 9m13s
ci / test (sqlite) (push) Successful in 7m33s
ci / image (push) Successful in 2m48s

The tournament judge before the contenders (ADR 0029): the trial judge split into resumable work units on a pool of low-priority workers, the common count of trials and field statistics, the control against chance on surrogate prices, and the immutable tournament plan with a final tract read once.

refs #122, refs #123, refs #124, refs #125, refs #126

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #188.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-12-04 15:53:40 +01:00
1 parent e0a438a0b2
commit cfa2a4da0e
31 files changed
+4776 -225

No files matched your search

+15
View File
@@ -35,6 +35,21 @@ public sealed class ArchiveTests
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
// A tournament, one of its trials and a unit with its outcome: JSON, bytes and a measure across engines (Phase 13).
var tournament = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(40));
var trial = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(41));
await s.ExecuteAsync(
"INSERT INTO tournaments (id, name, plan, plan_hash, status, finalists, created_at, started_at) VALUES (@id, 'Campionato', @p, 'abc', 'running', @f, @t, @t)",
("id", tournament), ("p", new DbJson("{\"name\": \"Campionato\", \"cost_multipliers\": [1, 2, 3]}")), ("f", new DbJson("[\"a\", \"b\"]")),
("t", _clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, tournament_id) VALUES (@id, 'sma_cross', '1', @p, 'def', 4, 'running', @t, @tour)",
("id", trial), ("p", new DbJson("{\"strategy\": \"sma_cross\"}")), ("t", _clock.UtcNow), ("tour", tournament)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', 'abc|2|def', @o, @sec, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(42))), ("tr", trial), ("tour", tournament), ("o", new byte[] { 31, 139, 8, 0, 255, 0 }), ("sec", 0.1234567890123),
("t", _clock.UtcNow)).ConfigureAwait(false);
}).ConfigureAwait(false);
}
+2
View File
@@ -0,0 +1,2 @@
// The fixed-seed generator lives in Core since Phase 13; the tests keep calling it Gen, as they always did.
global using Gen = Anubis.Core.SeededRandom;
+4 -1
View File
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Net;
using System.Net.Http.Json;
using Anubis.Server;
@@ -37,10 +38,12 @@ public sealed class HealthEndpointTests
return (await response.Content.ReadFromJsonAsync<HealthResponse>())!;
}
// Up to 30 seconds of wall time: on a busy test runner the engine can take more than ten to start.
async Task UntilAsync(string status, string loop)
{
HealthResponse? last = null;
for (var i = 0; i < 100; i++)
var deadline = Stopwatch.StartNew();
while (last is null || deadline.Elapsed < TimeSpan.FromSeconds(30))
{
last = await HealthAsync();
if (last.Status == status && last.Checks!.GetValueOrDefault("motore") == loop)
-84
View File
@@ -29,87 +29,3 @@ internal static class Property
}
}
}
/// <summary>
/// Fixed-seed generator based on SplitMix64. Unlike a seeded <see cref="Random"/>, its sequence is
/// fixed by this code, so it stays the same on every platform and .NET version.
/// </summary>
internal sealed class Gen(int seed)
{
private ulong _state = unchecked((ulong)(long)seed);
public ulong NextUInt64()
{
var z = _state += 0x9E3779B97F4A7C15UL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
public long Long(long minInclusive, long maxExclusive)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
var range = unchecked((ulong)(maxExclusive - minInclusive));
var limit = ulong.MaxValue - (ulong.MaxValue % range);
ulong x;
do
{
x = NextUInt64();
}
while (x >= limit);
return unchecked(minInclusive + (long)(x % range));
}
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
/// <summary>Uniform value in [0, 1).</summary>
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
/// <summary>A standard normal value (Box–Muller), for synthetic price series and returns.</summary>
public double Normal()
{
var u = 1.0 - Double();
var v = Double();
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
}
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
public decimal Decimal(decimal min, decimal max, int scale)
{
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
ArgumentOutOfRangeException.ThrowIfNegative(scale);
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
var unit = 1m;
for (var i = 0; i < scale; i++)
{
unit /= 10m;
}
var low = decimal.Ceiling(min / unit);
var high = decimal.Floor(max / unit);
if (low > high)
{
throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale));
}
var steps = high - low;
if (steps >= long.MaxValue)
{
throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale));
}
var k = Long(0, (long)steps + 1);
return (low + k) * unit;
}
public T Pick<T>(IReadOnlyList<T> items)
{
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
return items[Int(0, items.Count)];
}
}
+180
View File
@@ -0,0 +1,180 @@
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The control against chance (issue #124, criteria 3 and 4 of Phase 13): the surrogate series keep each day's size and
/// the correlations and lose every memory; a rule with an edge beats them, a rule without one does not.
/// </summary>
[TestClass]
public sealed class SurrogateTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSurrogateKeepsEveryDaysAbsoluteReturnAndTheCorrelations()
{
// On returns: flipped, every day keeps its size exactly; centred, its distance from the mean.
var returns = Synthetic.WalkReturns(1000, 3, drift: 0.001);
var signs = TournamentStatistics.Signs(returns.Length, 5);
var flipped = Surrogates.Flip(returns, signs, centred: false);
var centred = Surrogates.Flip(returns, signs, centred: true);
var mean = returns.Average();
for (var i = 0; i < returns.Length; i++)
{
Assert.AreEqual(Math.Abs(returns[i]), Math.Abs(flipped[i]));
Assert.AreEqual(signs[i] * returns[i], flipped[i]);
Assert.AreEqual(Math.Abs(returns[i] - mean), Math.Abs(centred[i] - mean), 1e-15);
}
Assert.IsTrue(signs.Count(s => s < 0) is > 400 and < 600, "About half the days change sign.");
// On bars: two correlated coins flip together, so their correlation stays and each day keeps its size.
var (a, b) = Synthetic.CorrelatedReturns(2000, 0.7, 11);
var data = Synthetic.Dataset(("AAA-EUR", Synthetic.Bars(a, 1)), ("BBB-EUR", Synthetic.Bars(b, 2)));
var surrogate = Surrogates.Of(data, seed: 21, centred: false);
var ra = Synthetic.CloseReturns(data["AAA-EUR"]!.Bars);
var rb = Synthetic.CloseReturns(data["BBB-EUR"]!.Bars);
var sa = Synthetic.CloseReturns(surrogate["AAA-EUR"]!.Bars);
var sb = Synthetic.CloseReturns(surrogate["BBB-EUR"]!.Bars);
var changed = 0;
for (var i = 0; i < ra.Length; i++)
{
Assert.AreEqual(Math.Abs(ra[i]), Math.Abs(sa[i]), 1e-12);
Assert.AreEqual(Math.Abs(rb[i]), Math.Abs(sb[i]), 1e-12);
Assert.AreEqual(Math.Sign(sa[i]) * Math.Sign(ra[i]), Math.Sign(sb[i]) * Math.Sign(rb[i]), "One sign a day for every instrument.");
changed += Math.Sign(sa[i]) != Math.Sign(ra[i]) ? 1 : 0;
}
Assert.IsTrue(changed is > 800 and < 1200, $"{changed} days flipped");
Assert.AreEqual(Synthetic.Correlation(ra, rb), Synthetic.Correlation(sa, sb), 0.02);
Assert.AreEqual(0.7, Synthetic.Correlation(sa, sb), 0.05);
// The first bar is the same, the volume never changes, the high stays the highest and the low the lowest.
foreach (var symbol in new[] { "AAA-EUR", "BBB-EUR" })
{
var real = data[symbol]!.Bars;
var made = surrogate[symbol]!.Bars;
Assert.AreEqual(real[0], made[0]);
Assert.HasCount(real.Count, made);
for (var i = 0; i < made.Count; i++)
{
Assert.AreEqual(real[i].Day, made[i].Day);
Assert.AreEqual(real[i].Volume, made[i].Volume);
Assert.IsTrue(made[i].High >= Math.Max(made[i].Open, made[i].Close) && made[i].Low <= Math.Min(made[i].Open, made[i].Close), made[i].ToString());
}
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASeriesWithMemoryLosesItInTheSurrogate()
{
var returns = Synthetic.AutoregressiveReturns(2000, 0.6, 4);
Assert.AreEqual(0.6, Synthetic.LagOne(returns), 0.05, "The hand-built series has memory.");
var lost = Enumerable.Range(0, 20)
.Select(k => Synthetic.LagOne(Surrogates.Flip(returns, TournamentStatistics.Signs(returns.Length, TournamentStatistics.ReplicaSeed(9, k)), centred: false)))
.ToList();
Assert.IsTrue(lost.Average(Math.Abs) < 0.1, string.Join(" ", lost));
Assert.IsTrue(lost.All(x => Math.Abs(x) < 0.15), string.Join(" ", lost));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AFallingDayTurnedUpSwapsHighAndLow()
{
// From a close of 100: open 101, high 103, low 98, close 99. With the sign turned, every price p becomes
// 100 × 100 / p, so the old low makes the new high and the old high the new low.
var day = Synthetic.Start;
IReadOnlyList<DailyBar> bars = [new(day, 100, 100, 100, 100, 10), new(day.AddDays(1), 101, 103, 98, 99, 20)];
var signs = new DaySigns(day, [1, -1]);
var made = Surrogates.Bars(bars, signs, centred: false);
Assert.AreEqual(bars[0], made[0]);
Assert.AreEqual(10_000.0 / 101, made[1].Open, 1e-9);
Assert.AreEqual(10_000.0 / 98, made[1].High, 1e-9);
Assert.AreEqual(10_000.0 / 103, made[1].Low, 1e-9);
Assert.AreEqual(10_000.0 / 99, made[1].Close, 1e-9);
Assert.AreEqual(20, made[1].Volume);
// The same day with its sign kept is the same bar.
var kept = Surrogates.Bars(bars, new DaySigns(day, [1, 1]), centred: false);
Assert.AreEqual(101, kept[1].Open, 1e-9);
Assert.AreEqual(103, kept[1].High, 1e-9);
Assert.AreEqual(98, kept[1].Low, 1e-9);
Assert.AreEqual(99, kept[1].Close, 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSurrogateRepeatsWithItsSeedAndChangesWithAnother()
{
var data = Synthetic.Walk(300, 2);
var one = Surrogates.Of(data, seed: 5, centred: true);
var again = Surrogates.Of(data, seed: 5, centred: true);
var other = Surrogates.Of(data, seed: 6, centred: true);
Assert.AreEqual(one.Fingerprint(), again.Fingerprint());
Assert.AreNotEqual(one.Fingerprint(), other.Fingerprint());
Assert.AreNotEqual(data.Fingerprint(), one.Fingerprint());
Assert.AreEqual(data.Currency, one.Currency);
CollectionAssert.AreEqual(data.Calendar.ToArray(), one.Calendar.ToArray());
// Signs belong to calendar days: the same days get the same signs whatever the instrument.
var signs = DaySigns.Draw(Synthetic.Start, Synthetic.Start.AddDays(9), 5);
Assert.AreEqual(Synthetic.Start, signs.First);
Assert.AreEqual(Synthetic.Start.AddDays(9), signs.Last);
CollectionAssert.AreEqual(TournamentStatistics.Signs(10, 5), Enumerable.Range(0, 10).Select(i => signs[Synthetic.Start.AddDays(i)]).ToArray());
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => signs[Synthetic.Start.AddDays(10)]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASurrogateOfInstrumentsWithCorporateActionsIsRefused()
{
var bars = BacktestData.Walk(60, 3);
var split = new CorporateAction("AAPL", CorporateActionKinds.Split, bars[30].Day, "test", "s1") { Ratio = 2m };
var data = BacktestData.One(BacktestData.Stock(), bars, [split]);
var error = Assert.ThrowsExactly<NotSupportedException>(() => Surrogates.Of(data, seed: 1, centred: true));
Assert.AreEqual("Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.", error.Message);
}
/// <summary>
/// Criterion 4, first half: three coins whose prices halve their distance from the mean in 50 bars, over 3000 days, and
/// a rule that buys them low and sells them back at the mean. Its result is real: at most 1 surrogate in 20 does as well.
/// One coin is not enough: the edge of this rule is a daily Sharpe ratio of about 0.03, the spread of the replicas
/// about 0.017, so on one coin of 3000 days the control passes on one seed out of three; three coins make it about
/// three spreads.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void OnAMeanRevertingSeriesAReversionRulePassesTheControl()
{
var data = Synthetic.MeanReverting(3000, 7, coins: 3, halfLife: 50, volatility: 0.01);
var (observed, replicas, share) = Synthetic.Control(ReversionFamily.Instance, ReversionFamily.With(300, 1m), data, 200, seed: 20_261_204, centred: true);
Assert.IsTrue(observed > 0, $"observed {observed}");
Assert.IsTrue(share <= 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
}
/// <summary>
/// Criterion 4, second half: on a random walk that drifts up, a long-only trend rule earns the drift and nothing
/// else. The centred surrogates keep the drift, so they do as well and the rule fails the control.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void OnARandomWalkWithDriftALongOnlyTrendRuleFailsTheControl()
{
var data = Synthetic.Walk(3000, 8, drift: 0.0008, volatility: 0.02);
var parameters = new StrategyParameters([new("fast", 20m), new("slow", 100m)]);
var (observed, replicas, share) = Synthetic.Control(MovingAverageCrossFamily.Instance, parameters, data, 200, seed: 20_261_204, centred: true);
Assert.IsTrue(share > 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
}
}
+273
View File
@@ -0,0 +1,273 @@
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// Synthetic series with a known nature, built from a fixed seed (Phase 13): a mean-reverting price (Ornstein–Uhlenbeck on
/// the logarithm), a random walk with or without drift, returns with memory, correlated pairs. The statistics of the
/// tournament are proved on them, because only there is the truth known in advance. Shared by the tests of the control,
/// of the common statistics and of the tournament.
/// </summary>
internal static class Synthetic
{
public static readonly DateOnly Start = new(2018, 1, 1);
/// <summary>A coin quoted in euro on OKX, traded every day: the synthetic series live on it.</summary>
public static InstrumentSpec Coin(string symbol = "AAA-EUR") => new(Venues.Okx, symbol, symbol, AssetClasses.Crypto, "EUR")
{
BaseCurrency = symbol.Split('-')[0],
TickSize = 0.0001m,
LotSize = 0.00000001m,
MinSize = 0.00001m,
Status = "live",
};
/// <summary>The autoregressive coefficient of a daily series whose distance from its mean halves in <paramref name="halfLife"/> bars.</summary>
public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife);
/// <summary>
/// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the
/// <paramref name="halfLife"/> and the series started at its level. The return of day t is x(t) − x(t−1).
/// </summary>
public static double[] MeanRevertingReturns(int days, int seed, double halfLife = 50, double volatility = 0.01)
{
var gen = new Gen(seed);
var phi = Phi(halfLife);
var result = new double[days];
var x = 0.0;
for (var i = 0; i < days; i++)
{
var next = (phi * x) + (volatility * gen.Normal());
result[i] = next - x;
x = next;
}
return result;
}
/// <summary>Log returns of a random walk: <paramref name="drift"/> plus normal noise, no memory.</summary>
public static double[] WalkReturns(int days, int seed, double drift = 0, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
for (var i = 0; i < days; i++)
{
result[i] = drift + (volatility * gen.Normal());
}
return result;
}
/// <summary>Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ.</summary>
public static double[] AutoregressiveReturns(int days, double phi, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
var previous = 0.0;
for (var i = 0; i < days; i++)
{
previous = (phi * previous) + (volatility * gen.Normal());
result[i] = previous;
}
return result;
}
/// <summary>Two series of returns with correlation about <paramref name="correlation"/>: a common part and a part of each.</summary>
public static (double[] A, double[] B) CorrelatedReturns(int days, double correlation, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var own = Math.Sqrt(1 - (correlation * correlation));
var a = new double[days];
var b = new double[days];
for (var i = 0; i < days; i++)
{
var common = gen.Normal();
a[i] = volatility * common;
b[i] = volatility * ((correlation * common) + (own * gen.Normal()));
}
return (a, b);
}
/// <summary>
/// Daily bars from log returns of the close: the first bar at <paramref name="start"/>, then each close the one before
/// times e^r. The open is the previous close, high and low a little beyond the body, all unrounded.
/// </summary>
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<double> logReturns, int seed = 1, double start = 100, DateOnly? from = null)
{
ArgumentNullException.ThrowIfNull(logReturns);
var gen = new Gen(seed);
var day = from ?? Start;
var bars = new List<DailyBar>(logReturns.Count + 1) { new(day, start, start * 1.002, start * 0.998, start, 1000) };
var close = start;
for (var i = 0; i < logReturns.Count; i++)
{
var open = close;
close = open * Math.Exp(logReturns[i]);
var high = Math.Max(open, close) * (1 + (0.003 * gen.Double()));
var low = Math.Min(open, close) * (1 - (0.003 * gen.Double()));
bars.Add(new DailyBar(day.AddDays(i + 1), open, high, low, close, 1000));
}
return bars;
}
/// <summary>A dataset in euro of synthetic coins, one per series of bars.</summary>
public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList<DailyBar> Bars)[] series) =>
new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR");
/// <summary>A mean-reverting coin: <paramref name="days"/> returns of <see cref="MeanRevertingReturns"/> turned into bars.</summary>
public static BacktestDataset MeanReverting(int days, int seed, double halfLife = 50, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(MeanRevertingReturns(days, seed, halfLife, volatility), seed)));
/// <summary>Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed.</summary>
public static BacktestDataset MeanReverting(int days, int seed, int coins, double halfLife = 50, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(MeanRevertingReturns(days, seed + (1000 * k), halfLife, volatility), seed + k)))]);
/// <summary>Several independent coins walking at random with the same <paramref name="drift"/>, each from its own seed.</summary>
public static BacktestDataset Walk(int days, int seed, int coins, double drift = 0, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(WalkReturns(days, seed + (1000 * k), drift, volatility), seed + k)))]);
/// <summary>The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR…</summary>
public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR");
/// <summary>A coin that walks at random with a <paramref name="drift"/> a day (zero for pure noise).</summary>
public static BacktestDataset Walk(int days, int seed, double drift = 0, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(WalkReturns(days, seed, drift, volatility), seed)));
/// <summary>Log returns of the closes of a series of bars, one per bar after the first.</summary>
public static double[] CloseReturns(IReadOnlyList<DailyBar> bars)
{
ArgumentNullException.ThrowIfNull(bars);
return [.. Enumerable.Range(1, Math.Max(bars.Count - 1, 0)).Select(i => Math.Log(bars[i].Close / bars[i - 1].Close))];
}
/// <summary>Pearson correlation of two series of the same length.</summary>
public static double Correlation(IReadOnlyList<double> x, IReadOnlyList<double> y)
{
var mx = x.Average();
var my = y.Average();
double sxy = 0, sxx = 0, syy = 0;
for (var i = 0; i < x.Count; i++)
{
sxy += (x[i] - mx) * (y[i] - my);
sxx += (x[i] - mx) * (x[i] - mx);
syy += (y[i] - my) * (y[i] - my);
}
return sxy / Math.Sqrt(sxx * syy);
}
/// <summary>Autocorrelation at lag one.</summary>
public static double LagOne(IReadOnlyList<double> x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]);
/// <summary>The daily Sharpe ratio of a run: what the control compares between the real series and its replicas.</summary>
public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe;
/// <summary>
/// The control of a rule on a dataset: its daily Sharpe on the real data, and on <paramref name="repetitions"/>
/// surrogates whose signs come from <paramref name="seed"/> + k. Returns the observed Sharpe, the replicas and the
/// share of replicas at least as good.
/// </summary>
public static (double Observed, double[] Replicas, double Share) Control(IStrategyFamily family, StrategyParameters parameters, BacktestDataset data, int repetitions, int seed, bool centred)
{
ArgumentNullException.ThrowIfNull(family);
var options = new BacktestOptions();
var observed = Sharpe(BacktestEngine.Run(family.Create(parameters), data, options));
var replicas = new double[repetitions];
for (var k = 0; k < repetitions; k++)
{
var surrogate = Surrogates.Of(data, TournamentStatistics.ReplicaSeed(seed, k), centred);
replicas[k] = Sharpe(BacktestEngine.Run(family.Create(parameters), surrogate, options));
}
return (observed, replicas, TournamentStatistics.ControlShare(observed, replicas));
}
}
/// <summary>
/// A test-only reversion rule, long only: it buys an instrument when its close falls <c>entry</c> standard deviations
/// below the mean of the last <c>lookback</c> closes (on the logarithm), and sells when the close is back at the mean. It
/// has an edge on a mean-reverting series and none on a random walk. It never enters the catalogue and has no order code.
/// </summary>
internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy
{
/// <summary>Bars it waits for before the first decision; until <c>lookback</c> bars, the mean is of those there are.</summary>
public const int MinimumBars = 50;
public string Id => ReversionFamily.FamilyId;
public string Version => "1";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
public IReadOnlyList<Intent> Decide(StrategyContext context)
{
var intents = new List<Intent>();
var weight = 1m / Math.Max(context.Universe.Count, 1);
foreach (var symbol in context.Universe)
{
var bars = context.Bars(symbol);
if (bars.Count < Math.Min(lookback, MinimumBars))
{
continue;
}
var logs = bars.Closes(lookback).Select(c => Math.Log(c)).ToArray();
var m = Moments.Of(logs);
if (m.StandardDeviation <= 0)
{
continue;
}
var z = (logs[^1] - m.Mean) / m.StandardDeviation;
var held = context.Portfolio.Holds(symbol);
if (!held && z < -(double)entry)
{
intents.Add(new Intent(symbol, weight, "reversion_entry"));
}
else if (held && z >= 0)
{
intents.Add(new Intent(symbol, 0m, "reversion_exit"));
}
}
return intents;
}
}
/// <summary>The family of <see cref="ReversionRule"/>: the window of the mean and the distance of the entry.</summary>
internal sealed class ReversionFamily : IStrategyFamily
{
public const string FamilyId = "test_reversion";
public static ReversionFamily Instance { get; } = new();
public string Id => FamilyId;
public string Version => "1";
public string Name => "Rientro di prova";
public string Description => "Regola di prova, solo nei test: compra sotto la media e vende quando il prezzo vi torna.";
public IReadOnlyList<ParameterSpec> Parameters =>
[
new("lookback", "Giorni della media", 100m, [50m, 100m, 150m], 10m, 400m, Whole: true),
new("entry", "Distanza d'ingresso in deviazioni", 1m, [0.5m, 1m, 1.5m], 0.1m, 4m),
];
public IStrategy Create(StrategyParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
return new ReversionRule(parameters.Whole("lookback"), parameters["entry"]);
}
/// <summary>The parameters of a variant, as the laboratory would build them.</summary>
public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]);
}
@@ -0,0 +1,218 @@
using Anubis.Backtest;
namespace Anubis.Tests;
/// <summary>
/// The common statistics of the tournament (issue #124, criterion 5 of Phase 13): one number of trials for the whole field,
/// one bar, one variance, one PBO, the effective number of bets, the bootstrap interval and the calendars put side by side.
/// </summary>
[TestClass]
public sealed class TournamentStatisticsTests
{
private static readonly DateOnly Monday = new(2024, 1, 1);
[TestMethod]
[TestCategory(Category.Unit)]
public void TwentyEightIdenticalSeriesAreWorthOneBet()
{
var one = Synthetic.WalkReturns(500, 1);
var copies = Enumerable.Range(0, 28).Select(_ => one.ToArray()).ToList();
Assert.AreEqual(1.0, TournamentStatistics.EffectiveBets(copies), 1e-12);
// Independent series are about as many bets as series; a flat series is a bet of its own.
var independent = Enumerable.Range(0, 28).Select(k => Synthetic.WalkReturns(500, 100 + k)).ToList();
Assert.IsTrue(TournamentStatistics.EffectiveBets(independent) > 20, TournamentStatistics.EffectiveBets(independent).ToString(System.Globalization.CultureInfo.InvariantCulture));
Assert.AreEqual(2.0, TournamentStatistics.EffectiveBets([one, new double[500]]), 1e-12);
Assert.AreEqual(0.0, TournamentStatistics.EffectiveBets([]));
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.EffectiveBets([one, new double[10]]));
}
/// <summary>
/// A rule with no edge, tried in a hundred variants on noise: the best one looks good alone, but against the common
/// number of trials and the variance of the field it never reaches the threshold of 0.90.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AStrategyWithNoEdgeTriedInOneHundredVariantsStaysBelowTheBar()
{
for (var seed = 1; seed <= 10; seed++)
{
var variants = Enumerable.Range(0, 100).Select(k => Synthetic.WalkReturns(1000, (seed * 1000) + k)).ToList();
var sharpes = variants.Select(v => Moments.Of(v).Sharpe).ToList();
var best = variants[sharpes.IndexOf(sharpes.Max())];
var variance = TournamentStatistics.FieldVariance([new FieldSharpes(365, sharpes)]);
var trials = TournamentStatistics.CommonTrials(100, 0, 0, 0);
var dsr = TournamentStatistics.CommonDeflated(best, 365, trials, variance);
Assert.AreEqual(100, dsr.Trials);
Assert.IsTrue(dsr.Value < 0.90, $"seed {seed}: DSR {dsr.Value}");
Assert.IsTrue(SharpeTests.Deflated(best, 1, 0).Value > dsr.Value, "Alone, the best variant looks better.");
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFieldVarianceIsTakenOnAnnualisedSharpes()
{
// A crypto contender (365 days a year) and a stock one (252): their daily Sharpes become annual before the
// variance, and the variance goes back to daily with the year of the series judged.
var field = new[] { new FieldSharpes(365, [0.05, 0.07]), new FieldSharpes(252, [0.05, 0.07]) };
double[] annual = [0.05 * Math.Sqrt(365), 0.07 * Math.Sqrt(365), 0.05 * Math.Sqrt(252), 0.07 * Math.Sqrt(252)];
var expected = Math.Pow(Moments.Of(annual).StandardDeviation, 2);
Assert.AreEqual(expected, TournamentStatistics.FieldVariance(field), 1e-15);
var returns = Synthetic.WalkReturns(500, 2, drift: 0.001);
var crypto = TournamentStatistics.CommonDeflated(returns, 365, 50, expected);
var stock = TournamentStatistics.CommonDeflated(returns, 252, 50, expected);
Assert.AreEqual(expected / 365, crypto.SharpeVariance, 1e-18);
Assert.AreEqual(expected / 252, stock.SharpeVariance, 1e-18);
Assert.IsTrue(stock.Benchmark > crypto.Benchmark, "Fewer days a year, a higher daily bar.");
Assert.AreEqual(0, TournamentStatistics.FieldVariance([new FieldSharpes(365, [0.05])]));
}
/// <summary>
/// Noise on two calendars, crypto every day and stocks on weekdays, put side by side with zero on the days without a
/// session: the probability of overfitting of the whole field is about one half. On average over forty seeds, because on
/// one seed alone it swings widely (from 0.14 to 0.54 on the first eight).
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCommonPboOnNoiseIsAboutOneHalf()
{
var values = new List<double>();
for (var seed = 1; seed <= 40; seed++)
{
var gen = new Gen(seed);
var everyDay = Enumerable.Range(0, 1100).Select(i => Monday.AddDays(i)).ToList();
var weekdays = everyDay.Where(d => d.DayOfWeek is not DayOfWeek.Saturday and not DayOfWeek.Sunday).ToList();
var series = new List<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)>();
for (var v = 0; v < 10; v++)
{
series.Add((everyDay, [.. everyDay.Select(_ => 0.01 * gen.Normal())]));
series.Add((weekdays, [.. weekdays.Select(_ => 0.01 * gen.Normal())]));
}
var aligned = TournamentStatistics.Align(series);
var pbo = TournamentStatistics.CommonOverfitting(aligned);
Assert.IsNotNull(pbo);
Assert.AreEqual(20, pbo.Variants);
Assert.AreEqual(12870, pbo.Combinations);
values.Add(pbo.Probability);
}
Assert.AreEqual(0.5, values.Average(), 0.1, string.Join(" ", values));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheBarGrowsWithTheTrials()
{
Assert.AreEqual(0, TournamentStatistics.Bar(1));
Assert.IsTrue(TournamentStatistics.Bar(10) < TournamentStatistics.Bar(100));
Assert.IsTrue(TournamentStatistics.Bar(100) < TournamentStatistics.Bar(1000));
Assert.AreEqual(SharpeTests.ExpectedMaximum(100, 1), TournamentStatistics.Bar(100));
// The best of a hundred tries of nothing stands about two and a half standard deviations above zero.
Assert.AreEqual(2.5, TournamentStatistics.Bar(100), 0.1);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void EightFinalistsGiveEightySevenCombinations()
{
// 28 pairs and the whole set, each with three weighting schemes.
Assert.AreEqual(87, TournamentStatistics.Combinations(8, 3));
Assert.AreEqual(6, TournamentStatistics.Combinations(2, 3));
Assert.AreEqual(0, TournamentStatistics.Combinations(1, 3));
Assert.AreEqual(0, TournamentStatistics.Combinations(0, 3));
Assert.AreEqual(500 + 87 + 40 + 27, TournamentStatistics.CommonTrials(500, 87, 40, 27));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.CommonTrials(-1, 0, 0, 0));
Assert.ThrowsExactly<OverflowException>(() => TournamentStatistics.CommonTrials(int.MaxValue, 1, 0, 0));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheIntervalContainsTheTrueMeanOfAKnownSeries()
{
var gen = new Gen(3);
var values = Enumerable.Range(0, 400).Select(_ => 0.05 + gen.Normal()).ToArray();
static double Mean(ReadOnlySpan<double> x)
{
var sum = 0.0;
foreach (var v in x)
{
sum += v;
}
return sum / x.Length;
}
var (low, high) = TournamentStatistics.Interval(values, Mean, block: 10, rounds: 2000, confidence: 0.95, seed: 1);
Assert.IsTrue(low < 0.05 && 0.05 < high, $"{low} – {high}");
Assert.IsTrue(high - low is > 0.1 and < 0.3, $"width {high - low}");
Assert.AreEqual((low, high), TournamentStatistics.Interval(values, Mean, 10, 2000, 0.95, 1), "The same seed gives the same interval.");
// Dependent data: each value ten times in a row. As many numbers as independent ones, ten times fewer facts.
var twins = values.SelectMany(v => Enumerable.Repeat(v, 10)).ToArray();
var independent = Enumerable.Range(0, twins.Length).Select(_ => 0.05 + gen.Normal()).ToArray();
var (tl, th) = TournamentStatistics.Interval(twins, Mean, 10, 2000, 0.95, 1);
var (il, ih) = TournamentStatistics.Interval(independent, Mean, 10, 2000, 0.95, 1);
Assert.IsTrue(th - tl > 1.8 * (ih - il), $"twins {th - tl}, independent {ih - il}");
// Fewer than three blocks: nothing can be said.
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), TournamentStatistics.Interval(values[..29], Mean, 10, 2000, 0.95, 1));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AlignmentPutsTheSeriesOnTheUnionOfTheirDaysWithZeroWhereThereIsNoSession()
{
// Crypto from Monday 1 January for ten days; a stock from Wednesday 3 January on weekdays to Friday 12.
var crypto = Enumerable.Range(0, 10).Select(i => Monday.AddDays(i)).ToList();
var stock = new[] { 2, 3, 4, 7, 8, 9, 10, 11 }.Select(i => Monday.AddDays(i)).ToList();
var aligned = TournamentStatistics.Align(
[
(crypto, [.. crypto.Select((_, i) => (i + 1) / 100.0)]),
(stock, [.. stock.Select((_, i) => -(i + 1) / 100.0)]),
]);
// The common window runs from the latest first day (3 January) to the earliest last day (10 January).
CollectionAssert.AreEqual(Enumerable.Range(2, 8).Select(i => Monday.AddDays(i)).ToArray(), aligned.Days.ToArray());
CollectionAssert.AreEqual(new[] { 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10 }, aligned.Returns[0]);
// Saturday 6 and Sunday 7 January: the stock has no session, its equity does not move.
CollectionAssert.AreEqual(new[] { -0.01, -0.02, -0.03, 0, 0, -0.04, -0.05, -0.06 }, aligned.Returns[1]);
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([(crypto, [0.1])]));
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([([Monday.AddDays(1), Monday], [0.1, 0.2])]));
Assert.IsEmpty(TournamentStatistics.Align([(crypto[..3], [0.1, 0.2, 0.3]), (crypto[5..], [0.1, 0.2, 0.3, 0.4, 0.5])]).Days);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SignsAreOnePerDayAndRepeatWithTheirSeed()
{
var signs = TournamentStatistics.Signs(1000, 7);
Assert.HasCount(1000, signs);
Assert.IsTrue(signs.All(s => s is 1 or -1));
Assert.IsTrue(signs.Count(s => s > 0) is > 450 and < 550);
CollectionAssert.AreEqual(signs, TournamentStatistics.Signs(1000, 7));
CollectionAssert.AreNotEqual(signs, TournamentStatistics.Signs(1000, TournamentStatistics.ReplicaSeed(7, 1)));
Assert.AreEqual(10, TournamentStatistics.ReplicaSeed(7, 3));
Assert.AreEqual(int.MinValue, TournamentStatistics.ReplicaSeed(int.MaxValue, 1), "The seed wraps instead of failing.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheControlShareCountsTheReplicasAtLeastAsGood()
{
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(1.0, [0.0, 1.0, 2.0, 0.5]));
Assert.AreEqual(0.0, TournamentStatistics.ControlShare(3.0, [0.0, 1.0, 2.0, 0.5]));
// Nothing to say is never a pass: an observed NaN fails, a NaN replica counts against.
Assert.AreEqual(1.0, TournamentStatistics.ControlShare(double.NaN, [0.0, 1.0]));
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(3.0, [double.NaN, 1.0]));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.ControlShare(1.0, []));
}
}
+873
View File
@@ -0,0 +1,873 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The tournament of the strategies (issues #123 and #125, criteria 2 and 6 of Phase 13): a plan written before any result,
/// the trials of the contenders on the search window, the finalists, the final tract opened once, the control against
/// chance and the common statistics, on synthetic series whose nature is known in advance.
/// </summary>
[TestClass]
public sealed class TournamentTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 0, 0, TimeSpan.Zero);
/// <summary>Warm-up of 450 days before the search, as every trial reads.</summary>
private static readonly DateOnly SearchFrom = Synthetic.Start.AddDays(TrialData.WarmupDays);
private static readonly Dictionary<string, IReadOnlyList<decimal>> OneGrid = new() { ["lookback"] = [20m], ["entry"] = [1m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> EdgeGrid = new() { ["lookback"] = [20m], ["entry"] = [1.5m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> NoiseGrid = new() { ["lookback"] = [20m, 40m, 60m], ["entry"] = [0.5m, 1m, 1.5m] };
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePlanIsWrittenBeforeAnyResultAndNeverChanges()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// A plan that breaks a rule is refused in Italian and leaves nothing behind.
var good = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
(TournamentRequest Request, string Message)[] wrong =
[
(good with { Name = " " }, "Dai un nome al campionato."),
(good with { Contenders = [] }, "Serve almeno un concorrente."),
(good with { Contenders = [good.Contenders[0], good.Contenders[0]] }, "L'etichetta «a» è usata due volte."),
(good with { Contenders = [good.Contenders[0] with { Group = "" }] }, "Il concorrente «a» ha bisogno di un gruppo e di un mercato."),
(good with { Contenders = [good.Contenders[0] with { Strategy = "nessuna" }] }, "Concorrente «a»: strategia sconosciuta."),
(good with { HoldoutFrom = good.Contenders[0].To.AddDays(-10) }, "Il tratto finale di «a» deve durare almeno 30 giorni: i suoi dati finiscono il 04/01/2021."),
(good with { HoldoutFrom = SearchFrom }, "Il tratto finale deve cominciare dopo l'inizio di «a», che comincia il 27/03/2019."),
(good with { Control = new TournamentControl(19, 1) }, "Le ripetizioni del controllo contro il caso vanno da 20 a 10000."),
(good with { Contenders = [good.Contenders[0] with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["lookback"] = [5m] } }] },
"Concorrente «a»: Giorni della media: i valori vanno da 10 a 400."),
(good with { PriorCounted = [new PriorCount("docs/backtests", "crypto_trend", -1)] },
"Le prove già contate hanno bisogno di una strategia e di un numero non negativo di varianti."),
];
foreach (var (request, message) in wrong)
{
var error = await Assert.ThrowsExactlyAsync<TournamentPlanException>(() => lab.PlanTournamentAsync(request, _none)).ConfigureAwait(false);
Assert.AreEqual(message, error.Message);
}
Assert.AreEqual(0, await CountAsync(test, "tournaments").ConfigureAwait(false));
Assert.AreEqual(0, await CountAsync(test, "backtest_trials").ConfigureAwait(false));
// The plan and the trials of its contenders are written together, before anything runs or is read.
var tournament = await lab.PlanTournamentAsync(good, _none).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Planned, tournament.Status);
Assert.IsTrue(tournament.PlanIntact);
var before = await RawPlanAsync(test, tournament.Id).ConfigureAwait(false);
Assert.AreEqual(TrialPlan.Hash(before.Plan), before.Hash);
var plan = tournament.Plan;
Assert.AreEqual(TournamentThresholds.Default, plan.Thresholds);
Assert.AreEqual(0.05, plan.Thresholds.MaxControlShare);
Assert.AreEqual(TrialThresholds.Default.MinDeflatedSharpe, plan.Thresholds.MinDeflatedSharpe);
CollectionAssert.AreEqual(new[] { 1m, 2m, 3m }, plan.CostMultipliers.ToArray());
Assert.AreEqual(new TournamentFinalists(8, "group_and_market", "walk_forward_sharpe"), plan.Finalists);
Assert.AreEqual(180, plan.Combinations.LookbackDays);
CollectionAssert.AreEqual(new[] { "equal", "inverse_volatility", "risk_parity" }, plan.Combinations.WeightSchemes.ToArray());
Assert.AreEqual(27, plan.PriorCounted.Sum(p => p.Variants));
Assert.AreEqual(18, plan.PriorCounted.Single(p => p.Strategy == "crypto_trend").Variants);
Assert.IsNotEmpty(plan.StressWindows);
Assert.AreEqual(TrialValidation.Default, plan.Validation);
Assert.AreEqual(Now, plan.WrittenAt);
Assert.AreEqual(0, plan.RegistryVariantsAtPlanning);
Assert.AreEqual(1 + 1 + TournamentStatistics.Combinations(2, 3) + 27, plan.PlannedTrials, "N planned: the variants, the combinations of two finalists, what was tried before.");
Assert.AreEqual(TournamentStatistics.Bar(plan.PlannedTrials), plan.Bar);
Assert.IsGreaterThan(2.0, plan.Bar, "The plan shows the bar before the start.");
Assert.AreEqual(TournamentPlan.FromJson(before.Plan).ToJson(), before.Plan, "The stored plan is its own text.");
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(2, trials);
var trialPlans = new List<(string Plan, string Hash)>();
foreach (var trial in trials)
{
Assert.AreEqual(tournament.Id, trial.TournamentId);
Assert.AreEqual(TrialStatuses.Planned, trial.Status);
Assert.AreEqual(good.HoldoutFrom.AddDays(-1), trial.Plan.Data.To, "A contender's trial never reads the final tract.");
Assert.IsNull(await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false));
trialPlans.Add(await RawTrialPlanAsync(test, trial.Id).ConfigureAwait(false));
}
CollectionAssert.AreEqual(new[] { "EAA-EUR" }, trials[0].Plan.Data.Symbols.ToArray());
Assert.AreEqual(0, await CountAsync(test, "tournament_units").ConfigureAwait(false), "No result exists yet.");
Assert.IsEmpty(field.Reads, "No data was read yet.");
Assert.IsNull(await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false));
// The contenders run, the tournament is judged; the plans have not changed by a byte.
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
Assert.AreEqual(before, await RawPlanAsync(test, tournament.Id).ConfigureAwait(false), "The plan text and its hash are never updated.");
for (var i = 0; i < trials.Count; i++)
{
Assert.AreEqual(trialPlans[i], await RawTrialPlanAsync(test, trials[i].Id).ConfigureAwait(false));
}
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(before.Hash, report.PlanHash);
Assert.AreEqual(tournament.Id, report.TournamentId);
// The units of the tournament lose their outcomes when it ends: the rows stay as a record.
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
Assert.IsNotEmpty(units);
Assert.IsTrue(units.All(u => u.Status == TrialUnitStatuses.Done && !u.HasOutcome));
CollectionAssert.IsSubsetOf(new[] { "variant", "control", "holdout" }, units.Select(u => u.Kind).Distinct().ToArray());
// A plan changed after it was written no longer gives its hash: the tournament is not judged.
var tampered = await lab.PlanTournamentAsync(good with { Contenders = [good.Contenders[0] with { Symbols = ["XYZ-EUR"] }] }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", tampered.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.IsFalse(refused.PlanIntact);
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
StringAssert.Contains(refused.Error, "impronta");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFinalTractIsReadOnce()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// a and b share a group and a market: only the better of the two goes on. c has its own.
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g1", "m1", ["NAA-EUR"], OneGrid), ("c", "g2", "m1", ["NAB-EUR"], OneGrid));
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
CollectionAssert.AreEquivalent(new[] { "a", "c" }, done.Finalists!.ToArray());
CollectionAssert.AreEqual(done.Finalists!.ToArray(), report.Finalists.Select(f => f.Label).ToArray());
CollectionAssert.AreEqual(new[] { true, false, true }, report.Contenders.Select(c => c.Finalist).ToArray());
Assert.IsNotNull(done.HoldoutOpenedAt);
// The final tract was read once, only for the finalists; the trials read up to the day before it.
var tract = field.Reads.Where(r => r.To > request.HoldoutFrom.AddDays(-1)).ToList();
Assert.IsTrue(tract.All(r => r.From == request.HoldoutFrom), "Only the runs of the final tract read past the search.");
CollectionAssert.AreEquivalent(new[] { "EAA-EUR", "NAB-EUR" }, tract.SelectMany(r => r.Symbols).ToArray());
Assert.IsTrue(field.Reads.Where(r => r.Symbols.Contains("NAA-EUR")).All(r => r.To == request.HoldoutFrom.AddDays(-1)), "A contender that is not a finalist never sees it.");
// The finalists cannot change once the tract is open: a second opening gets back the first, at the first moment.
clock.Advance(TimeSpan.FromHours(1));
var again = await lab.Tournaments.OpenHoldoutAsync(tournament.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(done.Finalists!.ToArray(), again.Finalists.ToArray());
Assert.AreEqual(done.HoldoutOpenedAt, again.OpenedAt);
// A tournament judged is not judged again.
var reads = field.Reads.Count;
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(reads, field.Reads);
// On a fresh tournament the first opening writes, the second gets it back.
var store = lab.Tournaments;
var other = await lab.PlanTournamentAsync(request with { Name = "Altro" }, _none).ConfigureAwait(false);
var first = await store.OpenHoldoutAsync(other.Id, ["c", "a"], _none).ConfigureAwait(false);
clock.Advance(TimeSpan.FromHours(1));
var second = await store.OpenHoldoutAsync(other.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { "c", "a" }, first.Finalists.ToArray());
CollectionAssert.AreEqual(new[] { "c", "a" }, second.Finalists.ToArray());
Assert.AreEqual(first.OpenedAt, second.OpenedAt);
CollectionAssert.AreEqual(new[] { "c", "a" }, (await store.GetAsync(other.Id, _none).ConfigureAwait(false))!.Finalists!.ToArray());
}
/// <summary>
/// Criterion 6: a field built on purpose, two contenders with an edge (the reversion rule on prices that revert to their
/// mean) and four of noise (the same rule on random walks without drift), each in its own group and market so all six are
/// finalists, judged with 200 repetitions of the control. Only the two with an edge pass. The variance of the field is
/// mostly the gap between edge and noise when a third of the field has an edge, and the bar of 113 trials rises with
/// it: the edges here are searched less (one variant against nine), as in a real field where noise is most of the search.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFieldWithTwoEdgesAndFourNoisesPassesOnlyTheTwo()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
const int days = 2314;
var field = new SyntheticField();
foreach (var (symbol, seed) in new[] { ("EAA-EUR", 101), ("EAB-EUR", 102), ("EAC-EUR", 103), ("EBA-EUR", 201), ("EBB-EUR", 202), ("EBC-EUR", 203) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.MeanRevertingReturns(days, seed, halfLife: 2, volatility: 0.02), seed));
}
foreach (var (symbol, seed) in new[] { ("NAA-EUR", 301), ("NAB-EUR", 302), ("NAC-EUR", 303), ("NAD-EUR", 304) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.WalkReturns(days, seed, drift: 0, volatility: 0.02), seed));
}
using var lab = Lab(test, clock, field, workers: 4);
var to = Synthetic.Start.AddDays(days);
var holdoutFrom = to.AddDays(-364);
var request = new TournamentRequest("Campo costruito apposta",
[
Contender("bordo-1", "g1", "m1", ["EAA-EUR", "EAB-EUR", "EAC-EUR"], EdgeGrid, to),
Contender("bordo-2", "g2", "m2", ["EBA-EUR", "EBB-EUR", "EBC-EUR"], EdgeGrid, to),
Contender("rumore-1", "g3", "m3", ["NAA-EUR"], NoiseGrid, to),
Contender("rumore-2", "g4", "m4", ["NAB-EUR"], NoiseGrid, to),
Contender("rumore-3", "g5", "m5", ["NAC-EUR"], NoiseGrid, to),
Contender("rumore-4", "g6", "m6", ["NAD-EUR"], NoiseGrid, to),
], holdoutFrom, 10_000m);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
Assert.AreEqual(200, tournament.Plan.Control.Repetitions);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
var said = Describe(report);
Assert.HasCount(6, report.Finalists, said);
Assert.AreEqual(new TournamentTrialsCount(2 + (4 * 9), TournamentStatistics.Combinations(6, 3), 0, 27, 113), report.Trials, said);
Assert.AreEqual(TournamentStatistics.Bar(113), report.Bar);
CollectionAssert.AreEquivalent(new[] { "bordo-1", "bordo-2" }, report.Finalists.Where(f => f.Passed).Select(f => f.Label).ToArray(), said);
Assert.AreEqual(2, report.PassedCount);
Assert.IsTrue(report.Passed);
Assert.AreEqual(TrialVerdicts.Passed, done.Verdict);
foreach (var edge in report.Finalists.Where(f => f.Label.StartsWith("bordo", StringComparison.Ordinal)))
{
Assert.IsTrue(edge.Checks.All(c => c.Passed == true), said);
Assert.AreEqual(200, edge.Control.Repetitions);
Assert.IsTrue(edge.Control.Centred, "The daily engine only buys: its control turns around the mean.");
Assert.IsLessThanOrEqualTo(0.05, edge.Control.Share!.Value, said);
Assert.IsGreaterThan(0.0, edge.SharpeInterval.Low, said);
}
foreach (var noise in report.Finalists.Where(f => f.Label.StartsWith("rumore", StringComparison.Ordinal)))
{
Assert.IsFalse(noise.Passed, said);
Assert.IsLessThan(0.90, noise.DeflatedSharpe.Value, said);
}
Assert.IsLessThanOrEqualTo(0.40, report.Overfitting!.Probability, said);
Assert.AreEqual(38, report.Overfitting.Variants);
Assert.IsNotNull(report.EffectiveBets);
Assert.IsTrue(report.EffectiveBets is > 4 and <= 6, said);
Assert.AreEqual(TournamentReport.FromJson(report.ToJson()).ToJson(), report.ToJson());
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingDoesNotRedoFinishedControlUnits()
{
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
const int total = 2 * 20;
// The same tournament judged without a stop, for comparison.
TournamentReport whole;
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var reference = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, reference.Id).ConfigureAwait(false);
var json = await lab.Tournaments.ReportJsonAsync(reference.Id, _none).ConfigureAwait(false);
Assert.IsNotNull(json, (await lab.Tournaments.GetAsync(reference.Id, _none).ConfigureAwait(false))!.Error);
whole = TournamentReport.FromJson(json);
}
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The process stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
var before = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), before, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Judging, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
var symbols = trials.ToDictionary(t => t.Id, t => t.Plan.Data.Symbols[0]);
var finished = (await DoneControlsAsync(test, tournament.Id).ConfigureAwait(false)).Select(u => FormattableString.Invariant($"control {symbols[u.Trial]} {u.Key.Split(':')[1]}")).ToList();
Assert.IsGreaterThanOrEqualTo(5, finished.Count);
Assert.IsTrue(units.Where(u => u.Status == TrialUnitStatuses.Done).All(u => u.HasOutcome), "The tournament keeps its outcomes until it ends.");
Assert.IsFalse(field.Reads.Any(r => r.From == plan.HoldoutFrom), "The stop came before the final tract.");
// The next start judges it again: only the repetitions not finished run, the final tract is read once.
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(total - finished.Count, controls);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(controls, key, "A finished repetition does not run again: " + key);
}
CollectionAssert.AreEquivalent(controls.Concat(finished).ToArray(), controls.Concat(finished).Distinct().ToArray());
Assert.HasCount(total, controls.Concat(finished).Distinct().ToList(), "Every repetition of both finalists is done once.");
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList(), "Two finalists, plain and doubled costs.");
Assert.HasCount(2, field.Reads.Where(r => r.From == plan.HoldoutFrom).ToList(), "The final tract of each finalist is read once.");
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(Comparable(whole), Comparable(report));
}
}
/// <summary>
/// The repetitions of the control done before a stop by another build (or on other data) are not reused: the judge started
/// again runs every repetition, so the control of a finalist is never a mix of two engines.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingRunsAgainTheControlUnitsOfAnotherBuild()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The judge stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), [], replicas, p.Data.Symbols[0], null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.IsGreaterThanOrEqualTo(5, DoneControls(test, tournament.Id));
// They were computed by another build.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournament_units SET fingerprint = @f WHERE tournament_id = @t AND kind = @k", _none,
("f", "altra|2|build"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(2 * plan.Control.Repetitions, controls, "Every repetition runs again.");
Assert.HasCount(2 * plan.Control.Repetitions, controls.Distinct().ToList());
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList());
var fingerprints = await test.Db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT fingerprint FROM tournament_units WHERE tournament_id = @t AND kind = @k",
r => r.Text("fingerprint"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
Assert.HasCount(2, fingerprints, "One fingerprint for the search data of each finalist.");
Assert.IsTrue(fingerprints.All(f => f.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)));
}
/// <summary>
/// The plan of a tournament that no longer reads (changed by hand, or after an update that cannot read it) fails the
/// tournament with a reason in Italian, when its last contender finishes and when it is found being judged at a start; the
/// laboratory goes on with the rest of the queue.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnUnreadableTournamentPlanFailsTheTournamentAndTheQueueGoesOn()
{
const string Unreadable = "Il piano registrato del campionato non si può più leggere: il campionato non si giudica.";
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var broken = await lab.PlanTournamentAsync(request with { Name = "Illeggibile" }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan = @p WHERE id = @id", _none, ("p", new DbJson("[1]")), ("id", broken.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, broken.Id).ConfigureAwait(false);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
// Found being judged at a start: it fails again, and the trials of the queue run and are judged.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @j, error = NULL, finished_at = NULL WHERE id = @id", _none,
("j", TournamentStatuses.Judging), ("id", broken.Id)), _none).ConfigureAwait(false);
var good = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!.IsFinished && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var judged = (await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, judged.Status, judged.Error);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
}
/// <summary>
/// The database refuses every change of the tournament while its last contender finishes, so neither the judge nor the
/// record of its failure can write: the queue goes on, and the trial that comes back to it after the pause brings the
/// tournament to its judge, though the trial itself is finished.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ARequeuedFinishedContenderStillReachesTheJudge()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false);
await RefuseTournamentChangesAsync(test, true).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && clock.Waiting == 0 && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
Assert.AreEqual(1, clock.Waiting, "The queue waits before trying again.");
Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(trials[1].Id, _none).ConfigureAwait(false))!.Status);
Assert.AreEqual(TournamentStatuses.Running, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
// The database is back: after the pause the finished trial comes back to the queue and the tournament is judged.
await RefuseTournamentChangesAsync(test, false).ConfigureAwait(false);
clock.Advance(Laboratory.RetryDelay);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
}
/// <summary>
/// The judge checks that every contender trial is the one the plan of the tournament wrote: a trial plan changed by hand
/// (its hash no longer matches) or rewritten with its hash on another capital, grid, slippage, source or reference share
/// fails the tournament.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AContenderTrialWhosePlanChangedFailsTheTournament()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var tampered = await lab.PlanTournamentAsync(request with { Name = "Impronta" }, _none).ConfigureAwait(false);
var last = (await lab.Trials.OfTournamentAsync(tampered.Id, _none).ConfigureAwait(false))[1];
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", last.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
Assert.AreEqual("Il piano registrato della prova di «b» non corrisponde più alla sua impronta: il campionato non si giudica.", refused.Error);
(string Name, Func<TrialPlan, TrialPlan> Change)[] changes =
[
("Capitale", p => p with { InitialCapital = 20_000m }),
("Griglia", p => p with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["entry"] = [1m], ["lookback"] = [30m] } }),
("Slittamento", p => p with { Slippage = new SlippageTable(9m, 9m, 25m) }),
("Origine", p => p with { Data = p.Data with { Source = TrialSources.Research } }),
("Quota", p => p with { ReferenceShare = 0.5m }),
];
foreach (var (name, change) in changes)
{
var tournament = await lab.PlanTournamentAsync(request with { Name = name }, _none).ConfigureAwait(false);
var trial = (await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false))[1];
var json = change(trial.Plan).ToJson();
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan = @p, plan_hash = @h WHERE id = @id", _none,
("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("id", trial.Id)), _none).ConfigureAwait(false);
Assert.IsTrue((await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.PlanIntact, name);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var failed = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, failed.Status, name);
Assert.AreEqual("Le prove del campionato non corrispondono al suo piano.", failed.Error, name);
}
}
/// <summary>
/// The control compares the replicas with the Sharpe ratio of the contender's own trial: when its search data change
/// between that trial and the judge, the tournament fails instead of mixing the two.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SearchDataThatChangedAfterTheTrialFailTheTournament()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false);
// One bar of the search tract of «a» is corrected after its trial.
var bars = Synthetic.Bars(Synthetic.MeanRevertingReturns(1099, 11, halfLife: 2, volatility: 0.02), 11).ToList();
bars[500] = bars[500] with { Close = bars[500].Close * 1.01, High = Math.Max(bars[500].High, bars[500].Close * 1.01) };
field.Add("EAA-EUR", bars);
await lab.ProcessAsync(trials[1].Id, _none).ConfigureAwait(false);
var (status, error) = await StateAsync(test, tournament.Id).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Failed, status);
Assert.AreEqual("I dati di ricerca di «a» sono cambiati dopo la sua prova: il campionato non si giudica.", error);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFinalistsAreTheBestOfEachGroupAndMarketAndAtMostEight()
{
var golden = BacktestReport.FromJson(Fixture.Text(Path.Combine("golden", "sma_cross.report.json")));
var trialPlan = Laboratory.BuildPlan(LaboratoryTests.Request(), Now).Plan;
var contenders = new List<TournamentContender>();
var outcomes = new List<ContenderOutcome>();
void Add(string label, string group, string market, double? walkForward, string status = TrialStatuses.Done)
{
var contender = new TournamentContender(label, "sma_cross", "1", group, market, trialPlan.Grid, trialPlan.Data, 4);
contenders.Add(contender);
var trial = new Trial(Guid.NewGuid(), "sma_cross", "1", trialPlan, "h", 4, status, null, null, null, null, Now, Now, Now);
var report = status != TrialStatuses.Done ? null
: golden with { WalkForward = walkForward is { } s ? new ReportWalkForward([], 0, 0, s) : null };
outcomes.Add(new ContenderOutcome(contender, trial, report, []));
}
Add("a", "trend", "crypto", 0.5);
Add("b", "trend", "crypto", 0.9);
Add("c", "trend", "fx", 0.1);
Add("d", "reversion", "crypto", 0.9);
Add("e", "reversion", "crypto", 0.9);
Add("f", "momentum", "crypto", 2.0, TrialStatuses.Failed);
Add("g", "momentum", "crypto", null);
Add("h", "momentum", "fx", double.NaN);
Add("i", "g1", "m", 0.01);
Add("j", "g2", "m", 0.02);
Add("k", "g3", "m", 0.03);
Add("l", "g4", "m", 0.04);
Add("m", "g5", "m", 0.05);
Add("n", "g6", "m", -0.5);
var plan = TournamentPlans.BuildPlan(new TournamentRequest("x", [new ContenderRequest("z", "sma_cross", "g", "m", TrialSources.Database, Venues.Okx, ["BTC-EUR"],
trialPlan.Data.From, trialPlan.Data.To)], trialPlan.Data.To.AddDays(-60), 10_000m), Now, 0, StrategyCatalog.Find).Plan with
{ Contenders = contenders };
// Best of each pair first, ties to the one written first; a failed trial, or one without walk-forward, never goes on.
CollectionAssert.AreEqual(new[] { "b", "d", "c", "m", "l", "k", "j", "i" }, TournamentJudge.Finalists(plan, outcomes).ToArray());
CollectionAssert.AreEqual(new[] { "b", "d", "c" }, TournamentJudge.Finalists(plan with { Finalists = plan.Finalists with { Max = 3 } }, outcomes).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AControlUnitKeepsOnlyItsSharpeAndItsKeyNamesTheRepetition()
{
var parameters = ReversionFamily.With(20, 1.5m).ToString();
var control = new TrialUnitKey(TrialUnitKind.Control, 7, parameters, 1m);
var holdout = new TrialUnitKey(TrialUnitKind.Holdout, 0, parameters, 2m);
Assert.AreEqual("control:7:entry=1.5;lookback=20:x1", control.Text);
Assert.AreEqual("holdout:0:entry=1.5;lookback=20:x2", holdout.Text);
foreach (var sharpe in new[] { -0.0123456789012345, 0.0, 0.1 + 0.2, double.Epsilon })
{
var back = TrialUnitOutcomes.Decode(control, TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null) { Sharpe = sharpe }));
Assert.AreEqual(sharpe, back.Sharpe);
Assert.IsNull(back.Run);
Assert.IsNull(back.LookAhead);
}
Assert.ThrowsExactly<InvalidOperationException>(() => TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportOfATournamentRoundTrips()
{
var checks = new List<ReportCheck>
{
new(ReportCheckKeys.DeflatedSharpe, "Deflated Sharpe Ratio sul numero comune di prove", 0.93, "≥", 0.9, "ratio", true),
new(TournamentCheckKeys.Control, "Controllo contro il caso: quota di copie pari o migliori", null, "≤", 0.05, "ratio", false),
};
var report = new TournamentReport(
Guid.Parse("01938a6e-0000-7000-8000-000000000001"),
"Campionato",
"abc",
new TournamentTrialsCount(40, 48, 3, 27, 118),
2.6,
0.123456789,
new ReportOverfitting(16, 12870, 40, 0.1),
4.5,
[
new TournamentContenderResult("a", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Done, 2, "entry=1;lookback=20", 0.1, true),
new TournamentContenderResult("b", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Failed, 9, null, null, false) { Error = "Strumento sconosciuto" },
],
[
new TournamentFinalistResult("a", ReversionFamily.FamilyId, "g", "m", "entry=1;lookback=20", 365, 0.2,
new DeflatedSharpe(0.2, 0.1, 1500, 0.8, 5.5, 118, 0.0027, 0.93), new ReportInterval(double.NegativeInfinity, double.PositiveInfinity), 1234.5678m, 0.12, true,
new TournamentControlResult(200, 7, true, 0.2, null, null, null) { Unavailable = Surrogates.CorporateActionsRefused },
new TournamentHoldoutResult(new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31), 100.10m, 90.05m, 0.01, 0.05, 0.02), checks, false),
],
0,
false,
["Una limitazione."],
Now,
1.5);
var json = report.ToJson();
Assert.AreEqual(json, TournamentReport.FromJson(json).ToJson());
foreach (var name in new[] { "\"passed_count\":", "\"field_variance\":", "\"effective_bets\":", "\"sharpe_interval\":", "\"net_at_double_costs\":", "\"unavailable\":", "\"walk_forward_sharpe\":" })
{
StringAssert.Contains(json, name);
}
StringAssert.Contains(json, "\"low\":\"-Infinity\"");
Assert.AreEqual(1234.5678m, TournamentReport.FromJson(json).Finalists[0].NetAtDoubleCosts);
}
/// <summary>The figures a resumed judge must give again: everything but the identities and the seconds.</summary>
private static string Comparable(TournamentReport report) =>
(report with { TournamentId = Guid.Empty, Seconds = 0, Contenders = [.. report.Contenders.Select(c => c with { TrialId = Guid.Empty })] }).ToJson();
private static string Describe(TournamentReport report) => string.Join(" | ", report.Finalists.Select(f => FormattableString.Invariant(
$"{f.Label}: S={f.Sharpe:F4} dsr={f.DeflatedSharpe.Value:F3} sr0={f.DeflatedSharpe.Benchmark:F4} share={f.Control.Share} net2={f.NetAtDoubleCosts:F0} dd={f.MaxDrawdown:F3} hold2={f.Holdout.NetAtDoubleCosts:F0} [{f.SharpeInterval.Low:F3},{f.SharpeInterval.High:F3}] failed:{string.Join(",", f.Checks.Where(c => c.Passed != true).Select(c => c.Key))}")))
+ FormattableString.Invariant($" | pbo={report.Overfitting?.Probability} var={report.FieldVariance:F4} bets={report.EffectiveBets:F2}");
/// <summary>A short field: 1100 days a series, a final tract of 100 days.</summary>
private static SyntheticField Small()
{
var field = new SyntheticField();
field.Add("EAA-EUR", Synthetic.Bars(Synthetic.MeanRevertingReturns(1099, 11, halfLife: 2, volatility: 0.02), 11));
field.Add("NAA-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 12, volatility: 0.02), 12));
field.Add("NAB-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 13, volatility: 0.02), 13));
return field;
}
private static TournamentRequest SmallRequest(params (string Label, string Group, string Market, string[] Symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> Grid)[] contenders)
{
var to = Synthetic.Start.AddDays(1099);
return new TournamentRequest("Campionato di prova", [.. contenders.Select(c => Contender(c.Label, c.Group, c.Market, c.Symbols, c.Grid, to))], to.AddDays(-99), 10_000m)
{
Control = new TournamentControl(20, 20_261_204),
};
}
private static ContenderRequest Contender(string label, string group, string market, string[] symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> grid, DateOnly to) =>
new(label, ReversionFamily.FamilyId, group, market, TrialSources.Database, Venues.Okx, symbols, SearchFrom, to, grid);
private static Laboratory Lab(TestDb test, IClock clock, SyntheticField field, int workers = 1) =>
new(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers))
{
Families = id => id == ReversionFamily.FamilyId ? ReversionFamily.Instance : StrategyCatalog.Find(id),
DataFor = field.LoadAsync,
};
/// <summary>Runs the trials of a tournament in the order of its plan: the last one brings it to its judge.</summary>
private static async Task RunAllAsync(Laboratory lab, Guid tournament)
{
foreach (var trial in await lab.Trials.OfTournamentAsync(tournament, _none).ConfigureAwait(false))
{
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
}
}
private static async Task<int> CountAsync(TestDb test, string table) =>
(int)await test.Db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT COUNT(*) AS n FROM {table}", r => r.Number("n")), _none).ConfigureAwait(false);
private static int DoneControls(TestDb test, Guid tournament) =>
(int)test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT COUNT(*) AS n FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d", r => r.Number("n"),
("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).GetAwaiter().GetResult();
private static async Task<IReadOnlyList<(Guid Trial, string Key)>> DoneControlsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT trial_id, unit_key FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d",
r => (r.Id("trial_id"), r.Text("unit_key")), ("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).ConfigureAwait(false);
private static async Task<IReadOnlyList<TrialUnitRow>> AllUnitsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT unit_key, kind, status, outcome, seconds, tournament_id FROM tournament_units WHERE tournament_id = @t ORDER BY id",
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), r.IdOrNull("tournament_id")),
("t", tournament)), _none).ConfigureAwait(false);
/// <summary>State and error of a tournament, read without its plan.</summary>
private static Task<(string Status, string? Error)> StateAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT status, error FROM tournaments WHERE id = @id", r => (r.Text("status"), r.TextOrNull("error")), ("id", id)));
/// <summary>Makes the database refuse, or accept again, every change of a row of the tournaments: a trigger on both engines.</summary>
private static Task RefuseTournamentChangesAsync(TestDb test, bool refuse) => test.Db.WriteAsync(async s =>
{
string[] statements = (test.Db.Engine, refuse) switch
{
(DbEngine.Sqlite, true) => ["CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments BEGIN SELECT RAISE(ABORT, 'database non raggiungibile'); END"],
(DbEngine.Sqlite, false) => ["DROP TRIGGER refuse_tournaments"],
(_, true) =>
[
"CREATE FUNCTION refuse_tournaments() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'database non raggiungibile'; END $$",
"CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments FOR EACH ROW EXECUTE FUNCTION refuse_tournaments()",
],
(_, false) => ["DROP TRIGGER refuse_tournaments ON tournaments", "DROP FUNCTION refuse_tournaments()"],
};
foreach (var sql in statements)
{
await s.ExecuteAsync(sql, _none).ConfigureAwait(false);
}
}, _none);
private static Task<(string Plan, string Hash)> RawPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM tournaments WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
private static Task<(string Plan, string Hash)> RawTrialPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM backtest_trials WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
/// <summary>The signs of a surrogate as text, to tell which repetition an engine was given.</summary>
private static string SignsOf(DaySigns signs) =>
string.Concat(Enumerable.Range(0, Math.Min(signs.Count, 256)).Select(i => signs[signs.First.AddDays(i)] > 0 ? '+' : '-'));
/// <summary>Synthetic series by symbol, read as the laboratory reads data (from the warm-up to the last day asked), with every read recorded.</summary>
private sealed class SyntheticField
{
private readonly Dictionary<string, IReadOnlyList<DailyBar>> _bars = new(StringComparer.Ordinal);
private readonly List<TrialData> _reads = [];
public IReadOnlyList<TrialData> Reads
{
get
{
lock (_reads)
{
return [.. _reads];
}
}
}
public void Add(string symbol, IReadOnlyList<DailyBar> bars) => _bars[symbol] = bars;
public Task<BacktestDataset> LoadAsync(TrialData data, CancellationToken cancellationToken)
{
lock (_reads)
{
_reads.Add(data);
}
var from = data.HistoryStart();
var instruments = data.Symbols.Select(s => new BacktestInstrument(Synthetic.Coin(s),
[.. (_bars.GetValueOrDefault(s) ?? throw new InvalidOperationException("Strumento sconosciuto: " + s)).Where(b => b.Day >= from && b.Day <= data.To)],
source: "sintetico"));
return Task.FromResult(new BacktestDataset(instruments, "EUR"));
}
}
/// <summary>An engine in between: it records the runs on surrogates (with the repetition their signs belong to) and on the final tract.</summary>
private sealed class CountingEngine(ITrialEngine inner, List<string> calls, IReadOnlyDictionary<string, int> replicas, string name, string? tag, Action<int>? onControl = null) : ITrialEngine
{
private readonly Counter _controls = new();
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public bool LongOnly => inner.LongOnly;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
if (tag is not null)
{
Record(FormattableString.Invariant($"{tag} x{costMultiplier}"));
}
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark() => inner.Benchmark();
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => inner.LookAhead(parameters, cuts);
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
public ITrialEngine Surrogate(DaySigns signs, bool centred)
{
var surrogate = inner.Surrogate(signs, centred);
return replicas.TryGetValue(SignsOf(signs), out var k)
? new CountingEngine(surrogate, calls, replicas, name, FormattableString.Invariant($"control {name} {k}"), onControl) { Parent = this }
: surrogate;
}
private CountingEngine? Parent { get; init; }
private void Record(string call)
{
lock (calls)
{
calls.Add(call.Split(' ')[0] == "control" ? call.Split(" x")[0] : call);
}
if (call.StartsWith("control", StringComparison.Ordinal))
{
onControl?.Invoke((Parent ?? this)._controls.Next());
}
}
}
private sealed class Counter
{
private int _value;
public int Next() => Interlocked.Increment(ref _value);
}
}
+477
View File
@@ -0,0 +1,477 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The units of a trial and the pool of the laboratory (Phase 13, issue #122): the judge works on runs already done, assembled
/// by key, so one thread, four threads and units read back from the database give the same report as the golden ones; a trial
/// stopped halfway runs again only what it had not finished.
/// </summary>
[TestClass]
public sealed class TrialUnitTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12");
private static readonly DateOnly Through = new(2026, 12, 31);
private static readonly TrialUnitKey RunKey = new(TrialUnitKind.Variant, 0, "", 1m);
private static readonly TrialUnitKey LookKey = new(TrialUnitKind.LookAhead, 0, "", 1m);
private sealed record Golden(string Name, TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data, PriorTrials Prior)
{
public string Hash => TrialPlan.Hash(Plan.ToJson());
public DailyTrialEngine Engine() => new(Plan, Family, Data);
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task JudgeOfVariantsGivesTheJsonOfRun()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task FourWorkersGiveTheReportOfOne()
{
using var pool = new LowPriorityPool("anubis-test-four", 4);
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = await TrialRunner.VariantsAsync(golden.Plan, golden.Family, engine, new PooledTrialUnits(pool), null, _none).ConfigureAwait(false);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task ARunReloadedFromItsStoredUnitGivesTheSameReport()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
var reloaded = new TrialRuns(
runs.Variants,
[.. runs.Grid.Select(Again)],
runs.OutsideGrid is null ? null : Again(runs.OutsideGrid),
runs.Costed.ToDictionary(c => c.Key, c => Again(c.Value)),
Again(runs.Benchmark),
TrialUnitOutcomes.Decode(LookKey, TrialUnitOutcomes.Encode(new TrialUnitResult(LookKey, null, runs.LookAhead))).LookAhead!);
Assert.IsTrue(reloaded.Grid.All(r => r.Decisions.Count == 0), "The decisions are not kept: only the look-ahead check reads them.");
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, reloaded, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AStoredUnitIsTheSameBytesWhenWrittenAgain()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: Through.AddDays(-399)));
var run = BacktestEngine.Run(new MovingAverageCross(5, 20), data);
var stored = TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null));
var back = TrialUnitOutcomes.Decode(RunKey, stored).Run!;
CollectionAssert.AreEqual(stored, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, back, null)));
Assert.AreEqual(run.Fees, back.Fees);
Assert.AreEqual(run.FinalEquity, back.FinalEquity);
CollectionAssert.AreEqual(run.Fills.ToList(), back.Fills.ToList());
CollectionAssert.AreEqual(run.Trades.ToList(), back.Trades.ToList());
CollectionAssert.AreEqual(run.Notes.ToList(), back.Notes.ToList());
Assert.IsTrue(stored.Length < 200_000, "The outcome is compressed.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheKeyOfAUnitIsTheSameTextInEveryCulture()
{
var before = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
Assert.AreEqual("variant:3:a=1;kind=0:x1", new TrialUnitKey(TrialUnitKind.Variant, 3, "a=1;kind=0", 1m).Text);
Assert.AreEqual("costed:0:a=1;kind=0:x2", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1;kind=0", 2.00m).Text);
Assert.AreEqual("costed:0:a=1:x1.5", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1", 1.50m).Text);
Assert.AreEqual("outside_grid:0:a=4;kind=1:x1", new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, "a=4;kind=1", 1m).Text);
Assert.AreEqual("benchmark:0::x1", new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m).Text);
Assert.AreEqual("look_ahead", new TrialUnitKey(TrialUnitKind.LookAhead, 0, "a=1", 1m).KindText);
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnOneWorkerThePoolCallsTheEngineInTheOrderOfToday()
{
var (plan, family, data) = SmallCross();
var inline = new List<string>();
var sequential = TrialRunner.Variants(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), inline));
using var pool = new LowPriorityPool("anubis-test-one", 1);
var pooled = new List<string>();
var parallel = await TrialRunner.VariantsAsync(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), pooled), new PooledTrialUnits(pool),
null, _none).ConfigureAwait(false);
Assert.HasCount(4 + 2 + 2, inline);
CollectionAssert.AreEqual(inline, pooled);
StringAssert.StartsWith(inline[^1], "look_ahead ");
Assert.AreEqual("benchmark", inline[^2]);
var inlineUnits = await TrialRunner.VariantsAsync(plan, family, new DailyTrialEngine(plan, family, data), InlineTrialUnits.Instance, null, _none).ConfigureAwait(false);
var hash = TrialPlan.Hash(plan.ToJson());
var one = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), sequential, PriorTrials.None, Now, TimeSpan.Zero).Report;
foreach (var other in new[] { parallel, inlineUnits })
{
var report = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), other, PriorTrials.None, Now, TimeSpan.Zero).Report;
Assert.AreEqual((one with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AUnitThatFailsStopsTheOnesNotYetStartedAndItsErrorComesBack()
{
var (plan, family, data) = SmallCross();
using var pool = new LowPriorityPool("anubis-test-fail", 1);
var calls = new List<string>();
var engine = new RecordingEngine(new DailyTrialEngine(plan, family, data), calls, _ => throw new InvalidOperationException("rotto"));
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => TrialRunner.VariantsAsync(plan, family, engine, new PooledTrialUnits(pool), null, _none))
.ConfigureAwait(false);
Assert.AreEqual("rotto", error.Message, "The error of the unit comes back, not the skip of the others.");
Assert.HasCount(1, calls, "After a failure the units still queued do not run.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ThePoolRunsOnNamedLowPriorityBackgroundThreadsAndFinishesWhatItWasGiven()
{
using var pool = new LowPriorityPool("anubis-test-pool", 2);
using var both = new Barrier(2);
(bool Together, string? Name, ThreadPriority Priority, bool Background) Probe() =>
(both.SignalAndWait(TimeSpan.FromSeconds(30)), Thread.CurrentThread.Name, Thread.CurrentThread.Priority, Thread.CurrentThread.IsBackground);
var seen = await Task.WhenAll(pool.RunAsync(Probe), pool.RunAsync(Probe)).ConfigureAwait(false);
Assert.AreEqual(2, pool.Workers);
Assert.IsTrue(seen.All(s => s.Together), "Two threads run two pieces of work at once.");
CollectionAssert.AreEquivalent(new[] { "anubis-test-pool-1", "anubis-test-pool-2" }, seen.Select(s => s.Name).ToArray());
Assert.IsTrue(seen.All(s => s.Priority == ThreadPriority.BelowNormal && s.Background));
await Assert.ThrowsAsync<ArithmeticException>(() => pool.RunAsync<int>(() => throw new ArithmeticException())).ConfigureAwait(false);
// Work handed over before the pool stops still runs; nothing more is taken; stopping twice is harmless.
using var release = new ManualResetEventSlim();
var slow = pool.RunAsync(() => release.Wait(TimeSpan.FromSeconds(30)));
var queued = pool.RunAsync(() => 7);
var stopping = Task.Run(pool.Dispose);
release.Set();
await stopping.ConfigureAwait(false);
Assert.IsTrue(await slow.ConfigureAwait(false));
Assert.AreEqual(7, await queued.ConfigureAwait(false));
Assert.Throws<InvalidOperationException>(() => pool.RunAsync(() => 1));
pool.Dispose();
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AfterAnInterruptionTheFinishedUnitsAreNotRunAgain()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
var workers = 1;
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers));
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TrialStatuses.Running, (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.Status);
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
var finished = rows.Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
var left = rows.Where(r => r.Status == TrialUnitStatuses.Running).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
Assert.IsNotEmpty(left, "The units claimed and not finished stay running.");
Assert.IsTrue(rows.All(r => r.Status != TrialUnitStatuses.Done || (r.HasOutcome && r.Seconds is >= 0)));
Assert.IsTrue(rows.All(r => r.TournamentId is null));
// The next start plans it again and runs only what was not finished, now on two threads.
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
workers = 2;
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total - finished.Count, second);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(second, CallOf(key), "A finished unit does not run again: " + key);
}
foreach (var key in left)
{
CollectionAssert.Contains(second, CallOf(key), "A unit left running runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
Assert.AreEqual(clock.UtcNow, report.ComputedAt);
// A trial outside a tournament keeps its units as a record, without their outcomes.
var after = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, after);
Assert.IsTrue(after.All(r => r.Status == TrialUnitStatuses.Done && !r.HasOutcome));
CollectionAssert.AreEquivalent(new[] { "variant", "costed", "benchmark", "look_ahead" }, after.Select(r => r.Kind).Distinct().ToArray());
Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials.");
}
/// <summary>
/// A trial stopped halfway whose bars change before the next start (a bar collected again, a corporate action): the units
/// done on the old bars are not reused, every unit runs again on the new ones and the report is that of a run without a stop.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task UnitsComputedOnOtherDataAreRunAgainOnResume()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var btc = await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var before = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
var finished = (await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false)).Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
// The bars are collected again with other prices before the next start.
await new BarStore(test.Db, clock).UpsertDailyAsync(btc.Id, BacktestData.Walk(400, 4, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)),
"test", _none).ConfigureAwait(false);
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
Assert.AreNotEqual(before.Fingerprint(), data.Fingerprint());
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total, second, "Every unit runs again on the new bars.");
foreach (var key in finished)
{
CollectionAssert.Contains(second, CallOf(key), "A unit done on the old bars runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
// Every unit keeps what it was computed on: the new bars, the engine and this build.
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, rows);
Assert.IsTrue(rows.All(r => r.Fingerprint == data.Fingerprint() + TrialUnitStore.Build), string.Join(", ", rows.Select(r => r.Fingerprint)));
StringAssert.StartsWith(TrialUnitStore.Build, "|" + BacktestEngine.Version + "|");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors()
{
var workers = LaboratorySettings.Workers;
Assert.AreEqual("laboratory.workers", workers.Key);
Assert.AreEqual("1", workers.Default);
Assert.AreEqual("Operai del Laboratorio", workers.Label);
Assert.AreSame(workers, SettingsStore.Definition(workers.Key));
var max = Math.Max(1, Environment.ProcessorCount - 1);
Assert.AreEqual(max, LaboratorySettings.MaxWorkers);
Assert.IsNull(workers.Check!("1"));
Assert.IsNull(workers.Check(max.ToString(CultureInfo.InvariantCulture)));
foreach (var wrong in new[] { "0", (max + 1).ToString(CultureInfo.InvariantCulture), "", "due", "1.5", "-1", "+2", " 2" })
{
Assert.AreEqual($"Serve un numero intero tra 1 e {max}.", workers.Check(wrong), wrong);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWorkersOfTheLaboratoryAreSetInTheSystemSettings()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Operai del Laboratorio");
StringAssert.Contains(page, "Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta.");
StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading");
StringAssert.Contains(page, "Vale dalla prossima prova.");
async Task<string> Save(string value)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LaboratorySettings.Workers.Key, ("ritorno", "/impostazioni#sistema"), ("valore", value));
return ServerHarness.Location(answer);
}
var settings = server.Host.Services!.Settings;
Assert.AreEqual("/impostazioni#sistema", await Save("1"));
Assert.AreEqual(1, await LaboratorySettings.WorkersAsync(settings, _none));
StringAssert.Contains(await Save("0"), "errore=operai");
StringAssert.Contains(await Save((LaboratorySettings.MaxWorkers + 1).ToString(CultureInfo.InvariantCulture)), "errore=operai");
StringAssert.Contains(await Save("tanti"), "errore=operai");
Assert.AreEqual("1", (await settings.GetAsync(LaboratorySettings.Workers.Key, _none)).Value);
StringAssert.Contains(await server.TextAsync("/impostazioni?errore=operai#sistema"), "Gli operai del Laboratorio sono un numero intero da 1 a");
}
private static BacktestRun Again(BacktestRun run) => TrialUnitOutcomes.Decode(RunKey, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null))).Run!;
/// <summary>The call of the recording engine a unit key stands for.</summary>
private static string CallOf(string key)
{
var parts = key.Split(':');
return parts[0] switch
{
"benchmark" => "benchmark",
"look_ahead" => $"look_ahead {parts[2]} {TrialValidation.Default.LookAheadCuts}",
_ => $"run {parts[2]} {parts[3]}",
};
}
private static (TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data) SmallCross()
{
var first = new DateOnly(2024, 1, 1);
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: first));
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
first.AddDays(60), first.AddDays(399), 10_000m, grid), Now).Plan;
return (plan, MovingAverageCrossFamily.Instance, data);
}
/// <summary>The inputs of the three golden reports of <see cref="TrialSeamTests"/>, built the same way.</summary>
private static async Task<IReadOnlyList<Golden>> GoldensAsync()
{
var walk = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03));
var cross = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan;
var folder = TempFolder.Create("golden-units");
try
{
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);
}
var trend = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow,
CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan;
var data = await Laboratory.LoadResearchAsync(folder, trend.Data, _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(StrategyNames.CryptoTrend)!;
return
[
new("sma_cross", cross, MovingAverageCrossFamily.Instance, walk, new PriorTrials(2, 18, [0.4, 0.9, -0.1])),
new("crypto_trend", trend, family, data, PriorTrials.None),
new("crypto_trend_judged", trend with { Judged = "coin_vol=12;max_stop=15" }, family, data, PriorTrials.None),
];
}
finally
{
TempFolder.Delete(folder);
}
}
private static void Same(string name, BacktestReport report) =>
Assert.AreEqual(Fixture.Text(Path.Combine("golden", name + ".report.json")), (report with { Seconds = 0 }).ToJson(), $"The report of {name} changed.");
/// <summary>An engine in between: it records every call (safe from several threads) and may act on the n-th one.</summary>
private sealed class RecordingEngine(ITrialEngine inner, List<string> calls, Action<int>? onCall = null) : ITrialEngine
{
private int _count;
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
Record(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark()
{
Record("benchmark");
return inner.Benchmark();
}
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
Record(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
return inner.LookAhead(parameters, cuts);
}
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
private void Record(string call)
{
lock (calls)
{
calls.Add(call);
}
onCall?.Invoke(Interlocked.Increment(ref _count));
}
}
}