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;
}
}