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>
181 lines
9.0 KiB
C#
181 lines
9.0 KiB
C#
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)}");
|
||
}
|
||
}
|