using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
///
/// Synthetic series with a known nature, built from a fixed seed (Phase 13): a mean-reverting price (Ornstein–Uhlenbeck on
/// the logarithm), a random walk with or without drift, returns with memory, correlated pairs. The statistics of the
/// tournament are proved on them, because only there is the truth known in advance. Shared by the tests of the control,
/// of the common statistics and of the tournament.
///
internal static class Synthetic
{
public static readonly DateOnly Start = new(2018, 1, 1);
/// A coin quoted in euro on OKX, traded every day: the synthetic series live on it.
public static InstrumentSpec Coin(string symbol = "AAA-EUR") => new(Venues.Okx, symbol, symbol, AssetClasses.Crypto, "EUR")
{
BaseCurrency = symbol.Split('-')[0],
TickSize = 0.0001m,
LotSize = 0.00000001m,
MinSize = 0.00001m,
Status = "live",
};
/// The autoregressive coefficient of a daily series whose distance from its mean halves in bars.
public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife);
///
/// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the
/// and the series started at its level. The return of day t is x(t) − x(t−1).
///
public static double[] MeanRevertingReturns(int days, int seed, double halfLife = 50, double volatility = 0.01)
{
var gen = new Gen(seed);
var phi = Phi(halfLife);
var result = new double[days];
var x = 0.0;
for (var i = 0; i < days; i++)
{
var next = (phi * x) + (volatility * gen.Normal());
result[i] = next - x;
x = next;
}
return result;
}
/// Log returns of a random walk: plus normal noise, no memory.
public static double[] WalkReturns(int days, int seed, double drift = 0, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
for (var i = 0; i < days; i++)
{
result[i] = drift + (volatility * gen.Normal());
}
return result;
}
/// Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ.
public static double[] AutoregressiveReturns(int days, double phi, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
var previous = 0.0;
for (var i = 0; i < days; i++)
{
previous = (phi * previous) + (volatility * gen.Normal());
result[i] = previous;
}
return result;
}
/// Two series of returns with correlation about : a common part and a part of each.
public static (double[] A, double[] B) CorrelatedReturns(int days, double correlation, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var own = Math.Sqrt(1 - (correlation * correlation));
var a = new double[days];
var b = new double[days];
for (var i = 0; i < days; i++)
{
var common = gen.Normal();
a[i] = volatility * common;
b[i] = volatility * ((correlation * common) + (own * gen.Normal()));
}
return (a, b);
}
///
/// Daily bars from log returns of the close: the first bar at , then each close the one before
/// times e^r. The open is the previous close, high and low a little beyond the body, all unrounded.
///
public static IReadOnlyList Bars(IReadOnlyList logReturns, int seed = 1, double start = 100, DateOnly? from = null)
{
ArgumentNullException.ThrowIfNull(logReturns);
var gen = new Gen(seed);
var day = from ?? Start;
var bars = new List(logReturns.Count + 1) { new(day, start, start * 1.002, start * 0.998, start, 1000) };
var close = start;
for (var i = 0; i < logReturns.Count; i++)
{
var open = close;
close = open * Math.Exp(logReturns[i]);
var high = Math.Max(open, close) * (1 + (0.003 * gen.Double()));
var low = Math.Min(open, close) * (1 - (0.003 * gen.Double()));
bars.Add(new DailyBar(day.AddDays(i + 1), open, high, low, close, 1000));
}
return bars;
}
/// A dataset in euro of synthetic coins, one per series of bars.
public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList Bars)[] series) =>
new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR");
/// A mean-reverting coin: returns of turned into bars.
public static BacktestDataset MeanReverting(int days, int seed, double halfLife = 50, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(MeanRevertingReturns(days, seed, halfLife, volatility), seed)));
/// Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed.
public static BacktestDataset MeanReverting(int days, int seed, int coins, double halfLife = 50, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(MeanRevertingReturns(days, seed + (1000 * k), halfLife, volatility), seed + k)))]);
/// Several independent coins walking at random with the same , each from its own seed.
public static BacktestDataset Walk(int days, int seed, int coins, double drift = 0, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(WalkReturns(days, seed + (1000 * k), drift, volatility), seed + k)))]);
/// The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR…
public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR");
/// A coin that walks at random with a a day (zero for pure noise).
public static BacktestDataset Walk(int days, int seed, double drift = 0, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(WalkReturns(days, seed, drift, volatility), seed)));
/// Log returns of the closes of a series of bars, one per bar after the first.
public static double[] CloseReturns(IReadOnlyList bars)
{
ArgumentNullException.ThrowIfNull(bars);
return [.. Enumerable.Range(1, Math.Max(bars.Count - 1, 0)).Select(i => Math.Log(bars[i].Close / bars[i - 1].Close))];
}
/// Pearson correlation of two series of the same length.
public static double Correlation(IReadOnlyList x, IReadOnlyList y)
{
var mx = x.Average();
var my = y.Average();
double sxy = 0, sxx = 0, syy = 0;
for (var i = 0; i < x.Count; i++)
{
sxy += (x[i] - mx) * (y[i] - my);
sxx += (x[i] - mx) * (x[i] - mx);
syy += (y[i] - my) * (y[i] - my);
}
return sxy / Math.Sqrt(sxx * syy);
}
/// Autocorrelation at lag one.
public static double LagOne(IReadOnlyList x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]);
/// The daily Sharpe ratio of a run: what the control compares between the real series and its replicas.
public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe;
///
/// The control of a rule on a dataset: its daily Sharpe on the real data, and on
/// surrogates whose signs come from + k. Returns the observed Sharpe, the replicas and the
/// share of replicas at least as good.
///
public static (double Observed, double[] Replicas, double Share) Control(IStrategyFamily family, StrategyParameters parameters, BacktestDataset data, int repetitions, int seed, bool centred)
{
ArgumentNullException.ThrowIfNull(family);
var options = new BacktestOptions();
var observed = Sharpe(BacktestEngine.Run(family.Create(parameters), data, options));
var replicas = new double[repetitions];
for (var k = 0; k < repetitions; k++)
{
var surrogate = Surrogates.Of(data, TournamentStatistics.ReplicaSeed(seed, k), centred);
replicas[k] = Sharpe(BacktestEngine.Run(family.Create(parameters), surrogate, options));
}
return (observed, replicas, TournamentStatistics.ControlShare(observed, replicas));
}
}
///
/// A test-only reversion rule, long only: it buys an instrument when its close falls entry standard deviations
/// below the mean of the last lookback closes (on the logarithm), and sells when the close is back at the mean. It
/// has an edge on a mean-reverting series and none on a random walk. It never enters the catalogue and has no order code.
///
internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy
{
/// Bars it waits for before the first decision; until lookback bars, the mean is of those there are.
public const int MinimumBars = 50;
public string Id => ReversionFamily.FamilyId;
public string Version => "1";
public IReadOnlyList Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList Universe(UniverseContext context) => context.Available;
public IReadOnlyList Decide(StrategyContext context)
{
var intents = new List();
var weight = 1m / Math.Max(context.Universe.Count, 1);
foreach (var symbol in context.Universe)
{
var bars = context.Bars(symbol);
if (bars.Count < Math.Min(lookback, MinimumBars))
{
continue;
}
var logs = bars.Closes(lookback).Select(c => Math.Log(c)).ToArray();
var m = Moments.Of(logs);
if (m.StandardDeviation <= 0)
{
continue;
}
var z = (logs[^1] - m.Mean) / m.StandardDeviation;
var held = context.Portfolio.Holds(symbol);
if (!held && z < -(double)entry)
{
intents.Add(new Intent(symbol, weight, "reversion_entry"));
}
else if (held && z >= 0)
{
intents.Add(new Intent(symbol, 0m, "reversion_exit"));
}
}
return intents;
}
}
/// The family of : the window of the mean and the distance of the entry.
internal sealed class ReversionFamily : IStrategyFamily
{
public const string FamilyId = "test_reversion";
public static ReversionFamily Instance { get; } = new();
public string Id => FamilyId;
public string Version => "1";
public string Name => "Rientro di prova";
public string Description => "Regola di prova, solo nei test: compra sotto la media e vende quando il prezzo vi torna.";
public IReadOnlyList Parameters =>
[
new("lookback", "Giorni della media", 100m, [50m, 100m, 150m], 10m, 400m, Whole: true),
new("entry", "Distanza d'ingresso in deviazioni", 1m, [0.5m, 1m, 1.5m], 0.1m, 4m),
];
public IStrategy Create(StrategyParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
return new ReversionRule(parameters.Whole("lookback"), parameters["entry"]);
}
/// The parameters of a variant, as the laboratory would build them.
public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]);
}