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>
219 lines
11 KiB
C#
219 lines
11 KiB
C#
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, []));
|
||
}
|
||
}
|