Add the tournament statistics and the surrogate series of the control
ci / test (postgres) (push) Successful in 7m30s
ci / test (sqlite) (push) Successful in 5m52s
ci / image (push) Successful in 2m8s

The championship judge needs statistics the single-trial protocol does not
have: one common number of trials for the whole field and the bar it sets,
a field variance taken on annualised Sharpe ratios so crypto and weekday
markets compare, the common probability of overfitting on one calendar,
the effective number of bets, a block-bootstrap interval and the control
against chance. The control replays a rule on surrogate prices where every
day all instruments change sign together, centred on the mean for
long-only rules, so sizes, tails and correlations stay while any tendency
to revert or to go on is lost. Instruments with corporate actions are
refused for now.

The seeded SplitMix64 generator of the tests moves to Anubis.Core as
SeededRandom, unchanged, so the control and the intervals draw from it;
the tests keep calling it Gen through a global alias.

refs #124

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 13:07:14 +01:00
1 parent b564871391
commit 8967575d2c
8 files changed
+1264 -84

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
using System.Globalization;
using Anubis.Data;
namespace Anubis.Backtest;
/// <summary>
/// One sign a calendar day, +1 or −1, from <see cref="First"/> on: the same sign for every instrument on the same day. Two
/// datasets that must share their signs (the contenders of one tournament) draw them from the same first day and seed.
/// </summary>
public sealed class DaySigns
{
private readonly int[] _signs;
public DaySigns(DateOnly first, IReadOnlyList<int> signs)
{
ArgumentNullException.ThrowIfNull(signs);
if (signs.Any(s => s is not (1 or -1)))
{
throw new ArgumentException("A sign is +1 or −1.", nameof(signs));
}
First = first;
_signs = [.. signs];
}
/// <summary>The day of the first sign.</summary>
public DateOnly First { get; }
/// <summary>How many days have a sign.</summary>
public int Count => _signs.Length;
/// <summary>The day of the last sign (<see cref="First"/> when there is none).</summary>
public DateOnly Last => First.AddDays(Math.Max(_signs.Length - 1, 0));
/// <summary>The sign of <paramref name="day"/>; a day outside the signs is an error, never a default.</summary>
public int this[DateOnly day]
{
get
{
var at = day.DayNumber - First.DayNumber;
if (at < 0 || at >= _signs.Length)
{
throw new ArgumentOutOfRangeException(nameof(day), day, "No sign for this day.");
}
return _signs[at];
}
}
/// <summary>The signs of every calendar day from <paramref name="first"/> to <paramref name="last"/>, drawn with <see cref="TournamentStatistics.Signs"/>.</summary>
public static DaySigns Draw(DateOnly first, DateOnly last, int seed)
{
ArgumentOutOfRangeException.ThrowIfLessThan(last, first);
return new DaySigns(first, TournamentStatistics.Signs(last.DayNumber - first.DayNumber + 1, seed));
}
}
/// <summary>
/// The surrogate series of the control against chance (ADR 0026 point 4; appendix G.5 of the research document of
/// 2 December 2026): every day the returns of all the instruments change sign together, with probability one half. The
/// size of every day, the tails and the correlations between instruments stay; every tendency to revert or to go on is
/// lost. The strategy is then run again on the surrogate prices.
/// </summary>
/// <remarks>
/// <para>The work is on log returns from the previous close: open, high, low and close of day t, each as l = ln(p / close of
/// t − 1). With the sign s of the day, l becomes s·l, or μ + s·(l − μ) when centred, μ being the mean daily log return of
/// the instrument's closes over the loaded bars. Centred is for long-only rules: the drift stays, so a rule that only rides
/// it does as well on the surrogates as on the real data. When s = −1 the high and the low swap.</para>
/// <para>The first bar of each instrument stays as it is, the volume does not change, the value traded follows the close.
/// The surrogate covers the whole loaded history, the warm-up included. It is deterministic: no culture, no clock.
/// Instruments with corporate actions are refused for now.</para>
/// </remarks>
public static class Surrogates
{
/// <summary>The message of the refusal, for the user.</summary>
public const string CorporateActionsRefused = "Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.";
/// <summary>
/// The surrogate of a series of log returns: each one times the sign of its position, or, centred, around the mean of
/// the series. The absolute value of every return (centred: its distance from the mean) is kept exactly.
/// </summary>
public static double[] Flip(IReadOnlyList<double> logReturns, IReadOnlyList<int> signs, bool centred)
{
ArgumentNullException.ThrowIfNull(logReturns);
ArgumentNullException.ThrowIfNull(signs);
if (signs.Count < logReturns.Count)
{
throw new ArgumentException("One sign for every return.", nameof(signs));
}
var mean = centred && logReturns.Count > 0 ? logReturns.Average() : 0;
var result = new double[logReturns.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = Flip(logReturns[i], signs[i], centred, mean);
}
return result;
}
/// <summary>The surrogate of every instrument of <paramref name="data"/>, with signs drawn from <paramref name="seed"/> over its calendar days.</summary>
public static BacktestDataset Of(BacktestDataset data, int seed, bool centred)
{
ArgumentNullException.ThrowIfNull(data);
var days = data.Instruments.Where(i => i.Bars.Count > 0).ToList();
var signs = days.Count == 0
? new DaySigns(DateOnly.MinValue, [])
: DaySigns.Draw(days.Min(i => i.Bars[0].Day), days.Max(i => i.Bars[^1].Day), seed);
return Of(data, signs, centred);
}
/// <summary>The surrogate of every instrument of <paramref name="data"/>, the ones read only as data included, with the given signs.</summary>
public static BacktestDataset Of(BacktestDataset data, DaySigns signs, bool centred)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(signs);
if (data.Instruments.Any(i => i.Actions.Count > 0))
{
throw new NotSupportedException(CorporateActionsRefused);
}
return new BacktestDataset(
data.Instruments.Select(i => new BacktestInstrument(i.Spec, Bars(i.Bars, signs, centred), [], i.Source)),
data.Currency,
data.Calendar,
data.DataOnly);
}
/// <summary>The surrogate of one instrument's bars, oldest first, one per day.</summary>
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<DailyBar> bars, DaySigns signs, bool centred)
{
ArgumentNullException.ThrowIfNull(bars);
ArgumentNullException.ThrowIfNull(signs);
if (bars.Count == 0)
{
return [];
}
for (var i = 0; i < bars.Count; i++)
{
var b = bars[i];
if (!(b.Open > 0 && b.High > 0 && b.Low > 0 && b.Close > 0) || !double.IsFinite(b.Open + b.High + b.Low + b.Close))
{
throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture,
$"Il controllo contro il caso vuole prezzi positivi: la barra del {b.Day:yyyy-MM-dd} ne ha uno che non lo è."));
}
if (i > 0 && b.Day <= bars[i - 1].Day)
{
throw new ArgumentException("The bars must be in order of day, one a day.", nameof(bars));
}
}
var mean = 0.0;
if (centred && bars.Count > 1)
{
for (var i = 1; i < bars.Count; i++)
{
mean += Math.Log(bars[i].Close / bars[i - 1].Close);
}
mean /= bars.Count - 1;
}
var result = new List<DailyBar>(bars.Count) { bars[0] };
var previous = bars[0].Close;
var made = bars[0].Close;
for (var i = 1; i < bars.Count; i++)
{
var bar = bars[i];
var s = signs[bar.Day];
double Price(double p) => made * Math.Exp(Flip(Math.Log(p / previous), s, centred, mean));
var open = Price(bar.Open);
var close = Price(bar.Close);
var (high, low) = s > 0 ? (Price(bar.High), Price(bar.Low)) : (Price(bar.Low), Price(bar.High));
high = Math.Max(high, Math.Max(open, close));
low = Math.Min(low, Math.Min(open, close));
result.Add(bar with
{
Open = open,
High = high,
Low = low,
Close = close,
QuoteVolume = bar.QuoteVolume is { } value ? value * (close / bar.Close) : null,
Adjusted = null,
});
previous = bar.Close;
made = close;
}
return result;
}
private static double Flip(double l, int sign, bool centred, double mean) =>
centred ? mean + (sign * (l - mean)) : sign * l;
}
+294
View File
@@ -0,0 +1,294 @@
using Anubis.Core;
namespace Anubis.Backtest;
/// <summary>The returns of several series on one calendar: <see cref="Returns"/>[k][d] is the return of series k on <see cref="Days"/>[d].</summary>
public sealed record AlignedReturns(IReadOnlyList<DateOnly> Days, IReadOnlyList<double[]> Returns);
/// <summary>The daily Sharpe ratios of every variant of one contender, and the sessions in its year (365 crypto, 252 stocks and currencies).</summary>
public sealed record FieldSharpes(int PeriodsPerYear, IReadOnlyList<double> DailySharpes);
/// <summary>
/// The statistics of the tournament (ADR 0026, Phase 13), pure and written in house: one number of trials for the whole
/// field, the bar it sets, the variance of the field, the probability of overfitting of every variant together, the effective
/// number of bets, the control against chance and a bootstrap interval that keeps neighbouring days together. Each function
/// computes one thing from its arguments; none reads a clock or a database.
/// </summary>
public static class TournamentStatistics
{
/// <summary>
/// The common number of trials N of the deflated Sharpe ratio: every variant of every contender, every combination of
/// finalists, every variant already in the register and every variant tried before outside it (the protocols of
/// <c>docs/backtests</c>). Nothing is taken away: a failed contender still counts.
/// </summary>
public static int CommonTrials(int fieldVariants, int combinations, int registryVariants, int priorCounted)
{
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariants);
ArgumentOutOfRangeException.ThrowIfNegative(combinations);
ArgumentOutOfRangeException.ThrowIfNegative(registryVariants);
ArgumentOutOfRangeException.ThrowIfNegative(priorCounted);
return checked(fieldVariants + combinations + registryVariants + priorCounted);
}
/// <summary>
/// The combinations of finalists the plan counts: every pair and the whole set, each with every weighting scheme. Eight
/// finalists and three schemes give (28 + 1) × 3 = 87; fewer than two finalists give none.
/// </summary>
public static int Combinations(int finalists, int weightSchemes)
{
ArgumentOutOfRangeException.ThrowIfNegative(finalists);
ArgumentOutOfRangeException.ThrowIfNegative(weightSchemes);
return finalists < 2 ? 0 : checked(((finalists * (finalists - 1) / 2) + 1) * weightSchemes);
}
/// <summary>
/// The bar the plan shows before the start: the Sharpe ratio the best of <paramref name="trials"/> tries of nothing would
/// show by chance alone, in standard deviations of the field. Zero for one trial.
/// </summary>
public static double Bar(int trials) => SharpeTests.ExpectedMaximum(trials, 1);
/// <summary>
/// Puts series of different calendars on one: the union of their days inside the common window, from the latest first day
/// to the earliest last day. A day without a session for a series is a return of zero, because its equity does not move
/// (crypto trades every day, stocks and currencies on weekdays). Each series gives its days in increasing order and one
/// return per day.
/// </summary>
public static AlignedReturns Align(IReadOnlyList<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)> series)
{
ArgumentNullException.ThrowIfNull(series);
foreach (var (days, returns) in series)
{
ArgumentNullException.ThrowIfNull(days);
ArgumentNullException.ThrowIfNull(returns);
if (days.Count != returns.Count)
{
throw new ArgumentException("Every series needs one return per day.", nameof(series));
}
for (var i = 1; i < days.Count; i++)
{
if (days[i] <= days[i - 1])
{
throw new ArgumentException("The days of a series must be in increasing order, each once.", nameof(series));
}
}
}
if (series.Count == 0 || series.Any(s => s.Days.Count == 0))
{
return new AlignedReturns([], [.. series.Select(_ => Array.Empty<double>())]);
}
var first = series.Max(s => s.Days[0]);
var last = series.Min(s => s.Days[^1]);
var calendar = series.SelectMany(s => s.Days).Where(d => d >= first && d <= last).Distinct().Order().ToList();
var position = new Dictionary<DateOnly, int>(calendar.Count);
for (var i = 0; i < calendar.Count; i++)
{
position[calendar[i]] = i;
}
var aligned = new List<double[]>(series.Count);
foreach (var (days, returns) in series)
{
var values = new double[calendar.Count];
for (var i = 0; i < days.Count; i++)
{
if (position.TryGetValue(days[i], out var at))
{
values[at] = returns[i];
}
}
aligned.Add(values);
}
return new AlignedReturns(calendar, aligned);
}
/// <summary>
/// The variance of the field: the sample variance of the annual Sharpe ratios (daily × √P) of every variant of every
/// contender, so that a crypto year of 365 days and a stock year of 252 are compared in the same unit. Variants counted
/// before the tournament count in N but not here, because their ratios are not all kept: the field is the variance.
/// Zero with fewer than two variants.
/// </summary>
public static double FieldVariance(IReadOnlyList<FieldSharpes> field)
{
ArgumentNullException.ThrowIfNull(field);
var annual = new List<double>();
foreach (var contender in field)
{
ArgumentNullException.ThrowIfNull(contender);
ArgumentOutOfRangeException.ThrowIfLessThan(contender.PeriodsPerYear, 1);
var root = Math.Sqrt(contender.PeriodsPerYear);
annual.AddRange(contender.DailySharpes.Select(s => s * root));
}
var deviation = Moments.Of([.. annual]).StandardDeviation;
return deviation * deviation;
}
/// <summary>
/// The deflated Sharpe ratio of one contender against the whole field: its daily returns (Sharpe, length, skewness and
/// kurtosis), the common number of trials and the variance of the field brought back to daily with the contender's own
/// year (annual variance / P).
/// </summary>
public static DeflatedSharpe CommonDeflated(ReadOnlySpan<double> returns, int periodsPerYear, int trials, double fieldVariance)
{
ArgumentOutOfRangeException.ThrowIfLessThan(periodsPerYear, 1);
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariance);
return SharpeTests.Deflated(returns, trials, fieldVariance / periodsPerYear);
}
/// <summary>
/// The probability of overfitting of the whole field (CSCV, <see cref="Validation.Overfitting"/>): every variant of every
/// contender, on one calendar. Null when it cannot be computed (fewer than two variants or too few days).
/// </summary>
public static OverfittingResult? CommonOverfitting(AlignedReturns aligned, int groups = 16)
{
ArgumentNullException.ThrowIfNull(aligned);
return Validation.Overfitting(aligned.Returns, groups);
}
/// <summary>
/// The seed of repetition <paramref name="repetition"/> of the control: the plan's seed plus the repetition, wrapping
/// around instead of failing, so repetition k always draws the same signs.
/// </summary>
public static int ReplicaSeed(int seed, int repetition)
{
ArgumentOutOfRangeException.ThrowIfNegative(repetition);
return unchecked(seed + repetition);
}
/// <summary>
/// The signs of a surrogate: one per calendar day, +1 or −1 with the same probability, drawn in order from
/// <see cref="SeededRandom"/> with <paramref name="seed"/>. Every instrument takes the sign of its day.
/// </summary>
public static int[] Signs(int days, int seed)
{
ArgumentOutOfRangeException.ThrowIfNegative(days);
var random = new SeededRandom(seed);
var signs = new int[days];
for (var i = 0; i < days; i++)
{
signs[i] = random.Bool() ? 1 : -1;
}
return signs;
}
/// <summary>
/// The share of replicas on surrogate series that do as well as the real result or better: count(replica ≥ observed) /
/// count. The control passes when it is at most the plan's threshold (0.05: the real result beats at least 190 of 200).
/// What cannot be compared never helps: an observed NaN gives 1 and a NaN replica counts as at least as good.
/// </summary>
public static double ControlShare(double observed, IReadOnlyList<double> replicas)
{
ArgumentNullException.ThrowIfNull(replicas);
ArgumentOutOfRangeException.ThrowIfZero(replicas.Count);
if (double.IsNaN(observed))
{
return 1;
}
return (double)replicas.Count(r => double.IsNaN(r) || r >= observed) / replicas.Count;
}
/// <summary>
/// A bootstrap interval of <paramref name="statistic"/> that keeps neighbouring days together: each of
/// <paramref name="rounds"/> resamples is made of blocks of <paramref name="block"/> days in a row, starting at random
/// and going round the end of the series (circular moving blocks), until it is as long as the series. The bounds are the
/// percentiles of the sorted statistics, with the convention of <c>Learning.Judge.Interval</c>. With fewer than three
/// blocks nothing can be said: the interval is everything.
/// </summary>
public static (double Low, double High) Interval(IReadOnlyList<double> returns, Func<ReadOnlySpan<double>, double> statistic, int block, int rounds, double confidence, int seed)
{
ArgumentNullException.ThrowIfNull(returns);
ArgumentNullException.ThrowIfNull(statistic);
ArgumentOutOfRangeException.ThrowIfLessThan(block, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(rounds, 1);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(confidence);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(confidence, 1);
var n = returns.Count;
if (n < 3 * block)
{
return (double.NegativeInfinity, double.PositiveInfinity);
}
var random = new SeededRandom(seed);
var sample = new double[n];
var values = new double[rounds];
for (var r = 0; r < rounds; r++)
{
for (var filled = 0; filled < n;)
{
var start = random.Int(0, n);
for (var k = 0; k < block && filled < n; k++, filled++)
{
sample[filled] = returns[(start + k) % n];
}
}
values[r] = statistic(sample);
}
Array.Sort(values);
var tail = (1 - confidence) / 2;
return (values[(int)Math.Floor(tail * (rounds - 1))], values[(int)Math.Ceiling((1 - tail) * (rounds - 1))]);
}
/// <summary>
/// The effective number of independent bets among series on one calendar: the participation ratio of their correlation
/// matrix, n² / Σᵢⱼ ρᵢⱼ², which needs no eigenvalues (the trace of R is n, the trace of R² is Σρ²). Identical series are
/// one bet, uncorrelated series are n. A flat series is correlated only with itself.
/// </summary>
public static double EffectiveBets(IReadOnlyList<double[]> aligned)
{
ArgumentNullException.ThrowIfNull(aligned);
var n = aligned.Count;
if (n == 0)
{
return 0;
}
var length = aligned[0].Length;
if (aligned.Any(s => s is null || s.Length != length))
{
throw new ArgumentException("Every series needs the same days.", nameof(aligned));
}
// Centred series and their norms, once.
var centred = new double[n][];
var norms = new double[n];
for (var i = 0; i < n; i++)
{
var mean = length > 0 ? aligned[i].Average() : 0;
centred[i] = [.. aligned[i].Select(x => x - mean)];
norms[i] = Math.Sqrt(centred[i].Sum(x => x * x));
}
var squares = 0.0;
for (var i = 0; i < n; i++)
{
squares += 1; // ρᵢᵢ = 1, flat or not
for (var j = i + 1; j < n; j++)
{
if (norms[i] <= 0 || norms[j] <= 0)
{
continue;
}
var dot = 0.0;
for (var t = 0; t < length; t++)
{
dot += centred[i][t] * centred[j][t];
}
var rho = Math.Clamp(dot / (norms[i] * norms[j]), -1, 1);
squares += 2 * rho * rho;
}
}
return (double)n * n / squares;
}
}
+101
View File
@@ -0,0 +1,101 @@
using System.Diagnostics.CodeAnalysis;
namespace Anubis.Core;
/// <summary>
/// A fixed-seed generator based on SplitMix64 (Steele, Lea and Flood, 2014). Unlike a seeded <see cref="Random"/>, its
/// sequence is fixed by this code, so it stays the same on every platform and .NET version: a control, a bootstrap or a
/// synthetic series drawn from a seed repeats exactly. It moved here from the tests (Phase 13) without changing a bit of
/// its algorithm, so every series the tests drew before draws the same today.
/// </summary>
/// <remarks>
/// Two older generators stay as they are, because their outputs are recorded: <c>Learning.FixedRandom</c> (same stream,
/// but its <c>Next</c> multiplies instead of rejecting) and <c>Backtest.PathBootstrap</c> (a seeded <see cref="Random"/>,
/// whose results are in the committed outcome files).
/// </remarks>
[SuppressMessage("Naming", "CA1720", Justification = "Long, Int, Double and Decimal name what they draw; the tests have called them so since Phase 1.")]
public sealed class SeededRandom(int seed)
{
// The seed is sign-extended: seed −1 starts from 0xFFFF_FFFF_FFFF_FFFF, as it always did.
private ulong _state = unchecked((ulong)(long)seed);
/// <summary>The next 64 bits of SplitMix64.</summary>
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"/>), without bias (rejection sampling).</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));
}
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
/// <summary>True or false with the same probability: the lowest bit of the next draw.</summary>
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, cosine branch, two draws per value), for synthetic prices 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, uniform on that grid.</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("No value with this scale in the interval.", nameof(scale));
}
var steps = high - low;
if (steps >= long.MaxValue)
{
throw new ArgumentException("The interval is too wide for this scale.", nameof(scale));
}
var k = Long(0, (long)steps + 1);
return (low + k) * unit;
}
/// <summary>One of <paramref name="items"/>, each with the same probability.</summary>
public T Pick<T>(IReadOnlyList<T> items)
{
ArgumentNullException.ThrowIfNull(items);
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
return items[Int(0, items.Count)];
}
}