Files
Anubis/tests/Anubis.Tests/BasketSynthetic.cs
T
Alby96andClaude Opus 5.5 44639e3f49 Add the basket engine: a margin account that trades the document's baskets
Phase 14 needs an engine that simulates the research document's baskets
with the frictions of the venue, so the trial judge can say whether they
earn anything once those frictions are paid.

BasketEngine walks a BasketMarket (the bars of a BarDataset without the
moments no symbol trades) bar by bar: decisions on the closed bar,
execution at the next open, buys at the ask and sells at the bid (bid and
ask rebuilt from the venue spread when the source gives one price, as the
ECB fixings do). Every leg of every level is its own position with the
venue's mandatory stop; a stop that leaves one leg of a two-leg basket
alone closes the rest at the next execution as an orphan leg. Commission
on both sides, financing at every rollover crossed (Wednesday triple, from
the VenueCosts calendar), liquidation below half the initial margin.

On top, the document's account rules (9% stop on the open loss over the
balance, on mid prices in the daily pause, entries back at the next server
day; 2% gate on new baskets only; open baskets, Rvol, correlation, three
costs) and, «come dal vivo», SPEC 9.2 through RiskMonitor (day, week, fall
from the high, trip with the seven-day restart), the 40% margin limit,
nine positions, no opposite positions, net exposure per currency and the
Prudente basket stops. One equity point a day for every variant.

Signals come from the replica's RollingZ and RollingSigma on each unit's
compressed series; a rolling Rvol joins them, equal to BasketIndex.Rvol.
The comparison configuration (same close, no cost, no protection) makes
the replica's baskets on 200 seeded series and its total to 1e-9; on the
ECB fixture it gives the replica's 535.54 targets over 1,259 baskets.
TrialPlan gains optional Mode and Costs, left out when null, so the plans
of the daily families keep their hashes.

refs #127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 18:17:13 +01:00

139 lines
6.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// Builders of hand-made market data for the basket engine (Phase 14): daily bars on the currency weekdays, 15-minute bars
/// with explicit bid and ask, the 28 crosses of seven synthetic rates, and log series that revert or walk.
/// </summary>
internal static class BasketSynthetic
{
/// <summary>A Monday in winter, far from any change of the clocks.</summary>
public static readonly DateOnly Monday = new(2026, 1, 5);
/// <summary>The first <paramref name="count"/> currency weekdays from <paramref name="start"/> (Monday to Friday).</summary>
public static IReadOnlyList<DateOnly> Weekdays(DateOnly start, int count)
{
var days = new List<DateOnly>(count);
for (var day = start; days.Count < count; day = day.AddDays(1))
{
if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
{
days.Add(day);
}
}
return days;
}
/// <summary>
/// Daily bars like the ECB's (open = high = low = close, at 00:00 UTC of each weekday from <paramref name="start"/>), one
/// reference price a day and no ask: the engine builds bid and ask with the venue's spread.
/// </summary>
public static BarDataset Daily(IReadOnlyDictionary<string, double[]> closes, DateOnly? start = null)
{
var length = closes.Values.Max(c => c.Length);
var days = Weekdays(start ?? Monday, length);
var bars = closes.ToDictionary(
p => p.Key,
p => (IReadOnlyList<ResearchBar>)[.. p.Value.Select((c, i) => Flat(Midnight(days[i]), c))],
StringComparer.Ordinal);
return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(days[0]), Midnight(days[^1]).AddDays(1), bars);
}
/// <summary>
/// 15-minute bars from <paramref name="first"/>, one per entry of <paramref name="bids"/>, with the ask given beside each
/// bid (open, high, low, close of both sides).
/// </summary>
public static BarDataset Quarters(DateTimeOffset first, IReadOnlyDictionary<string, (QuoteSide Bid, QuoteSide Ask)[]> quotes)
{
var bids = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var asks = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var length = 0;
foreach (var (symbol, rows) in quotes)
{
bids[symbol] = [.. rows.Select((r, i) => r.Bid.Bar(first.AddMinutes(15 * i)))];
asks[symbol] = [.. rows.Select((r, i) => r.Ask.Bar(first.AddMinutes(15 * i)))];
length = Math.Max(length, rows.Length);
}
return BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, first, first.AddMinutes(15 * length), bids, asks);
}
/// <summary>A quote whose four prices are one mid, with the bid half a spread below and the ask half above.</summary>
public static (QuoteSide Bid, QuoteSide Ask) Mid(decimal mid, decimal spread) => (QuoteSide.Flat(mid - (spread / 2)), QuoteSide.Flat(mid + (spread / 2)));
/// <summary>The 28 ECB-like crosses of seven synthetic rates against the euro, one fixing a weekday.</summary>
public static BarDataset Crosses(int days, int seed, double halfLife = 50, double volatility = 0.005, DateOnly? start = null)
{
var dates = Weekdays(start ?? new DateOnly(2020, 1, 6), days);
var levels = new Dictionary<string, double>(StringComparer.Ordinal)
{
["GBP"] = 0.86,
["AUD"] = 1.62,
["NZD"] = 1.78,
["USD"] = 1.10,
["CAD"] = 1.48,
["CHF"] = 0.97,
["JPY"] = 150,
};
var rates = new List<FxRate>();
var k = 0;
foreach (var (currency, level) in levels)
{
var path = Reverting(days, Synthetic.Phi(halfLife), seed + (k++ * 7919), volatility);
rates.AddRange(dates.Select((d, i) => new FxRate(Currencies.Eur, currency, d, Math.Round((decimal)(level * Math.Exp(path[i])), 6), "ecb")));
}
var crosses = EcbCrosses.Build(rates);
return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(dates[0]), Midnight(dates[^1]).AddDays(1), crosses);
}
/// <summary>A log series that reverts to zero: s(t) = φ·s(t−1) + σ·ε, from zero.</summary>
public static double[] Reverting(int bars, double phi, int seed, double volatility = 0.01)
{
var random = new Gen(seed);
var s = new double[bars];
for (var t = 1; t < bars; t++)
{
s[t] = (phi * s[t - 1]) + (volatility * random.Normal());
}
return s;
}
/// <summary>A log series that walks: s(t) = s(t−1) + drift + σ·ε, from zero.</summary>
public static double[] Walk(int bars, int seed, double drift = 0, double volatility = 0.01)
{
var random = new Gen(seed);
var s = new double[bars];
for (var t = 1; t < bars; t++)
{
s[t] = s[t - 1] + drift + (volatility * random.Normal());
}
return s;
}
/// <summary>Prices that alternate between two levels for <paramref name="count"/> bars: a window with a known spread.</summary>
public static IEnumerable<double> Alternate(double low, double high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
public static DateTimeOffset Midnight(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
private static ResearchBar Flat(DateTimeOffset at, double close)
{
var price = (decimal)close;
return new ResearchBar(at, price, price, price, price, 0m);
}
}
/// <summary>Open, high, low and close of one side of a quote.</summary>
internal readonly record struct QuoteSide(decimal Open, decimal High, decimal Low, decimal Close)
{
public static QuoteSide Flat(decimal price) => new(price, price, price, price);
public ResearchBar Bar(DateTimeOffset at) => new(at, Open, High, Low, Close, 0m);
}