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

+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;
-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, []));
}
}