diff --git a/src/Anubis/Baskets/BasketIndex.cs b/src/Anubis/Baskets/BasketIndex.cs index 9a42b70..34cfd92 100644 --- a/src/Anubis/Baskets/BasketIndex.cs +++ b/src/Anubis/Baskets/BasketIndex.cs @@ -72,6 +72,165 @@ public static class BasketIndex return deviation is > 0 ? (index[t] - mean) / deviation : null; } + /// + /// The z-score of every bar of a series in one pass (Phase 14): at bar t, (x(t) − mean) / sample standard deviation + /// (n − 1) of the last values, bar t included — the same value as , to + /// about 1e-12. Not a number before the window is full and where the window is flat. The replica of appendix G and the + /// basket engine both read their signals here, so the two decide on the same bits. + /// + /// + /// Sums of the values minus an anchor slide one bar at a time; every bars they are computed + /// again from scratch around the exact mean of the window, so the rounding never piles up and far-from-zero levels lose + /// no digits. The series must be compressed: a missing value is an error, not a gap to skip. + /// + public static double[] RollingZ(IReadOnlyList x, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(x); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + var values = Compressed(x, nameof(x)); + var n = values.Length; + var z = new double[n]; + Array.Fill(z, double.NaN); + var sums = new SlidingSums(window); + var equal = 0; + for (var t = 0; t < n; t++) + { + equal = t > 0 && values[t] == values[t - 1] ? equal + 1 : 1; + if (t < window - 1) + { + continue; + } + + sums.Advance(values, t); + // A window whose values are all equal is flat by definition (as in ZScore): no z. + var variance = sums.CentredSquares() / (window - 1); + if (equal < window && variance > 0) + { + z[t] = sums.FromMean(values[t]) / Math.Sqrt(variance); + } + } + + return z; + } + + /// + /// σ of appendix G.3 at every bar: the population standard deviation (n) of the − 1 first + /// differences inside the last values, bar t included. Not a number before the window is + /// full; exactly zero when all those differences are equal. Same sliding sums as . + /// + public static double[] RollingSigma(IReadOnlyList x, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(x); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + var values = Compressed(x, nameof(x)); + var n = values.Length; + var sigma = new double[n]; + Array.Fill(sigma, double.NaN); + if (n < 2) + { + return sigma; + } + + var differences = new double[n - 1]; + for (var i = 1; i < n; i++) + { + differences[i - 1] = values[i] - values[i - 1]; + } + + var m = window - 1; + var sums = new SlidingSums(m); + var equal = 0; + for (var i = 0; i < differences.Length; i++) + { + equal = i > 0 && differences[i] == differences[i - 1] ? equal + 1 : 1; + if (i < m - 1) + { + continue; + } + + // The difference i ends at bar i + 1. + sums.Advance(differences, i); + sigma[i + 1] = equal >= m ? 0 : Math.Sqrt(Math.Max(sums.CentredSquares() / m, 0)); + } + + return sigma; + } + + /// The refusal of a series with a missing or infinite value: rolling signals read compressed series only. + public static void RequireCompressed(IReadOnlyList x, string parameter) => _ = Compressed(x, parameter); + + /// The series as an array (itself when it is one), refused when a value is missing or infinite. + private static double[] Compressed(IReadOnlyList x, string parameter) + { + ArgumentNullException.ThrowIfNull(x); + var values = x as double[] ?? [.. x]; + for (var t = 0; t < values.Length; t++) + { + if (!double.IsFinite(values[t])) + { + throw new ArgumentException($"La serie ha un buco (un valore mancante o non finito) alla barra {t}: va compressa, senza buchi.", parameter); + } + } + + return values; + } + + /// + /// The sums Σ(x − a) and Σ(x − a)² over the last count values, a being the anchor. They slide by one value at + /// every bar and are rebuilt exactly, around the exact mean of the window, every count bars. + /// + private sealed class SlidingSums(int count) + { + private double _anchor; + private double _sum; + private double _squares; + private int _sinceRebuild = -1; + + /// Moves the window so that it ends at ; the first call (and every count-th) rebuilds. + public void Advance(double[] values, int t) + { + if (_sinceRebuild < 0 || _sinceRebuild == count - 1) + { + Rebuild(values, t); + return; + } + + var added = values[t] - _anchor; + var removed = values[t - count] - _anchor; + _sum += added - removed; + _squares += (added * added) - (removed * removed); + _sinceRebuild++; + } + + /// Σ(x − mean)² of the window. + public double CentredSquares() => _squares - (_sum * _sum / count); + + /// x − mean of the window. + public double FromMean(double value) => value - _anchor - (_sum / count); + + private void Rebuild(double[] values, int t) + { + var from = t - count + 1; + var total = 0d; + for (var i = from; i <= t; i++) + { + total += values[i]; + } + + _anchor = total / count; + _sum = 0; + _squares = 0; + for (var i = from; i <= t; i++) + { + var d = values[i] - _anchor; + _sum += d; + _squares += d * d; + } + + _sinceRebuild = 0; + } + } + /// /// σ_short at bar : the sample standard deviation of the last first /// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter. diff --git a/src/Anubis/Baskets/StylisedReplica.cs b/src/Anubis/Baskets/StylisedReplica.cs new file mode 100644 index 0000000..df2a9fc --- /dev/null +++ b/src/Anubis/Baskets/StylisedReplica.cs @@ -0,0 +1,378 @@ +using System.Globalization; +using Anubis.Backtest; +using Anubis.Data; + +namespace Anubis.Baskets; + +/// +/// The parameters of the stylised replica of appendix G.3: target and averaging distance in σ of the series, the most +/// averagings, the growth of the distance, the basket stop in targets (none when null), the window of the z-score and of +/// σ, the entry threshold. +/// +public sealed record ReplicaSettings( + double TargetSigma, + double DistanceSigma, + int MaxAveragings, + double Growth = 1, + double? StopTargets = null, + int Window = BasketIndex.DefaultWindow, + double EntryZ = 2) +{ + /// + /// The 15 cases of the «Forex 1999–2026» column of table G.4, in the document's order: five parameter sets, each with no + /// stop, a stop of 90 and one of 30 targets. + /// + public static IReadOnlyList DocumentCases { get; } = Array.AsReadOnly(BuildCases()); + + /// Checks the values; the message is for the user. + public void Validate() + { + if (!(TargetSigma > 0) || !(DistanceSigma >= 0) || MaxAveragings < 0 || !(Growth > 0) || Window < 3 || !(EntryZ > 0) + || (StopTargets is { } stop && !(stop > 0))) + { + throw new ArgumentException(string.Create(CultureInfo.InvariantCulture, + $"Parametri della replica non validi: obiettivo {TargetSigma}σ, distanza {DistanceSigma}σ, mediazioni {MaxAveragings}, crescita {Growth}, arresto {StopTargets}, finestra {Window}, ingresso {EntryZ}.")); + } + } + + private static ReplicaCase[] BuildCases() + { + (string Label, double Target, double Distance, int Averagings, double Growth)[] sets = + [ + ("2,5 σ · 10 σ · 3", 2.5, 10, 3, 1), + ("2 σ · 8 σ · 3", 2, 8, 3, 1), + ("3 σ · 12 σ · 3", 3, 12, 3, 1), + ("2,5 σ · 4 σ · 3", 2.5, 4, 3, 1), + ("2,5 σ · 4 σ crescente · 4", 2.5, 4, 4, 1.3), + ]; + (string Label, double? Targets)[] stops = [("nessuno", null), ("90 obiettivi", 90), ("30 obiettivi", 30)]; + double[] totals = [534, 542, 255, 757, 1_032, -98, 338, 534, 137, 649, 442, -45, 533, 759, 172]; + double[] breakEvens = [0.32, 0.26, 0.11, 0.39, 0.40, -0.03, 0.24, 0.33, 0.07, 0.33, 0.16, -0.01, 0.25, 0.25, 0.05]; + var cases = new List(); + foreach (var set in sets) + { + foreach (var stop in stops) + { + var i = cases.Count; + cases.Add(new ReplicaCase(set.Label, stop.Label, + new ReplicaSettings(set.Target, set.Distance, set.Averagings, set.Growth, stop.Targets), totals[i], breakEvens[i])); + } + } + + return [.. cases]; + } +} + +/// +/// One row of table G.4: the parameters, the labels as the document writes them, its total in targets and its break-even +/// per position. A row is binding when |total| > 100 targets: ours must have the same sign and stay within the larger of +/// 25 targets and 5% of the document's total. +/// +public sealed record ReplicaCase(string Label, string StopLabel, ReplicaSettings Settings, double DocumentTotal, double DocumentBreakEven) +{ + /// The largest |total| of a row that is only reported. + public const double BindingAbove = 100; + + public bool Binding => Math.Abs(DocumentTotal) > BindingAbove; + + /// The allowed distance from the document's total: the larger of 25 targets and 5%. + public double Tolerance => Math.Max(25, 0.05 * Math.Abs(DocumentTotal)); + + /// Whether has the document's sign and stays within . + public bool Passes(double total) => Math.Sign(total) == Math.Sign(DocumentTotal) && Math.Abs(total - DocumentTotal) <= Tolerance; +} + +/// How a basket of the replica ends. +public static class ReplicaExits +{ + public const string Target = "target"; + + public const string Stop = "stop"; + + /// Still open on the last bar, valued at its close. + public const string Open = "open"; +} + +/// +/// One basket of the replica: the series, the direction (+1 long, −1 short), the bars and log prices of its entries, the σ +/// frozen at the opening, the bar of the close (null if still open), how it ended and its result in targets. +/// +public sealed record ReplicaBasket( + int Series, + int Direction, + IReadOnlyList EntryBars, + IReadOnlyList Entries, + double Sigma, + int? ClosedAt, + string Exit, + double Result); + +/// +/// The result of the replica: the total in targets (open baskets at the last close included), the positions (every entry), +/// the baskets, those closed at the target and at the stop, and the baskets themselves. +/// +public sealed record ReplicaResult(double Total, int Positions, int Baskets, int AtTarget, int Stops, IReadOnlyList List) +{ + public static ReplicaResult Empty { get; } = new(0, 0, 0, 0, 0, []); + + /// The cost per position that would bring the total to zero: total ÷ positions (not a number without positions). + public double BreakEven => Positions == 0 ? double.NaN : Total / Positions; + + /// The share of baskets closed at the target (not a number without baskets). Shown, never judged. + public double AtTargetShare => Baskets == 0 ? double.NaN : (double)AtTarget / Baskets; + + /// The results of several series as one, in the order given. + public static ReplicaResult Combine(IEnumerable results) + { + ArgumentNullException.ThrowIfNull(results); + var total = 0d; + int positions = 0, baskets = 0, atTarget = 0, stops = 0; + var list = new List(); + foreach (var r in results) + { + total += r.Total; + positions += r.Positions; + baskets += r.Baskets; + atTarget += r.AtTarget; + stops += r.Stops; + list.AddRange(r.List); + } + + return new ReplicaResult(total, positions, baskets, atTarget, stops, list); + } +} + +/// The control against chance of the replica: the observed break-even, that of every replica, and the share of replicas equal or better. +public sealed record ReplicaControl(double Observed, IReadOnlyList Replicas, double Share); + +/// +/// The stylised replica of appendix G.3 of the research document of 2 December 2026 (Phase 14, issue #130): generation B on +/// each series alone, in logs, entry and exit on the same close, no costs, no account rules. It is the yardstick the basket +/// engine is checked against, and the way the 15 «Forex 1999–2026» totals of table G.4 are reproduced. +/// +/// +/// The conventions are those that reproduce all 15 totals (ADR of Phase 14). On every series s = ln(close): z and σ +/// come from (sample deviation of the last W values, bar t included) and +/// (population deviation of the W − 1 differences inside them); the first bar with a +/// signal is W − 1. At each bar, in this order: +/// +/// No basket: with |z| ≥ entry z one position opens against the deviation at s(t) and σ is frozen. Nothing else +/// happens on that bar. +/// A basket open from an earlier bar, first match wins: the stop (when set) if the basket's loss is at least S +/// targets; the target if dir·(s(t) − mean of the entries) ≥ k_T·σ; an averaging if fewer than M were made, the last entry +/// is at least k_D·σ·g^(averagings made) away against the basket, and z is still beyond the threshold on the entry side. +/// No basket opens on the bar where one closes. +/// +/// A position is worth dir·(s − entry) / (k_T·σ) targets. A basket still open on the last bar is valued at its close. +/// Series are independent; any number can be open together. +/// +public static class StylisedReplica +{ + /// The replica on one series of log prices (series index 0). + public static ReplicaResult Run(IReadOnlyList logs, ReplicaSettings settings) => Run(logs, settings, 0); + + /// The replica on many series, each on its own; the result adds them in order. + public static ReplicaResult Run(IReadOnlyList> series, ReplicaSettings settings) + { + ArgumentNullException.ThrowIfNull(series); + return ReplicaResult.Combine(series.Select((s, i) => Run(s, settings, i))); + } + + /// + /// The control of G.5: every bar the first differences of all the series change sign together with probability one + /// half (not centred: the replica trades both ways), the series are rebuilt from their first value and the replica runs + /// again. Signs from with seed + /// (seed, k) for repetition k; the share is on the break-even. The + /// series must share one calendar: the same length, bar t the same moment in all. Repetitions run in parallel; the + /// result does not depend on it. + /// + public static ReplicaControl Control(IReadOnlyList> series, ReplicaSettings settings, int repetitions, int seed) + { + ArgumentNullException.ThrowIfNull(series); + ArgumentNullException.ThrowIfNull(settings); + ArgumentOutOfRangeException.ThrowIfLessThan(repetitions, 1); + if (series.Count == 0 || series.Any(s => s.Count != series[0].Count)) + { + throw new ArgumentException("Il controllo contro il caso vuole serie della stessa lunghezza, sullo stesso calendario.", nameof(series)); + } + + foreach (var s in series) + { + BasketIndex.RequireCompressed(s, nameof(series)); + } + + var observed = Run(series, settings).BreakEven; + var length = series[0].Count; + var differences = series.Select(s => + { + var d = new double[Math.Max(length - 1, 0)]; + for (var t = 1; t < length; t++) + { + d[t - 1] = s[t] - s[t - 1]; + } + + return d; + }).ToList(); + + // The repetitions are independent and each writes its own slot: in parallel, with the same result as in order. + var replicas = new double[repetitions]; + Parallel.For(0, repetitions, k => + { + // One sign a bar; the difference that ends at bar t takes the sign of bar t (the sign of bar 0 is drawn, unused). + var signs = TournamentStatistics.Signs(length, TournamentStatistics.ReplicaSeed(seed, k)); + var barSigns = new ArraySegment(signs, Math.Min(1, length), Math.Max(length - 1, 0)); + var rebuilt = new List>(series.Count); + for (var i = 0; i < series.Count; i++) + { + var flipped = Surrogates.Flip(differences[i], barSigns, centred: false); + var s = new double[length]; + if (length > 0) + { + s[0] = series[i][0]; + } + + for (var t = 1; t < length; t++) + { + s[t] = s[t - 1] + flipped[t - 1]; + } + + rebuilt.Add(s); + } + + replicas[k] = Run(rebuilt, settings).BreakEven; + }); + + return new ReplicaControl(observed, replicas, TournamentStatistics.ControlShare(observed, replicas)); + } + + /// + /// The 28 series of ln(close) of the ECB crosses, in the order of , each up to + /// included. Days without a fixing are simply not there: each series is compressed. + /// + public static IReadOnlyList> EcbSeries(IReadOnlyDictionary> crosses, DateOnly through) + { + ArgumentNullException.ThrowIfNull(crosses); + var result = new List>(FxPairs.All.Count); + foreach (var pair in FxPairs.All) + { + if (!crosses.TryGetValue(pair.Name, out var bars)) + { + throw new ArgumentException($"Manca la coppia {pair.Name} tra i cambi incrociati della BCE.", nameof(crosses)); + } + + result.Add(bars + .Where(b => DateOnly.FromDateTime(b.OpensAt.UtcDateTime) <= through) + .OrderBy(b => b.OpensAt) + .Select(b => Math.Log((double)b.Close)) + .ToArray()); + } + + return result; + } + + private static ReplicaResult Run(IReadOnlyList series, ReplicaSettings settings, int index) + { + ArgumentNullException.ThrowIfNull(series); + ArgumentNullException.ThrowIfNull(settings); + settings.Validate(); + var logs = series as double[] ?? [.. series]; + var z = BasketIndex.RollingZ(logs, settings.Window); + var sigma = BasketIndex.RollingSigma(logs, settings.Window); + var kT = settings.TargetSigma; + var entryZ = settings.EntryZ; + + var list = new List(); + var total = 0d; + int positions = 0, atTarget = 0, stops = 0; + List? bars = null; + List? entries = null; + int direction = 0, averagings = 0; + var frozen = 0d; + + for (var t = 0; t < logs.Length; t++) + { + if (double.IsNaN(z[t]) || double.IsNaN(sigma[t])) + { + continue; + } + + var s = logs[t]; + if (entries is null) + { + if (Math.Abs(z[t]) >= entryZ && sigma[t] > 0) + { + direction = z[t] > 0 ? -1 : 1; + bars = [t]; + entries = [s]; + frozen = sigma[t]; + averagings = 0; + positions++; + } + + continue; + } + + var result = Targets(entries, direction, s, kT * frozen); + string? exit = null; + if (settings.StopTargets is { } stop && -result >= stop) + { + exit = ReplicaExits.Stop; + stops++; + } + else if (direction * (s - Mean(entries)) >= kT * frozen) + { + exit = ReplicaExits.Target; + atTarget++; + } + else if (averagings < settings.MaxAveragings + && direction * (entries[^1] - s) >= settings.DistanceSigma * frozen * Math.Pow(settings.Growth, averagings) + && (direction == 1 ? z[t] <= -entryZ : z[t] >= entryZ)) + { + bars!.Add(t); + entries.Add(s); + averagings++; + positions++; + } + + if (exit is not null) + { + list.Add(new ReplicaBasket(index, direction, bars!, entries, frozen, t, exit, result)); + total += result; + bars = null; + entries = null; + } + } + + if (entries is not null) + { + var result = Targets(entries, direction, logs[^1], kT * frozen); + list.Add(new ReplicaBasket(index, direction, bars!, entries, frozen, null, ReplicaExits.Open, result)); + total += result; + } + + return new ReplicaResult(total, positions, list.Count, atTarget, stops, list); + } + + /// The basket's value in targets at log price : Σ dir·(s − entry), over one target. + private static double Targets(List entries, int direction, double s, double target) + { + var sum = 0d; + foreach (var e in entries) + { + sum += direction * (s - e); + } + + return sum / target; + } + + private static double Mean(List entries) + { + var sum = 0d; + foreach (var e in entries) + { + sum += e; + } + + return sum / entries.Count; + } +} diff --git a/tests/Anubis.Tests/StylisedReplicaTests.cs b/tests/Anubis.Tests/StylisedReplicaTests.cs new file mode 100644 index 0000000..b703850 --- /dev/null +++ b/tests/Anubis.Tests/StylisedReplicaTests.cs @@ -0,0 +1,308 @@ +using System.Security.Cryptography; +using Anubis.Backtest; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The stylised replica of appendix G.3 of the research document (Phase 14, issue #130): the shared rolling signals, the 15 +/// «Forex 1999–2026» totals of table G.4 on the ECB history up to 2 December 2026, the break-even on a process built to +/// revert and on a drifting walk, and the control against chance of G.5 on synthetic series whose truth is known. +/// +[TestClass] +public sealed class StylisedReplicaTests +{ + private const string EcbFile = "free/ecb-hist-1999-2026-12-02.csv"; + + private const string EcbSha256 = "f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8"; + + private static readonly DateOnly DocumentEnd = new(2026, 12, 2); + + /// + /// The 15 rows of a numpy prototype of the same conventions, in G.4 order: total in targets, positions, baskets. The C# + /// replica must give the same within one target and three positions or baskets (the only room is the order of the + /// floating-point sums of the rolling window). + /// + private static readonly (double Total, int Positions, int Baskets)[] Prototype = + [ + (535.5, 1675, 1259), (543.7, 2047, 1543), (257.2, 2390, 1788), + (753.6, 1953, 1467), (1029.1, 2583, 1929), (-100.8, 2937, 2186), + (340.1, 1424, 1066), (536.3, 1641, 1223), (138.4, 1936, 1447), + (647.1, 1977, 1167), (439.5, 2702, 1590), (-47.4, 3650, 2166), + (531.3, 2133, 1273), (757.4, 3010, 1796), (169.9, 3455, 2109), + ]; + + private static readonly Lazy>> _ecb = new(() => + StylisedReplica.EcbSeries(EcbCrosses.Build(Ecb.ParseHistoryCsv(Fixture.Text(EcbFile), EcbCrosses.Rates)), DocumentEnd)); + + private static readonly Lazy _table = new(() => + [.. ReplicaSettings.DocumentCases.Select(c => StylisedReplica.Run(_ecb.Value, c.Settings))]); + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEcbHistoryOfTheDocumentIsInTheTestDataWithItsFingerprint() + { + Assert.AreEqual(EcbSha256, Convert.ToHexStringLower(SHA256.HashData(Fixture.Bytes(EcbFile)))); + + var rates = Ecb.ParseHistoryCsv(Fixture.Text(EcbFile), EcbCrosses.Rates); + var days = rates.Select(r => r.Date).Distinct().ToList(); + Assert.AreEqual(7_149, days.Count, "the document counts 7,149 fixings"); + Assert.AreEqual(new DateOnly(1999, 1, 4), days[0]); + Assert.AreEqual(DocumentEnd, days[^1]); + Assert.AreEqual(7_149 * 7, rates.Count, "all seven currencies on every day"); + + var crosses = EcbCrosses.Build(rates); + CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), crosses.Keys.ToArray()); + Assert.IsTrue(crosses.Values.All(bars => bars.Count == 7_149)); + + var logs = StylisedReplica.EcbSeries(crosses, DocumentEnd); + Assert.AreEqual(28, logs.Count); + Assert.IsTrue(logs.All(s => s.Count == 7_149)); + + // EURUSD on the last day is the rate itself; USDJPY is 175.17 / 1.0856 rounded to 10 decimals. + Assert.AreEqual(Math.Log(1.0856), logs[3][^1], 1e-15); + Assert.AreEqual(Math.Log((double)Math.Round(175.17m / 1.0856m, 10, MidpointRounding.ToEven)), logs[24][^1], 1e-15); + + // The cut is inclusive: one day earlier, one value fewer. + Assert.IsTrue(StylisedReplica.EcbSeries(crosses, DocumentEnd.AddDays(-1)).All(s => s.Count == 7_148)); + } + + [TestMethod] + [TestCategory(Category.Golden)] + public void TheThirteenForexTotalsOfAppendixGAreReproduced() + { + var cases = ReplicaSettings.DocumentCases; + Assert.AreEqual(15, cases.Count); + Assert.AreEqual(13, cases.Count(c => c.Binding)); + for (var i = 0; i < cases.Count; i++) + { + var c = cases[i]; + var ours = _table.Value[i].Total; + Console.WriteLine($"{i + 1,2} {c.Label} | {c.StopLabel}: documento {c.DocumentTotal}, noi {ours:F1}, differenza {ours - c.DocumentTotal:+0.0;-0.0}, pareggio {_table.Value[i].BreakEven:+0.00;-0.00}"); + if (c.Binding) + { + Assert.AreEqual(Math.Sign(c.DocumentTotal), Math.Sign(ours), $"row {i + 1}: sign"); + Assert.IsTrue(Math.Abs(ours - c.DocumentTotal) <= Math.Max(25, 0.05 * Math.Abs(c.DocumentTotal)), $"row {i + 1}: {ours} against {c.DocumentTotal}"); + Assert.IsTrue(c.Passes(ours), $"row {i + 1}: the case's own band"); + } + } + + // The two rows near zero are only reported: both negative like the document, both a little lower than it. + foreach (var row in new[] { 6, 12 }) + { + var c = cases[row - 1]; + var ours = _table.Value[row - 1].Total; + Assert.IsFalse(c.Binding); + Assert.IsTrue(ours < 0 && c.DocumentTotal < 0, $"row {row}: {ours} and {c.DocumentTotal}"); + Assert.IsTrue(ours - c.DocumentTotal < 0, $"row {row}: the difference is negative, as in the prototype"); + } + } + + [TestMethod] + [TestCategory(Category.Golden)] + public void TheReplicaMatchesThePrototypeOnEveryRow() + { + for (var i = 0; i < Prototype.Length; i++) + { + var ours = _table.Value[i]; + var (total, positions, baskets) = Prototype[i]; + Console.WriteLine($"{i + 1,2}: totale {ours.Total:F2} ({total}), posizioni {ours.Positions} ({positions}), panieri {ours.Baskets} ({baskets}), " + + $"pareggio {ours.BreakEven:F3}, al bersaglio {ours.AtTargetShare:P1}, arresti {ours.Stops}"); + Assert.AreEqual(total, ours.Total, 1.0, $"row {i + 1}: total"); + Assert.AreEqual(positions, ours.Positions, 3, $"row {i + 1}: positions"); + Assert.AreEqual(baskets, ours.Baskets, 3, $"row {i + 1}: baskets"); + Assert.AreEqual(ours.Positions, ours.List.Sum(b => b.Entries.Count)); + Assert.AreEqual(ours.Baskets, ours.List.Count); + Assert.AreEqual(ours.Total, ours.List.Sum(b => b.Result), 1e-6); + Assert.AreEqual(ours.AtTarget, ours.List.Count(b => b.Exit == ReplicaExits.Target)); + Assert.AreEqual(ours.Stops, ours.List.Count(b => b.Exit == ReplicaExits.Stop)); + Assert.AreEqual(ours.Total / ours.Positions, ours.BreakEven, 1e-12); + } + + // Without a stop no basket closes at a stop; and the stops of 30 targets close more baskets than those of 90. + Assert.AreEqual(0, _table.Value[0].Stops); + Assert.IsTrue(_table.Value[2].Stops > _table.Value[1].Stops); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OnAProcessThatRevertsTheBreakEvenIsAboutOnePointTwoTargets() + { + // Half-life of 50 bars: φ = 2^(−1/50). The document gives 1.23 targets per position. + var series = Enumerable.Range(0, 20).Select(i => Levels(Synthetic.MeanRevertingReturns(5_000, 1_400 + i))).ToList(); + var result = StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings); + Console.WriteLine($"pareggio {result.BreakEven:F3}, totale {result.Total:F1}, posizioni {result.Positions}, panieri {result.Baskets}, al bersaglio {result.AtTargetShare:P1}"); + Assert.IsTrue(result.BreakEven is >= 1.10 and <= 1.35, $"break-even {result.BreakEven}"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OnARandomWalkWithDriftTheBreakEvenIsNegative() + { + var series = Enumerable.Range(0, 20).Select(i => Levels(Synthetic.WalkReturns(5_000, 2_400 + i, drift: 0.001))).ToList(); + var result = StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings); + Console.WriteLine($"pareggio {result.BreakEven:F3}, totale {result.Total:F1}, posizioni {result.Positions}, panieri {result.Baskets}"); + Assert.IsTrue(result.BreakEven < -1, $"break-even {result.BreakEven}"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OnRandomWalksTheShuffledShareIsAboutAHalf() + { + // A driftless walk has the same law once its returns change sign: the observed result is one of the replicas, and + // its share is uniform. 100 sets of 4 walks of 1,000 bars, 100 repetitions each. + var settings = ReplicaSettings.DocumentCases[0].Settings; + var shares = new double[100]; + for (var set = 0; set < shares.Length; set++) + { + var series = Enumerable.Range(0, 4).Select(i => Levels(Synthetic.WalkReturns(1_000, 30_000 + (4 * set) + i))).ToList(); + shares[set] = StylisedReplica.Control(series, settings, 100, 20_261_202 + (1_000 * set)).Share; + } + + var low = shares.Count(s => s < 0.05); + Console.WriteLine($"quota media {shares.Average():F3}, insiemi sotto 0,05: {low}"); + Assert.IsTrue(shares.Average() is >= 0.40 and <= 0.60, $"mean share {shares.Average()}"); + Assert.IsTrue(low < 10, $"{low} sets below 0.05"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OnARevertingProcessTheShuffledShareIsBelowFivePercent() + { + var series = Enumerable.Range(0, 4).Select(i => Levels(Synthetic.MeanRevertingReturns(1_000, 40_000 + i))).ToList(); + var control = StylisedReplica.Control(series, ReplicaSettings.DocumentCases[0].Settings, 100, 20_261_202); + Console.WriteLine($"pareggio osservato {control.Observed:F3}, mediana rimescolata {Median(control.Replicas):F3}, quota {control.Share:F3}"); + Assert.AreEqual(100, control.Replicas.Count); + Assert.AreEqual(StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings).BreakEven, control.Observed); + Assert.IsTrue(control.Share < 0.05, $"share {control.Share}"); + + // The control is deterministic: the same seed gives the same replicas. + var again = StylisedReplica.Control(series, ReplicaSettings.DocumentCases[0].Settings, 100, 20_261_202); + CollectionAssert.AreEqual(control.Replicas.ToArray(), again.Replicas.ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReplicaIsInvariantToScaleShiftAndInversion() + { + var settings = ReplicaSettings.DocumentCases[4].Settings; + var s = Levels(Synthetic.MeanRevertingReturns(4_000, 50_001)); + var original = StylisedReplica.Run(s, settings); + Assert.IsTrue(original.Baskets > 20, $"{original.Baskets} baskets"); + + // A positive affine change of the log price: same baskets, same results. + var moved = StylisedReplica.Run(s.Select(x => (3.7 * x) - 12.5).ToArray(), settings); + Assert.AreEqual(original.Baskets, moved.Baskets); + Assert.AreEqual(original.Positions, moved.Positions); + for (var i = 0; i < original.List.Count; i++) + { + var (a, b) = (original.List[i], moved.List[i]); + Assert.AreEqual(a.Direction, b.Direction); + CollectionAssert.AreEqual(a.EntryBars.ToArray(), b.EntryBars.ToArray()); + Assert.AreEqual(a.ClosedAt, b.ClosedAt); + Assert.AreEqual(a.Exit, b.Exit); + Assert.AreEqual(a.Result, b.Result, 1e-9); + Assert.AreEqual(3.7 * a.Sigma, b.Sigma, 1e-12); + } + + Assert.AreEqual(original.Total, moved.Total, 1e-8); + + // The inverse quote (ln 1/P = −ln P): every basket in the other direction, the same total. + var inverted = StylisedReplica.Run(s.Select(x => -x).ToArray(), settings); + Assert.AreEqual(original.Baskets, inverted.Baskets); + Assert.IsTrue(original.List.Zip(inverted.List).All(p => p.First.Direction == -p.Second.Direction && p.First.ClosedAt == p.Second.ClosedAt)); + Assert.AreEqual(original.Total, inverted.Total, 1e-9); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void RollingSignalsEqualTheExactComputation() + { + var series = new List> + { + Levels(Synthetic.WalkReturns(3_000, 60_001)), + Levels(Synthetic.WalkReturns(3_000, 60_002, drift: 0.002)), + Levels(Synthetic.MeanRevertingReturns(3_000, 60_003)), + // A walk far from zero, where sums of raw values would lose digits. + Levels(Synthetic.WalkReturns(3_000, 60_004)).Select(x => 10_000 + x).ToArray(), + }; + series.AddRange(_ecb.Value); + + foreach (var window in new[] { 100, 20 }) + { + foreach (var x in series) + { + var z = BasketIndex.RollingZ(x, window); + var sigma = BasketIndex.RollingSigma(x, window); + Assert.AreEqual(x.Count, z.Length); + Assert.AreEqual(x.Count, sigma.Length); + for (var t = 0; t < x.Count; t++) + { + var exactZ = BasketIndex.ZScore(x, t, window); + // Population deviation of the window − 1 differences = the sample one times √((m − 1) / m). + var exactSigma = BasketIndex.ShortSigma(x, t, window - 1) * Math.Sqrt((window - 2.0) / (window - 1.0)); + if (t < window - 1) + { + Assert.IsTrue(double.IsNaN(z[t]) && double.IsNaN(sigma[t]), $"bar {t}: no signal before the window is full"); + continue; + } + + Assert.IsNotNull(exactZ); + Assert.AreEqual(exactZ.Value, z[t], 1e-9 * Math.Max(1, Math.Abs(exactZ.Value)), $"z at bar {t}"); + Assert.AreEqual(exactSigma!.Value, sigma[t], 1e-9 * exactSigma.Value, $"σ at bar {t}"); + } + } + } + + // A flat stretch has no z and a σ of exactly zero; a straight line has a z but no σ either. + double[] flat = [.. Enumerable.Range(0, 30).Select(i => i < 10 ? i * 0.1 : 0.7)]; + Assert.IsTrue(double.IsNaN(BasketIndex.RollingZ(flat, 10)[29])); + Assert.AreEqual(0, BasketIndex.RollingSigma(flat, 10)[29]); + Assert.IsFalse(double.IsNaN(BasketIndex.RollingZ(flat, 10)[12])); + double[] line = [.. Enumerable.Range(0, 30).Select(i => 1.0 + (i * 0.25))]; + Assert.AreEqual(0, BasketIndex.RollingSigma(line, 10)[29]); + Assert.AreEqual(BasketIndex.ZScore(line, 29, 10)!.Value, BasketIndex.RollingZ(line, 10)[29], 1e-9); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ASeriesWithAGapIsRefused() + { + var s = Levels(Synthetic.WalkReturns(300, 70_001)); + s[150] = double.NaN; + Assert.ThrowsExactly(() => BasketIndex.RollingZ(s, 100)); + Assert.ThrowsExactly(() => BasketIndex.RollingSigma(s, 100)); + var settings = ReplicaSettings.DocumentCases[0].Settings; + var error = Assert.ThrowsExactly(() => StylisedReplica.Run(s, settings)); + StringAssert.Contains(error.Message, "buco"); + + s[150] = double.PositiveInfinity; + Assert.ThrowsExactly(() => StylisedReplica.Run(s, settings)); + + // The control needs one calendar: series of different lengths are refused. + var a = Levels(Synthetic.WalkReturns(300, 70_002)); + var b = Levels(Synthetic.WalkReturns(299, 70_003)); + Assert.ThrowsExactly(() => StylisedReplica.Control([a, b], settings, 10, 1)); + } + + /// The levels of a log price from its log returns: the cumulative sum. + private static double[] Levels(double[] returns) + { + var levels = new double[returns.Length]; + var level = 0.0; + for (var i = 0; i < returns.Length; i++) + { + level += returns[i]; + levels[i] = level; + } + + return levels; + } + + private static double Median(IReadOnlyList values) + { + var sorted = values.Where(v => !double.IsNaN(v)).Order().ToArray(); + return sorted.Length == 0 ? double.NaN : sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[(sorted.Length / 2) - 1] + sorted[sorted.Length / 2]) / 2; + } +}