The tournament judge before the contenders (ADR 0029): the trial judge split into resumable work units on a pool of low-priority workers, the common count of trials and field statistics, the control against chance on surrogate prices, and the immutable tournament plan with a final tract read once. refs #122, refs #123, refs #124, refs #125, refs #126 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
274 lines
12 KiB
C#
274 lines
12 KiB
C#
using Anubis.Backtest;
|
||
using Anubis.Data;
|
||
using Anubis.Strategies;
|
||
|
||
namespace Anubis.Tests;
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
internal static class Synthetic
|
||
{
|
||
public static readonly DateOnly Start = new(2018, 1, 1);
|
||
|
||
/// <summary>A coin quoted in euro on OKX, traded every day: the synthetic series live on it.</summary>
|
||
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",
|
||
};
|
||
|
||
/// <summary>The autoregressive coefficient of a daily series whose distance from its mean halves in <paramref name="halfLife"/> bars.</summary>
|
||
public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife);
|
||
|
||
/// <summary>
|
||
/// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the
|
||
/// <paramref name="halfLife"/> and the series started at its level. The return of day t is x(t) − x(t−1).
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Log returns of a random walk: <paramref name="drift"/> plus normal noise, no memory.</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ.</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Two series of returns with correlation about <paramref name="correlation"/>: a common part and a part of each.</summary>
|
||
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);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Daily bars from log returns of the close: the first bar at <paramref name="start"/>, 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.
|
||
/// </summary>
|
||
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<double> 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<DailyBar>(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;
|
||
}
|
||
|
||
/// <summary>A dataset in euro of synthetic coins, one per series of bars.</summary>
|
||
public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList<DailyBar> Bars)[] series) =>
|
||
new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR");
|
||
|
||
/// <summary>A mean-reverting coin: <paramref name="days"/> returns of <see cref="MeanRevertingReturns"/> turned into bars.</summary>
|
||
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)));
|
||
|
||
/// <summary>Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed.</summary>
|
||
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)))]);
|
||
|
||
/// <summary>Several independent coins walking at random with the same <paramref name="drift"/>, each from its own seed.</summary>
|
||
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)))]);
|
||
|
||
/// <summary>The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR…</summary>
|
||
public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR");
|
||
|
||
/// <summary>A coin that walks at random with a <paramref name="drift"/> a day (zero for pure noise).</summary>
|
||
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)));
|
||
|
||
/// <summary>Log returns of the closes of a series of bars, one per bar after the first.</summary>
|
||
public static double[] CloseReturns(IReadOnlyList<DailyBar> 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))];
|
||
}
|
||
|
||
/// <summary>Pearson correlation of two series of the same length.</summary>
|
||
public static double Correlation(IReadOnlyList<double> x, IReadOnlyList<double> 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);
|
||
}
|
||
|
||
/// <summary>Autocorrelation at lag one.</summary>
|
||
public static double LagOne(IReadOnlyList<double> x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]);
|
||
|
||
/// <summary>The daily Sharpe ratio of a run: what the control compares between the real series and its replicas.</summary>
|
||
public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe;
|
||
|
||
/// <summary>
|
||
/// The control of a rule on a dataset: its daily Sharpe on the real data, and on <paramref name="repetitions"/>
|
||
/// surrogates whose signs come from <paramref name="seed"/> + k. Returns the observed Sharpe, the replicas and the
|
||
/// share of replicas at least as good.
|
||
/// </summary>
|
||
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));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A test-only reversion rule, long only: it buys an instrument when its close falls <c>entry</c> standard deviations
|
||
/// below the mean of the last <c>lookback</c> 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.
|
||
/// </summary>
|
||
internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy
|
||
{
|
||
/// <summary>Bars it waits for before the first decision; until <c>lookback</c> bars, the mean is of those there are.</summary>
|
||
public const int MinimumBars = 50;
|
||
|
||
public string Id => ReversionFamily.FamilyId;
|
||
|
||
public string Version => "1";
|
||
|
||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||
|
||
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
|
||
|
||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||
{
|
||
var intents = new List<Intent>();
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>The family of <see cref="ReversionRule"/>: the window of the mean and the distance of the entry.</summary>
|
||
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<ParameterSpec> 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"]);
|
||
}
|
||
|
||
/// <summary>The parameters of a variant, as the laboratory would build them.</summary>
|
||
public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]);
|
||
}
|