Add the stylised replica of appendix G and the shared rolling signals
Phase 14 must reproduce the 15 "Forex 1999-2026" totals of table G.4 and check the basket engine against a yardstick that follows G.3 to the letter. StylisedReplica runs generation B on each series of ln(close), entry and exit on the same close, no costs, with the conventions a numpy prototype found to reproduce every row: z over the last 100 values with the sample deviation, sigma as the population deviation of the 99 differences inside them, stop before target (per position against the mean of entries) before averaging, no reopening on the closing bar, open baskets valued at the last close. On the ECB history up to 2 Dec 2026 it gives the prototype's totals, positions and baskets on all 15 rows; the 13 binding totals are within their band (largest gap 3.4 targets). BasketIndex.RollingZ and RollingSigma compute the signals in one pass with anchored sliding sums rebuilt every window, so the replica and the engine can read the same bits; they equal the exact two-pass values to 1e-9 and refuse a series with a gap. The control of G.5 flips the first differences of all series with one sign per bar (not centred) and measures the share of replicas whose break-even is equal or better. refs #130 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
47e08d6778
commit
63bd5b9635
3 files changed
+845
No files matched your search
@@ -72,6 +72,165 @@ public static class BasketIndex
|
||||
return deviation is > 0 ? (index[t] - mean) / deviation : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="window"/> values, bar t included — the same value as <see cref="ZScore"/>, 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sums of the values minus an anchor slide one bar at a time; every <paramref name="window"/> 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.
|
||||
/// </remarks>
|
||||
public static double[] RollingZ(IReadOnlyList<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// σ of appendix G.3 at every bar: the population standard deviation (n) of the <paramref name="window"/> − 1 first
|
||||
/// differences inside the last <paramref name="window"/> values, bar t included. Not a number before the window is
|
||||
/// full; exactly zero when all those differences are equal. Same sliding sums as <see cref="RollingZ"/>.
|
||||
/// </summary>
|
||||
public static double[] RollingSigma(IReadOnlyList<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>The refusal of a series with a missing or infinite value: rolling signals read compressed series only.</summary>
|
||||
public static void RequireCompressed(IReadOnlyList<double> x, string parameter) => _ = Compressed(x, parameter);
|
||||
|
||||
/// <summary>The series as an array (itself when it is one), refused when a value is missing or infinite.</summary>
|
||||
private static double[] Compressed(IReadOnlyList<double> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sums Σ(x − a) and Σ(x − a)² over the last <c>count</c> 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 <c>count</c> bars.
|
||||
/// </summary>
|
||||
private sealed class SlidingSums(int count)
|
||||
{
|
||||
private double _anchor;
|
||||
private double _sum;
|
||||
private double _squares;
|
||||
private int _sinceRebuild = -1;
|
||||
|
||||
/// <summary>Moves the window so that it ends at <paramref name="t"/>; the first call (and every count-th) rebuilds.</summary>
|
||||
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++;
|
||||
}
|
||||
|
||||
/// <summary>Σ(x − mean)² of the window.</summary>
|
||||
public double CentredSquares() => _squares - (_sum * _sum / count);
|
||||
|
||||
/// <summary>x − mean of the window.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// σ_short at bar <paramref name="t"/>: the sample standard deviation of the last <paramref name="shortBars"/> first
|
||||
/// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter.
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Baskets;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ReplicaSettings(
|
||||
double TargetSigma,
|
||||
double DistanceSigma,
|
||||
int MaxAveragings,
|
||||
double Growth = 1,
|
||||
double? StopTargets = null,
|
||||
int Window = BasketIndex.DefaultWindow,
|
||||
double EntryZ = 2)
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ReplicaCase> DocumentCases { get; } = Array.AsReadOnly(BuildCases());
|
||||
|
||||
/// <summary>Checks the values; the message is for the user.</summary>
|
||||
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<ReplicaCase>();
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ReplicaCase(string Label, string StopLabel, ReplicaSettings Settings, double DocumentTotal, double DocumentBreakEven)
|
||||
{
|
||||
/// <summary>The largest |total| of a row that is only reported.</summary>
|
||||
public const double BindingAbove = 100;
|
||||
|
||||
public bool Binding => Math.Abs(DocumentTotal) > BindingAbove;
|
||||
|
||||
/// <summary>The allowed distance from the document's total: the larger of 25 targets and 5%.</summary>
|
||||
public double Tolerance => Math.Max(25, 0.05 * Math.Abs(DocumentTotal));
|
||||
|
||||
/// <summary>Whether <paramref name="total"/> has the document's sign and stays within <see cref="Tolerance"/>.</summary>
|
||||
public bool Passes(double total) => Math.Sign(total) == Math.Sign(DocumentTotal) && Math.Abs(total - DocumentTotal) <= Tolerance;
|
||||
}
|
||||
|
||||
/// <summary>How a basket of the replica ends.</summary>
|
||||
public static class ReplicaExits
|
||||
{
|
||||
public const string Target = "target";
|
||||
|
||||
public const string Stop = "stop";
|
||||
|
||||
/// <summary>Still open on the last bar, valued at its close.</summary>
|
||||
public const string Open = "open";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ReplicaBasket(
|
||||
int Series,
|
||||
int Direction,
|
||||
IReadOnlyList<int> EntryBars,
|
||||
IReadOnlyList<double> Entries,
|
||||
double Sigma,
|
||||
int? ClosedAt,
|
||||
string Exit,
|
||||
double Result);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ReplicaResult(double Total, int Positions, int Baskets, int AtTarget, int Stops, IReadOnlyList<ReplicaBasket> List)
|
||||
{
|
||||
public static ReplicaResult Empty { get; } = new(0, 0, 0, 0, 0, []);
|
||||
|
||||
/// <summary>The cost per position that would bring the total to zero: total ÷ positions (not a number without positions).</summary>
|
||||
public double BreakEven => Positions == 0 ? double.NaN : Total / Positions;
|
||||
|
||||
/// <summary>The share of baskets closed at the target (not a number without baskets). Shown, never judged.</summary>
|
||||
public double AtTargetShare => Baskets == 0 ? double.NaN : (double)AtTarget / Baskets;
|
||||
|
||||
/// <summary>The results of several series as one, in the order given.</summary>
|
||||
public static ReplicaResult Combine(IEnumerable<ReplicaResult> results)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(results);
|
||||
var total = 0d;
|
||||
int positions = 0, baskets = 0, atTarget = 0, stops = 0;
|
||||
var list = new List<ReplicaBasket>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The control against chance of the replica: the observed break-even, that of every replica, and the share of replicas equal or better.</summary>
|
||||
public sealed record ReplicaControl(double Observed, IReadOnlyList<double> Replicas, double Share);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>The conventions are those that reproduce all 15 totals (ADR of Phase 14). On every series s = ln(close): z and σ
|
||||
/// come from <see cref="BasketIndex.RollingZ"/> (sample deviation of the last W values, bar t included) and
|
||||
/// <see cref="BasketIndex.RollingSigma"/> (population deviation of the W − 1 differences inside them); the first bar with a
|
||||
/// signal is W − 1. At each bar, in this order:</para>
|
||||
/// <list type="number">
|
||||
/// <item>No basket: with |z| ≥ entry z one position opens against the deviation at s(t) and σ is frozen. Nothing else
|
||||
/// happens on that bar.</item>
|
||||
/// <item>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.</item>
|
||||
/// <item>No basket opens on the bar where one closes.</item>
|
||||
/// </list>
|
||||
/// <para>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.</para>
|
||||
/// </remarks>
|
||||
public static class StylisedReplica
|
||||
{
|
||||
/// <summary>The replica on one series of log prices (series index 0).</summary>
|
||||
public static ReplicaResult Run(IReadOnlyList<double> logs, ReplicaSettings settings) => Run(logs, settings, 0);
|
||||
|
||||
/// <summary>The replica on many series, each on its own; the result adds them in order.</summary>
|
||||
public static ReplicaResult Run(IReadOnlyList<IReadOnlyList<double>> series, ReplicaSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(series);
|
||||
return ReplicaResult.Combine(series.Select((s, i) => Run(s, settings, i)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="TournamentStatistics.Signs"/> with seed <see cref="TournamentStatistics.ReplicaSeed"/>
|
||||
/// (seed, k) for repetition k; the share is <see cref="TournamentStatistics.ControlShare"/> 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.
|
||||
/// </summary>
|
||||
public static ReplicaControl Control(IReadOnlyList<IReadOnlyList<double>> 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<int>(signs, Math.Min(1, length), Math.Max(length - 1, 0));
|
||||
var rebuilt = new List<IReadOnlyList<double>>(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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The 28 series of ln(close) of the ECB crosses, in the order of <see cref="FxPairs.All"/>, each up to
|
||||
/// <paramref name="through"/> included. Days without a fixing are simply not there: each series is compressed.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<IReadOnlyList<double>> EcbSeries(IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> crosses, DateOnly through)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(crosses);
|
||||
var result = new List<IReadOnlyList<double>>(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<double> 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<ReplicaBasket>();
|
||||
var total = 0d;
|
||||
int positions = 0, atTarget = 0, stops = 0;
|
||||
List<int>? bars = null;
|
||||
List<double>? 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);
|
||||
}
|
||||
|
||||
/// <summary>The basket's value in targets at log price <paramref name="s"/>: Σ dir·(s − entry), over one target.</summary>
|
||||
private static double Targets(List<double> 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<double> entries)
|
||||
{
|
||||
var sum = 0d;
|
||||
foreach (var e in entries)
|
||||
{
|
||||
sum += e;
|
||||
}
|
||||
|
||||
return sum / entries.Count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
using System.Security.Cryptography;
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Baskets;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<IReadOnlyList<IReadOnlyList<double>>> _ecb = new(() =>
|
||||
StylisedReplica.EcbSeries(EcbCrosses.Build(Ecb.ParseHistoryCsv(Fixture.Text(EcbFile), EcbCrosses.Rates)), DocumentEnd));
|
||||
|
||||
private static readonly Lazy<ReplicaResult[]> _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<IReadOnlyList<double>>
|
||||
{
|
||||
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<ArgumentException>(() => BasketIndex.RollingZ(s, 100));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BasketIndex.RollingSigma(s, 100));
|
||||
var settings = ReplicaSettings.DocumentCases[0].Settings;
|
||||
var error = Assert.ThrowsExactly<ArgumentException>(() => StylisedReplica.Run(s, settings));
|
||||
StringAssert.Contains(error.Message, "buco");
|
||||
|
||||
s[150] = double.PositiveInfinity;
|
||||
Assert.ThrowsExactly<ArgumentException>(() => 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<ArgumentException>(() => StylisedReplica.Control([a, b], settings, 10, 1));
|
||||
}
|
||||
|
||||
/// <summary>The levels of a log price from its log returns: the cumulative sum.</summary>
|
||||
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<double> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user