diff --git a/src/Anubis/Backtest/Surrogates.cs b/src/Anubis/Backtest/Surrogates.cs new file mode 100644 index 0000000..736f371 --- /dev/null +++ b/src/Anubis/Backtest/Surrogates.cs @@ -0,0 +1,196 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Backtest; + +/// +/// One sign a calendar day, +1 or −1, from 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. +/// +public sealed class DaySigns +{ + private readonly int[] _signs; + + public DaySigns(DateOnly first, IReadOnlyList 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]; + } + + /// The day of the first sign. + public DateOnly First { get; } + + /// How many days have a sign. + public int Count => _signs.Length; + + /// The day of the last sign ( when there is none). + public DateOnly Last => First.AddDays(Math.Max(_signs.Length - 1, 0)); + + /// The sign of ; a day outside the signs is an error, never a default. + 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]; + } + } + + /// The signs of every calendar day from to , drawn with . + 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)); + } +} + +/// +/// 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. +/// +/// +/// 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. +/// 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. +/// +public static class Surrogates +{ + /// The message of the refusal, for the user. + public const string CorporateActionsRefused = "Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie."; + + /// + /// 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. + /// + public static double[] Flip(IReadOnlyList logReturns, IReadOnlyList 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; + } + + /// The surrogate of every instrument of , with signs drawn from over its calendar days. + 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); + } + + /// The surrogate of every instrument of , the ones read only as data included, with the given signs. + 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); + } + + /// The surrogate of one instrument's bars, oldest first, one per day. + public static IReadOnlyList Bars(IReadOnlyList 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(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; +} diff --git a/src/Anubis/Backtest/TournamentStatistics.cs b/src/Anubis/Backtest/TournamentStatistics.cs new file mode 100644 index 0000000..73c4744 --- /dev/null +++ b/src/Anubis/Backtest/TournamentStatistics.cs @@ -0,0 +1,294 @@ +using Anubis.Core; + +namespace Anubis.Backtest; + +/// The returns of several series on one calendar: [k][d] is the return of series k on [d]. +public sealed record AlignedReturns(IReadOnlyList Days, IReadOnlyList Returns); + +/// The daily Sharpe ratios of every variant of one contender, and the sessions in its year (365 crypto, 252 stocks and currencies). +public sealed record FieldSharpes(int PeriodsPerYear, IReadOnlyList DailySharpes); + +/// +/// 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. +/// +public static class TournamentStatistics +{ + /// + /// 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 + /// docs/backtests). Nothing is taken away: a failed contender still counts. + /// + 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); + } + + /// + /// 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. + /// + 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); + } + + /// + /// The bar the plan shows before the start: the Sharpe ratio the best of tries of nothing would + /// show by chance alone, in standard deviations of the field. Zero for one trial. + /// + public static double Bar(int trials) => SharpeTests.ExpectedMaximum(trials, 1); + + /// + /// 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. + /// + public static AlignedReturns Align(IReadOnlyList<(IReadOnlyList Days, IReadOnlyList 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())]); + } + + 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(calendar.Count); + for (var i = 0; i < calendar.Count; i++) + { + position[calendar[i]] = i; + } + + var aligned = new List(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); + } + + /// + /// 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. + /// + public static double FieldVariance(IReadOnlyList field) + { + ArgumentNullException.ThrowIfNull(field); + var annual = new List(); + 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; + } + + /// + /// 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). + /// + public static DeflatedSharpe CommonDeflated(ReadOnlySpan returns, int periodsPerYear, int trials, double fieldVariance) + { + ArgumentOutOfRangeException.ThrowIfLessThan(periodsPerYear, 1); + ArgumentOutOfRangeException.ThrowIfNegative(fieldVariance); + return SharpeTests.Deflated(returns, trials, fieldVariance / periodsPerYear); + } + + /// + /// The probability of overfitting of the whole field (CSCV, ): every variant of every + /// contender, on one calendar. Null when it cannot be computed (fewer than two variants or too few days). + /// + public static OverfittingResult? CommonOverfitting(AlignedReturns aligned, int groups = 16) + { + ArgumentNullException.ThrowIfNull(aligned); + return Validation.Overfitting(aligned.Returns, groups); + } + + /// + /// The seed of repetition of the control: the plan's seed plus the repetition, wrapping + /// around instead of failing, so repetition k always draws the same signs. + /// + public static int ReplicaSeed(int seed, int repetition) + { + ArgumentOutOfRangeException.ThrowIfNegative(repetition); + return unchecked(seed + repetition); + } + + /// + /// The signs of a surrogate: one per calendar day, +1 or −1 with the same probability, drawn in order from + /// with . Every instrument takes the sign of its day. + /// + 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; + } + + /// + /// 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. + /// + public static double ControlShare(double observed, IReadOnlyList 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; + } + + /// + /// A bootstrap interval of that keeps neighbouring days together: each of + /// resamples is made of blocks of 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 Learning.Judge.Interval. With fewer than three + /// blocks nothing can be said: the interval is everything. + /// + public static (double Low, double High) Interval(IReadOnlyList returns, Func, 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))]); + } + + /// + /// 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. + /// + public static double EffectiveBets(IReadOnlyList 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; + } +} diff --git a/src/Anubis/Core/SeededRandom.cs b/src/Anubis/Core/SeededRandom.cs new file mode 100644 index 0000000..ac26284 --- /dev/null +++ b/src/Anubis/Core/SeededRandom.cs @@ -0,0 +1,101 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Anubis.Core; + +/// +/// A fixed-seed generator based on SplitMix64 (Steele, Lea and Flood, 2014). Unlike a seeded , 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. +/// +/// +/// Two older generators stay as they are, because their outputs are recorded: Learning.FixedRandom (same stream, +/// but its Next multiplies instead of rejecting) and Backtest.PathBootstrap (a seeded , +/// whose results are in the committed outcome files). +/// +[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); + + /// The next 64 bits of SplitMix64. + public ulong NextUInt64() + { + var z = _state += 0x9E3779B97F4A7C15UL; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; + return z ^ (z >> 31); + } + + /// Uniform integer in [, ), without bias (rejection sampling). + 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)); + } + + /// Uniform integer in [, ). + public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive); + + /// True or false with the same probability: the lowest bit of the next draw. + public bool Bool() => (NextUInt64() & 1UL) == 1UL; + + /// Uniform value in [0, 1). + public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53)); + + /// A standard normal value (Box–Muller, cosine branch, two draws per value), for synthetic prices and returns. + 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); + } + + /// A decimal in [, ] with at most decimals, uniform on that grid. + 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; + } + + /// One of , each with the same probability. + public T Pick(IReadOnlyList items) + { + ArgumentNullException.ThrowIfNull(items); + ArgumentOutOfRangeException.ThrowIfZero(items.Count); + return items[Int(0, items.Count)]; + } +} diff --git a/tests/Anubis.Tests/GlobalUsings.cs b/tests/Anubis.Tests/GlobalUsings.cs new file mode 100644 index 0000000..2f8cc0c --- /dev/null +++ b/tests/Anubis.Tests/GlobalUsings.cs @@ -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; diff --git a/tests/Anubis.Tests/Property.cs b/tests/Anubis.Tests/Property.cs index 51bbca6..dc45eaa 100644 --- a/tests/Anubis.Tests/Property.cs +++ b/tests/Anubis.Tests/Property.cs @@ -29,87 +29,3 @@ internal static class Property } } } - -/// -/// Fixed-seed generator based on SplitMix64. Unlike a seeded , its sequence is -/// fixed by this code, so it stays the same on every platform and .NET version. -/// -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); - } - - /// Uniform integer in [, ). - 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; - - /// Uniform value in [0, 1). - public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53)); - - /// A standard normal value (Box–Muller), for synthetic price series and returns. - 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); - } - - /// A decimal in [, ] with at most decimals. - 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(IReadOnlyList items) - { - ArgumentOutOfRangeException.ThrowIfZero(items.Count); - return items[Int(0, items.Count)]; - } -} diff --git a/tests/Anubis.Tests/SurrogateTests.cs b/tests/Anubis.Tests/SurrogateTests.cs new file mode 100644 index 0000000..44d9117 --- /dev/null +++ b/tests/Anubis.Tests/SurrogateTests.cs @@ -0,0 +1,180 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// 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. +/// +[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 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(() => 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(() => 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); + } + + /// + /// 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. + /// + [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)}"); + } + + /// + /// 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. + /// + [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)}"); + } +} diff --git a/tests/Anubis.Tests/Synthetic.cs b/tests/Anubis.Tests/Synthetic.cs new file mode 100644 index 0000000..7813a25 --- /dev/null +++ b/tests/Anubis.Tests/Synthetic.cs @@ -0,0 +1,273 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// 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. +/// +internal static class Synthetic +{ + public static readonly DateOnly Start = new(2018, 1, 1); + + /// A coin quoted in euro on OKX, traded every day: the synthetic series live on it. + 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", + }; + + /// The autoregressive coefficient of a daily series whose distance from its mean halves in bars. + public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife); + + /// + /// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the + /// and the series started at its level. The return of day t is x(t) − x(t−1). + /// + 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; + } + + /// Log returns of a random walk: plus normal noise, no memory. + 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; + } + + /// Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ. + 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; + } + + /// Two series of returns with correlation about : a common part and a part of each. + 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); + } + + /// + /// Daily bars from log returns of the close: the first bar at , 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. + /// + public static IReadOnlyList Bars(IReadOnlyList 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(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; + } + + /// A dataset in euro of synthetic coins, one per series of bars. + public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList Bars)[] series) => + new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR"); + + /// A mean-reverting coin: returns of turned into bars. + 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))); + + /// Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed. + 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)))]); + + /// Several independent coins walking at random with the same , each from its own seed. + 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)))]); + + /// The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR… + public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR"); + + /// A coin that walks at random with a a day (zero for pure noise). + 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))); + + /// Log returns of the closes of a series of bars, one per bar after the first. + public static double[] CloseReturns(IReadOnlyList 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))]; + } + + /// Pearson correlation of two series of the same length. + public static double Correlation(IReadOnlyList x, IReadOnlyList 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); + } + + /// Autocorrelation at lag one. + public static double LagOne(IReadOnlyList x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]); + + /// The daily Sharpe ratio of a run: what the control compares between the real series and its replicas. + public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe; + + /// + /// The control of a rule on a dataset: its daily Sharpe on the real data, and on + /// surrogates whose signs come from + k. Returns the observed Sharpe, the replicas and the + /// share of replicas at least as good. + /// + 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)); + } +} + +/// +/// A test-only reversion rule, long only: it buys an instrument when its close falls entry standard deviations +/// below the mean of the last lookback 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. +/// +internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy +{ + /// Bars it waits for before the first decision; until lookback bars, the mean is of those there are. + public const int MinimumBars = 50; + + public string Id => ReversionFamily.FamilyId; + + public string Version => "1"; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) => context.Available; + + public IReadOnlyList Decide(StrategyContext context) + { + var intents = new List(); + 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; + } +} + +/// The family of : the window of the mean and the distance of the entry. +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 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"]); + } + + /// The parameters of a variant, as the laboratory would build them. + public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]); +} diff --git a/tests/Anubis.Tests/TournamentStatisticsTests.cs b/tests/Anubis.Tests/TournamentStatisticsTests.cs new file mode 100644 index 0000000..6600c6e --- /dev/null +++ b/tests/Anubis.Tests/TournamentStatisticsTests.cs @@ -0,0 +1,218 @@ +using Anubis.Backtest; + +namespace Anubis.Tests; + +/// +/// 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. +/// +[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(() => TournamentStatistics.EffectiveBets([one, new double[10]])); + } + + /// + /// 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. + /// + [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])])); + } + + /// + /// 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). + /// + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCommonPboOnNoiseIsAboutOneHalf() + { + var values = new List(); + 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 Days, IReadOnlyList 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(() => TournamentStatistics.CommonTrials(-1, 0, 0, 0)); + Assert.ThrowsExactly(() => 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 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(() => TournamentStatistics.Align([(crypto, [0.1])])); + Assert.ThrowsExactly(() => 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(() => TournamentStatistics.ControlShare(1.0, [])); + } +}