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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 18:17:13 +01:00
1 parent 63bd5b9635
commit 44639e3f49
10 files changed
+2631

No files matched your search

+452
View File
@@ -0,0 +1,452 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The basket engine of Phase 14 (issue #127): a margin account with independent positions, bought at the ask and sold at the
/// bid, the venue's mandatory stop, liquidation, financing, the document's account rules (9% stop, 2% gate) and, «come dal
/// vivo», the limits of SPEC 9.2 and of the plan's margin table. Every money figure is computed by hand in the comment next
/// to it; the comparison configuration is checked against the stylised replica of appendix G.
/// </summary>
[TestClass]
public sealed class BasketEngineTests
{
private static readonly FxPair EurUsd = FxPairs.Get("EURUSD");
private static readonly FxPair UsdChf = FxPairs.Get("USDCHF");
private static readonly FxPair UsdJpy = FxPairs.Get("USDJPY");
private static readonly FxPair GbpUsd = FxPairs.Get("GBPUSD");
[TestMethod]
[TestCategory(Category.Unit)]
public void AToyTwoLegBasketGivesTheResultComputedByHand()
{
// Tuesday 10 March 2026 from 10:00 UTC (06:00 in New York): no pause, no weekend, no rollover (21:00 UTC).
// EURUSD bid/ask one pip wide, USDCHF two pips. Bars 0–9 alternate, so the chain index X = E/pip + C/pip alternates
// 19,000 / 19,004; bar 10 drops to 18,985: z = −2.67 over 10 bars, the spread is bought (both legs long, chain s = +1).
var first = new DateTimeOffset(2026, 3, 10, 10, 0, 0, TimeSpan.Zero);
decimal[] e = [.. Alt(1.1000m, 1.1002m, 10), 1.0990m, 1.0990m, 1.0997m, 1.0998m, 1.1000m];
decimal[] c = [.. Alt(0.8000m, 0.8002m, 10), 0.7995m, 0.7995m, 0.8000m, 0.8001m, 0.8003m];
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
{
["EURUSD"] = [.. e.Select(m => BasketSynthetic.Mid(m, 0.0001m))],
["USDCHF"] = [.. c.Select(m => BasketSynthetic.Mid(m, 0.0002m))],
});
var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
LotPer10k = 0.1m,
Mode = BasketMode.AsDocument,
MaxRvol = null,
MinCorrelation = null,
};
var result = Run(data, rules, VenueCosts.Etoro, 100_000m);
// Units: 0.1 × 100,000 / 10,000 × 100,000 = 100,000 on each leg (EUR 1.0990 and USD 1 both above 1,000 USD).
// Filled at bar 11's open: EURUSD bought at the ask 1.09905, USDCHF at the ask 0.7996.
// Bar 12 close: pips (1.09965 − 1.09905) + (0.7999 − 0.7996) = 6 + 3 = 9 < 10; bar 13: 7 + 4 = 11 ≥ 10: target.
// Sold at bar 14's open at the bid: EURUSD 1.09995, USDCHF 0.8002.
// EURUSD: 100,000 × 0.0009 = 90.00 USD. USDCHF: 100,000 × 0.0006 = 60 CHF ÷ 0.8003 (the mid at the exit) = 74.9719 USD.
// Commission 0.005% a side on the USD exposure at the mid: opening 109,900 → 5.495 and 100,000 → 5.00; closing
// 110,000 → 5.50 and 100,000 → 5.00; together 20.995. No rollover crossed: no financing.
// Result: 90 + 74.97188554 − 20.995 = 143.97688554 → 143.98 USD.
var basket = result.Run.Baskets.Single();
Assert.AreEqual(BasketReasons.Target, basket.ExitReason);
Assert.AreEqual(1, basket.Levels);
Assert.AreEqual(100_000m, basket.Units);
Assert.AreEqual(143.98m, Math.Round(basket.Result, 2));
Assert.AreEqual(143.98m, Math.Round(result.Run.NetResult, 2));
Assert.AreEqual(20.995m, result.Commission);
Assert.AreEqual(0m, result.Financing);
Assert.AreEqual(20.995m, result.Run.Fees);
var fills = result.Run.Fills;
Assert.AreEqual(4, fills.Count);
Assert.AreEqual(1.09905m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Buy).Price);
Assert.AreEqual(0.7996m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Buy).Price);
Assert.AreEqual(1.09995m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Sell).Price);
Assert.AreEqual(0.8002m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Sell).Price);
var trace = result.Traces.Single();
Assert.AreEqual(11, trace.Positions[0].EntryBar);
Assert.AreEqual(14, trace.Positions[0].ExitBar);
Assert.AreEqual(143.98m, Math.Round(trace.Positions.Sum(p => p.Result), 2));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheAccountStopFiresAtTheExactThresholdAndResumesAtTheServerDayChange()
{
// Tuesday 13 January 2026 from 13:00 UTC (08:00 New York); the server day changes at 17:00 New York, 22:00 UTC.
// 100,000 EURUSD bought at exactly 1.0000 on bar 11 (no spread, no cost): balance 10,000.
// Bar 11 closes at 0.99101: open loss 899 / 10,000 = 8.99%, nothing. Bar 12 closes at 0.9910: 9.00%, the stop fires.
var first = new DateTimeOffset(2026, 1, 13, 13, 0, 0, TimeSpan.Zero);
var rows = new List<(QuoteSide, QuoteSide)>();
rows.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
rows.Add(BasketSynthetic.Mid(0.9990m, 0m));
rows.Add(Same(new QuoteSide(1.0000m, 1.0000m, 0.99101m, 0.99101m)));
rows.Add(Same(new QuoteSide(0.99101m, 0.99101m, 0.9910m, 0.9910m)));
rows.AddRange(Alt(0.9910m, 0.9911m, 12).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 13–24
rows.Add(BasketSynthetic.Mid(0.9890m, 0m)); // bar 25, 19:15 UTC: a signal
rows.AddRange(Alt(0.9890m, 0.9891m, 10).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 26–35
rows.Add(BasketSynthetic.Mid(0.9870m, 0m)); // bar 36, 22:00 UTC: a signal
rows.Add(BasketSynthetic.Mid(0.9870m, 0m));
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]> { ["EURUSD"] = [.. rows] });
var rules = SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m, ClockWindows = false };
var result = Run(data, rules, VenueCosts.None);
var stops = result.Events.Where(x => x.Reason == BasketReasons.AccountStop).ToList();
Assert.AreEqual(1, stops.Count, "8.99% does not fire, 9.00% does");
var trigger = first.AddMinutes(15 * 13);
Assert.AreEqual(trigger, stops[0].At, "at the close of bar 12");
Assert.AreEqual(BasketReasons.AccountStop, result.Run.Baskets[0].ExitReason);
Assert.AreEqual(-900m, result.Run.Baskets[0].Result);
var resume = ServerClock.NextDayStart(trigger);
Assert.AreEqual(new DateTimeOffset(2026, 1, 13, 22, 0, 0, TimeSpan.Zero), resume);
var paused = result.Events.Single(x => x.Reason == BasketReasons.PausedUntilNextDay);
Assert.AreEqual(first.AddMinutes(15 * 26), paused.At, "the signal of bar 25 is refused");
Assert.IsFalse(result.Events.Any(x => x.Kind is BasketEventKinds.Open or BasketEventKinds.Add && x.At > trigger && x.At <= resume));
var reopened = result.Events.Where(x => x.Kind == BasketEventKinds.Open && x.At > trigger).ToList();
Assert.AreEqual(1, reopened.Count);
Assert.AreEqual(resume.AddMinutes(15), reopened[0].At, "the first bar of the next server day opens");
// During the daily pause the stop reads mid prices: a bid of 0.9900 and an ask of 1.0100 around a mid of 1.0000 would
// be a 10% loss at the bid, but the mid has not moved. The same quote outside the pause fires the stop.
Assert.AreEqual(0, PauseRun(wideAt: 16).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 16 closes at 17:15 New York: in the pause");
Assert.AreEqual(1, PauseRun(wideAt: 12).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 12 closes at 16:15 New York: outside");
static BasketRunResult PauseRun(int wideAt)
{
var start = new DateTimeOffset(2026, 1, 13, 18, 0, 0, TimeSpan.Zero);
var quotes = new List<(QuoteSide, QuoteSide)>();
quotes.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
quotes.Add(BasketSynthetic.Mid(0.9990m, 0m));
for (var t = 11; t < 20; t++)
{
quotes.Add(t == wideAt ? BasketSynthetic.Mid(1.0000m, 0.0200m) : BasketSynthetic.Mid(1.0000m, 0m));
}
var pauseData = BasketSynthetic.Quarters(start, new Dictionary<string, (QuoteSide, QuoteSide)[]> { ["EURUSD"] = [.. quotes] });
return Run(pauseData, SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m }, VenueCosts.None);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTwoPercentGateStopsNewBasketsButLetsAveragingThrough()
{
// 15,000 EURUSD bought at 0.9985; bar 12 closes at 0.9840: open loss 217.50 / 10,000 = 2.175%. The averaging rule
// holds (−145 pips ≤ −15, z still ≤ −2) and goes through; USDJPY's signal on the same bar is refused by the gate.
var result = Run(GateData(), GateRules(BasketMode.AsDocument), VenueCosts.None);
var eur = result.Traces.Single(x => x.Unit == "EURUSD");
Assert.AreEqual(2, eur.Levels);
Assert.AreEqual(13, eur.Positions[1].EntryBar);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
var refused = result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused);
Assert.AreEqual(BasketReasons.GateOpenLoss, refused.Reason);
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.GateOpenLoss));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveADayAtMinusTwoPercentStopsAveragingToo()
{
// The same days «come dal vivo»: the equity falls from 10,000 to 9,782.50 in one day (−2.175%), so SPEC 9.2 blocks new
// baskets and averaging for 24 hours.
var result = Run(GateData(), GateRules(BasketMode.AsLive), VenueCosts.None);
var eur = result.Traces.Single(x => x.Unit == "EURUSD");
Assert.AreEqual(1, eur.Levels);
Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused).Reason);
Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused).Reason);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveHalfSizeAndQuarterSizeFollowSpec92()
{
// 10,000 EURUSD bought at 0.9985 fall 6% in a day: the Prudente basket stop closes them (5.99% of equity, over 1%).
// The week is −5.99%: SPEC 9.2 halves the size for seven days, so GBPUSD three days later opens 5,000 units, not 10,000.
var half = Run(SizeData(0.06), SizeRules(), VenueCosts.None);
var gbp = half.Traces.Single(x => x.Unit == "GBPUSD");
Assert.AreEqual(5_000m, gbp.Positions[0].Units);
Assert.AreEqual(BasketReasons.StopBasket, half.Run.Baskets[0].ExitReason);
Assert.AreEqual(1, half.Run.Notes.Count(n => n.Reason == BasketReasons.HalfSize));
// An 11% fall: the 9% account stop closes everything; the week is −10.98% and so is the fall from the high: both halve,
// a quarter together. 2,500 units.
var quarter = Run(SizeData(0.11), SizeRules(), VenueCosts.None);
Assert.AreEqual(BasketReasons.AccountStop, quarter.Run.Baskets[0].ExitReason);
Assert.AreEqual(2_500m, quarter.Traces.Single(x => x.Unit == "GBPUSD").Positions[0].Units);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveALevelBelowTheVenueMinimumDoesNotStart()
{
// With 1,000 USD of capital the lot gives 1,000 units (EURUSD raised to 1,002 to reach 1,000 USD). After the 6% fall
// the GBPUSD level would be 500 units, 649.25 USD: under the venue minimum of 1,000 USD, so it does not start.
var result = Run(SizeData(0.06), SizeRules(), VenueCosts.None, 1_000m);
Assert.AreEqual(1_002m, result.Traces.Single(x => x.Unit == "EURUSD").Positions[0].Units);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "GBPUSD"));
Assert.AreEqual(BasketReasons.BelowVenueMinimum, result.Events.Single(x => x.Unit == "GBPUSD" && x.Kind == BasketEventKinds.Refused).Reason);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveTheMarginLimitAndThePositionLimitRefuseEntries()
{
// Ten pairs signal on the same bar. With 0.01 lots every level is small: nine open, the tenth would be the tenth
// position of the shared Demo and is refused.
var data = TenPairs();
var small = Run(data, TenRules(0.01m), VenueCosts.None);
Assert.AreEqual(9, small.Events.Count(x => x.Kind == BasketEventKinds.Open));
Assert.AreEqual(BasketReasons.PositionLimit, small.Events.Single(x => x.Kind == BasketEventKinds.Refused).Reason);
// With 0.05 lots the margin committed reaches 40% of the equity first: the levels after it are refused.
var large = Run(data, TenRules(0.05m), VenueCosts.None);
var opened = large.Events.Count(x => x.Kind == BasketEventKinds.Open);
Assert.IsTrue(opened is > 0 and < 9, $"{opened} opened");
Assert.IsTrue(large.Events.Where(x => x.Kind == BasketEventKinds.Refused).All(x => x.Reason == BasketReasons.MarginLimit));
Assert.AreEqual(10 - opened, large.Events.Count(x => x.Reason == BasketReasons.MarginLimit));
var margin = large.Run.Equity.Max(p => p.Invested);
Assert.IsTrue(margin <= 0.40m * 10_000m, $"margin {margin}");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveNoOppositePositionOnTheSameInstrument()
{
// The chain EURUSD + USDCHF is bought on bar 10 (long EURUSD). On bar 12 EURUSD alone signals a sale: «come dal vivo»
// it would face the long EURUSD of the chain and is refused; «alla lettera» it opens.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.1000, 1.1000, .. Enumerable.Repeat(1.1040, 8)];
double[] c = [.. BasketSynthetic.Alternate(0.8000, 0.8002, 10), .. Enumerable.Repeat(0.7960, 10)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["USDCHF"] = c });
var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf), BasketUnit.OnePair(EurUsd)])
{
Window = 10,
Target = 1_000m,
Distance = 1_000m,
MaxOpenBaskets = 5,
MaxRvol = null,
MinCorrelation = null,
};
var live = Run(data, rules with { Mode = BasketMode.AsLive }, VenueCosts.None);
var refused = live.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused);
Assert.AreEqual(BasketReasons.OppositePosition, refused.Reason);
Assert.AreEqual(1, live.Traces.Count);
var letter = Run(data, rules with { Mode = BasketMode.AsDocument }, VenueCosts.None);
Assert.AreEqual(2, letter.Traces.Count);
Assert.AreEqual(-1, letter.Traces.Single(x => x.Unit == "EURUSD").Direction);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void LiquidationClosesEverythingBelowHalfTheMargin()
{
// 1,000 USD of capital, 9,000 EURUSD bought at the ask 0.998505: exposure 8,986.50 at the mid, margin at leverage 5
// 1,797.30, half of it 898.65. A fall of 1.5% in a day leaves about 862 of equity: below half the margin, every
// position closes at that close. A fall of 1.0% leaves about 906.5 (balance 999.55 less four nights of financing,
// 2.91, less 90.09 at the bid): no liquidation, but the 9% account stop (90.09 / 996.64 = 9.04%).
var deep = Run(LiquidationData(0.9835), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
Assert.AreEqual(BasketReasons.Liquidation, deep.Run.Baskets.Single().ExitReason);
Assert.AreEqual(12, deep.Traces.Single().Positions.Single().ExitBar);
Assert.AreEqual(0.983495m, deep.Traces.Single().Positions.Single().ExitPrice, "the bid of that close");
Assert.AreEqual(1, deep.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
var shallow = Run(LiquidationData(0.9885), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
Assert.AreEqual(BasketReasons.AccountStop, shallow.Run.Baskets.Single().ExitReason);
Assert.AreEqual(0, shallow.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
}
[TestMethod]
[TestCategory(Category.Golden)]
public void TheEngineInItsComparisonSettingMatchesTheReplicaOnTwoHundredSeries()
{
// 200 seeded series: AR(1) with half-lives 20–100, driftless and drifting walks, 600–1,500 bars, prices exp(s) on
// EURUSD. Three cases of table G.4 (no stop, a stop of 90, a stop of 30 with growth): the engine, deciding and filling
// on the same close with no cost and no account rule, must make the replica's baskets, and its result in targets
// computed from the fill prices must be the replica's total.
var cases = new[] { ReplicaSettings.DocumentCases[0], ReplicaSettings.DocumentCases[4], ReplicaSettings.DocumentCases[14] };
// The series are independent: they run in parallel, each with its own assertions.
var baskets = 0;
Parallel.For(0, 200, i =>
{
var bars = 600 + (i * 900 / 199);
var s = (i % 4) switch
{
0 or 1 => BasketSynthetic.Reverting(bars, Synthetic.Phi(20 + (i % 5 * 20)), 1_000 + i, 0.005),
2 => BasketSynthetic.Walk(bars, 1_000 + i, 0, 0.005),
_ => BasketSynthetic.Walk(bars, 1_000 + i, i % 8 == 3 ? 0.0005 : -0.0005, 0.005),
};
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = [.. s.Select(x => 1.1 * Math.Exp(x))] });
var logs = data.Bars("EURUSD").Close.Select(x => Math.Log(x)).ToArray();
var market = BasketMarket.Of(data);
foreach (var c in cases)
{
var replica = StylisedReplica.Run(logs, c.Settings);
var engine = new BasketEngine(market, VenueCosts.None, 10_000m).Run(BasketRules.Comparison(EurUsd, c.Settings));
Assert.AreEqual(replica.Baskets, engine.Traces.Count, $"series {i}, {c.Label} {c.StopLabel}: baskets");
var total = 0d;
for (var k = 0; k < replica.List.Count; k++)
{
var r = replica.List[k];
var x = engine.Traces[k];
var where = $"series {i}, {c.Label} {c.StopLabel}, basket {k}";
Assert.AreEqual(r.Direction, x.Direction, where);
CollectionAssert.AreEqual(r.EntryBars.ToArray(), x.Positions.Select(p => p.EntryBar).ToArray(), where);
Assert.AreEqual(r.ClosedAt, x.ExitBar, where);
Assert.AreEqual(r.Exit switch { ReplicaExits.Target => BasketReasons.Target, ReplicaExits.Stop => BasketReasons.StopBasket, _ => BasketReasons.End }, x.ExitReason, where);
// One target is k_T × σ of ln(price); the engine's σ is that of 10,000 · ln(price).
var target = c.Settings.TargetSigma * x.Sigma / 10_000;
total += x.Positions.Sum(p => x.Direction * (Math.Log((double)p.ExitPrice!.Value) - Math.Log((double)p.EntryPrice)) / target);
}
Assert.AreEqual(replica.Total, total, 1e-9, $"series {i}, {c.Label} {c.StopLabel}: total");
Interlocked.Add(ref baskets, replica.Baskets);
}
});
Assert.IsTrue(baskets > 5_000, $"{baskets} baskets compared");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void FiveNightsAreChargedFromTuesdayToFridayInTheEngine()
{
// Monday 19 January 2026 EURUSD fixes at 1.0985 against a window around 1.1001: z ≤ −2, buy. Filled on Tuesday's
// fixing (00:00 UTC) at the ask 1.098505; Thursday's fixing 1.1000 gives 14.9 pips ≥ 10: sold on Friday's (00:00 UTC).
// Rollovers crossed: Tuesday's (1), Wednesday's (3), Thursday's (1): five nights at the buy rate of 8.096 USD per
// 100,000. Exposure at Tuesday's mid: 1,000 × 1.0985 = 1,098.50 USD; financing 1,098.50 / 100,000 × 8.096 × 5 = 0.4446728.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.0985, 1.0985, 1.0985, .. Enumerable.Repeat(1.1000, 7)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument), VenueCosts.Etoro);
var position = result.Traces.Single().Positions.Single();
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 20)), position.EntryAt);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 23)), position.ExitAt);
Assert.AreEqual(1_098.5m / 100_000m * 8.096m * 5, position.Financing);
Assert.AreEqual(0.4446728m, result.Financing);
Assert.AreEqual(VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_098.5m, 5), result.Financing);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheRollingRvolEqualsTheReference()
{
foreach (var (baseline, shortBars) in new[] { (20, 16), (50, 8) })
{
var x = BasketSynthetic.Walk(400, baseline, 0, 0.3);
var rolling = BasketIndex.RollingRvol(x, baseline, shortBars);
for (var t = 0; t < x.Length; t++)
{
var reference = BasketIndex.Rvol(x, t, baseline, shortBars);
Assert.AreEqual(reference ?? double.NaN, rolling[t], $"t {t}");
}
}
}
// ----- data of the tests -----
private static BasketRunResult Run(BarDataset data, BasketRules rules, VenueCosts costs, decimal capital = 10_000m) =>
new BasketEngine(BasketMarket.Of(data), costs, capital).Run(rules);
/// <summary>A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.</summary>
private static BasketRules SingleRules(FxPair pair, BasketMode mode) => new([BasketUnit.OnePair(pair)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
Mode = mode,
MaxRvol = null,
};
private static BarDataset GateData()
{
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(0.9840, 8)];
double[] j = [.. BasketSynthetic.Alternate(150.00, 150.02, 12), .. Enumerable.Repeat(149.80, 8)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["USDJPY"] = j });
}
private static BasketRules GateRules(BasketMode mode) => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(UsdJpy)])
{
Window = 10,
Target = 10m,
Distance = 15m,
LotPer10k = 0.15m,
Mode = mode,
MaxRvol = null,
};
private static BarDataset SizeData(double gap)
{
var low = 0.9985 * (1 - gap);
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(low, 18)];
double[] g = [.. BasketSynthetic.Alternate(1.3000, 1.3002, 15), .. Enumerable.Repeat(1.2985, 15)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["GBPUSD"] = g });
}
private static BasketRules SizeRules() => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(GbpUsd)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
LotPer10k = 0.1m,
Mode = BasketMode.AsLive,
Profile = BasketProfiles.Prudente,
MaxRvol = null,
};
private static BarDataset TenPairs()
{
var levels = new Dictionary<string, double>(StringComparer.Ordinal)
{
["EURUSD"] = 1.10,
["GBPUSD"] = 1.30,
["AUDUSD"] = 0.66,
["NZDUSD"] = 0.60,
["USDCAD"] = 1.40,
["USDCHF"] = 0.85,
["USDJPY"] = 150,
["EURGBP"] = 0.846,
["EURJPY"] = 165,
["GBPJPY"] = 195,
};
return BasketSynthetic.Daily(levels.ToDictionary(
l => l.Key,
l => (double[])[.. BasketSynthetic.Alternate(l.Value, l.Value * 1.0002, 10), .. Enumerable.Repeat(l.Value * 0.9985, 10)],
StringComparer.Ordinal));
}
private static BasketRules TenRules(decimal lot) => new([.. TenPairs().Symbols.Select(s => BasketUnit.OnePair(FxPairs.Get(s)))])
{
Window = 10,
Target = 1_000m,
Distance = 1_000m,
LotPer10k = lot,
MaxOpenBaskets = 20,
Mode = BasketMode.AsLive,
MaxRvol = null,
};
private static BarDataset LiquidationData(double fall)
{
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(fall, 8)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
}
private static IEnumerable<decimal> Alt(decimal low, decimal high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
private static (QuoteSide, QuoteSide) Same(QuoteSide side) => (side, side);
}
+138
View File
@@ -0,0 +1,138 @@
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);
}