Add the basket maths: server clock, relations, index, money rules, states

Pure code in src/Anubis/Baskets for the basket reversion family of the new
route, so the engine of phase 14 and the eToro Demo of phase 20 share one
home for the arithmetic of the research document:

- ServerClock: New York + 7 h, the server day changing at 17:00 New York,
  half-open weekend rule, hourly window and daily venue pause.
- Relations: chain, ratio and disjoint couples (56 + 112 + 210 = 378),
  appendix B in the document's row order, the eight documented spreads,
  the index sign and the 14-pair list.
- BasketIndex: pip and log basis-point index, sample z-score, Rvol with
  its filter, correlation of log returns and the OLS hedge ratio; every
  value at bar t reads bars up to t only.
- BasketMath (decimal): pip sum, common exit, distance scale with no
  addition after the last level, stop excursion of table 4.12, pip value,
  equal units raised to the venue minimum, exposure, three-costs rule.
- Styles: pair states, the four styles, the Fedele and Prudente profiles.

Every acceptance criterion of the item has a named test with the
document's numbers, plus a fixed-seed property test that nothing at a
closed bar depends on later bars.

refs #119

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 10:06:44 +01:00
1 parent f895c54076
commit aec848b4a2
9 files changed
+1884

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
using System.Globalization;
using Anubis.Baskets;
namespace Anubis.Tests;
/// <summary>
/// The statistics of the basket maths (Phase 12, issue #119): the index in pips and in log basis points, z-score, Rvol with
/// its filter and factors, correlation, the hedge ratio, the states of a pair, the four styles, the two profiles, and the
/// rule that nothing computed at a closed bar looks at a later one.
/// </summary>
[TestClass]
public sealed class BasketSignalTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePipIndexAddsTheLegsWithTheSignOfTheRelation()
{
var eurusd = FxPairs.Get("EURUSD");
var usdchf = FxPairs.Get("USDCHF");
// Chain, s = +1: 1.0856 / 0.0001 + 0.847 / 0.0001 = 10,856 + 8,470.
Assert.AreEqual(19_326, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, +1), 1e-9);
Assert.AreEqual(2_386, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, -1), 1e-9);
// Single symbol, and a yen pair with its 0.01 pip.
Assert.AreEqual(10_856, BasketIndex.Pips(1.0856, eurusd), 1e-9);
Assert.AreEqual(15_795, BasketIndex.Pips(157.95, FxPairs.Get("USDJPY")), 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLogIndexIsInBasisPoints()
{
// One basis point is 0.01%: a 1% rise of leg A is about 99.5 points.
Assert.AreEqual(10_000 * Math.Log(1.01), BasketIndex.LogBp(1.01, 1.0), 1e-9);
Assert.AreEqual(99.50330853168, BasketIndex.LogBp(1.01, 1.0), 1e-9);
Assert.AreEqual(10_000 * (Math.Log(50.0) - (1.5 * Math.Log(20.0))), BasketIndex.LogBp(50.0, 20.0, beta: 1.5), 1e-9);
Assert.AreEqual(10_000 * Math.Log(2.0), BasketIndex.LogBp(2.0), 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheZScoreUsesTheSampleDeviationOfTheLastWValuesIncludingTheBar()
{
double[] index = [7, 1, 2, 3, 4, 10];
// Last 5 values ending at t = 5: 1, 2, 3, 4, 10. Mean 4; squares 9 + 4 + 1 + 0 + 36 = 50; sample variance 50 / 4
// = 12.5; deviation 5 / √2; z = (10 − 4) / (5 / √2) = 6√2 / 5 = 1.6970562748.
Assert.AreEqual(1.6970562748477141, BasketIndex.ZScore(index, 5, window: 5)!.Value, 1e-12);
// At t = 4 the window is 7, 1, 2, 3, 4: mean 3.4, squares 12.96 + 5.76 + 1.96 + 0.16 + 0.36 = 21.2, variance 5.3.
Assert.AreEqual((4 - 3.4) / Math.Sqrt(5.3), BasketIndex.ZScore(index, 4, window: 5)!.Value, 1e-12);
// Fewer than W values, a flat window or a missing value: no z.
Assert.IsNull(BasketIndex.ZScore(index, 3, window: 5));
Assert.IsNull(BasketIndex.ZScore([5, 5, 5, 5, 5], 4, window: 5));
Assert.IsNull(BasketIndex.ZScore([1, 2, double.NaN, 4, 5], 4, window: 5));
Assert.AreEqual(100, BasketIndex.DefaultWindow);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RvolIsTheShortDeviationOverTheMedianOfItsBaseline()
{
// Index 0, 1, 3, 4, 6, 12: differences d1..d5 = 1, 2, 1, 2, 6. With 2 differences per short window the sample
// deviation of two values a, b is |a − b| / √2: σ(2) = σ(3) = σ(4) = 1 / √2, σ(5) = 4 / √2.
double[] index = [0, 1, 3, 4, 6, 12];
Assert.AreEqual(1 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 2, shortBars: 2)!.Value, 1e-12);
Assert.AreEqual(4 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 5, shortBars: 2)!.Value, 1e-12);
Assert.IsNull(BasketIndex.ShortSigma(index, 1, shortBars: 2));
// Baseline of 3: at t = 4 the median of σ(2), σ(3), σ(4) is 1 / √2, so Rvol = 1; at t = 5 the median of σ(3), σ(4),
// σ(5) is still 1 / √2, so Rvol = 4. At t = 3, σ(1) does not exist yet: no Rvol.
Assert.AreEqual(1.0, BasketIndex.Rvol(index, 4, baselineBars: 3, shortBars: 2)!.Value, 1e-12);
Assert.AreEqual(4.0, BasketIndex.Rvol(index, 5, baselineBars: 3, shortBars: 2)!.Value, 1e-12);
Assert.IsNull(BasketIndex.Rvol(index, 3, baselineBars: 3, shortBars: 2));
// A flat baseline has no Rvol.
Assert.IsNull(BasketIndex.Rvol([0, 1, 2, 3, 4, 5], 5, baselineBars: 3, shortBars: 2));
// An even baseline takes the mean of the two middle values: σ(4) and σ(5) → (1 + 4) / √2 / 2 against σ(5) = 4 / √2.
Assert.AreEqual(4.0 / 2.5, BasketIndex.Rvol(index, 5, baselineBars: 2, shortBars: 2)!.Value, 1e-12);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheDefaultRvolWindowsAreSixteenBarsAndTwentyDays()
{
Assert.AreEqual(16, BasketIndex.DefaultShortBars);
Assert.AreEqual(1920, BasketIndex.BaselineBars(barsPerDay: 96));
Assert.AreEqual(1920, BasketIndex.DefaultBaselineBars);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheVolatilityFilterBlocksNewEntriesAboveTwo()
{
Assert.IsTrue(BasketIndex.AllowsEntry(1.0));
Assert.IsTrue(BasketIndex.AllowsEntry(2.0));
Assert.IsFalse(BasketIndex.AllowsEntry(2.0001));
Assert.IsFalse(BasketIndex.AllowsEntry(4.0));
// Without enough history to know the volatility, no new entry.
Assert.IsFalse(BasketIndex.AllowsEntry(null));
Assert.IsFalse(BasketIndex.AllowsEntry(double.NaN));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(0.5, "1", "0.7")]
[DataRow(0.8, "1", "0.8")]
[DataRow(1.0, "1", "1")]
[DataRow(1.5, "1.5", "1.5")]
[DataRow(3.0, "3", "3")]
[DataRow(4.0, "3", "3")]
public void TheRvolFactorsAreClampedAsTheDocumentSays(double rvol, string distance, string target)
{
Assert.AreEqual(decimal.Parse(distance, CultureInfo.InvariantCulture), BasketMath.DistanceFactor(rvol));
Assert.AreEqual(decimal.Parse(target, CultureInfo.InvariantCulture), BasketMath.TargetFactor(rvol));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCorrelationIsPearsonOfLogReturnsOverTheWindow()
{
double[] a = [1.0, 1.1, 1.05, 1.2, 1.3];
var squared = a.Select(x => x * x).ToArray();
var inverse = a.Select(x => 1 / x).ToArray();
Assert.AreEqual(1.0, BasketIndex.Correlation(a, squared, 4, window: 4)!.Value, 1e-12);
Assert.AreEqual(-1.0, BasketIndex.Correlation(a, inverse, 4, window: 4)!.Value, 1e-12);
// Four returns need five prices; a flat leg has no correlation.
Assert.IsNull(BasketIndex.Correlation(a, squared, 3, window: 4));
Assert.IsNull(BasketIndex.Correlation(a, [2.0, 2.0, 2.0, 2.0, 2.0], 4, window: 4));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheHedgeRatioIsTheOlsSlopeOfLogPrices()
{
// ln A = ln 3 + 2 ln B exactly: β = 2.
double[] b = [1.0, 1.2, 0.9, 1.5, 1.1];
var a = b.Select(x => 3 * x * x).ToArray();
Assert.AreEqual(2.0, BasketIndex.HedgeRatio(a, b)!.Value, 1e-12);
Assert.IsNull(BasketIndex.HedgeRatio([1.0, 2.0], [3.0, 3.0]));
Assert.IsNull(BasketIndex.HedgeRatio([1.0], [3.0]));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(0.0, true, false, PairState.Idle)]
[DataRow(1.49, true, false, PairState.Idle)]
[DataRow(1.5, true, false, PairState.Watch)]
[DataRow(-1.5, true, false, PairState.Watch)]
[DataRow(1.99, true, false, PairState.Watch)]
[DataRow(2.0, true, false, PairState.Open)]
[DataRow(-2.0, true, false, PairState.Open)]
[DataRow(2.0, false, false, PairState.Armed)]
[DataRow(-2.5, false, false, PairState.Armed)]
[DataRow(0.1, false, true, PairState.Open)]
public void ThePairStatesFollowTheThresholds(double z, bool gatesPass, bool open, PairState expected)
{
Assert.AreEqual(expected, PairStates.Of(z, entryZ: 2.0, gatesPass, hasOpenUnit: open));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APairWithoutAZScoreIsIdle()
{
Assert.AreEqual(PairState.Idle, PairStates.Of(null, entryZ: 2.0, gatesPass: true));
Assert.AreEqual(1.5, PairStates.DefaultWatchZ);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSignalBuysTheSpreadLowAndSellsItHighAndTheSpreadClosesNearZero()
{
Assert.AreEqual(Direction.Buy, PairStates.Signal(-2.0, entryZ: 2.0));
Assert.AreEqual(Direction.Sell, PairStates.Signal(2.0, entryZ: 2.0));
Assert.IsNull(PairStates.Signal(1.99, entryZ: 2.0));
Assert.IsNull(PairStates.Signal(null, entryZ: 2.0));
Assert.IsTrue(PairStates.SpreadClosed(0.5));
Assert.IsTrue(PairStates.SpreadClosed(-0.5));
Assert.IsFalse(PairStates.SpreadClosed(0.51));
Assert.IsFalse(PairStates.SpreadClosed(null));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFourStylesCarryTheDocumentedValues()
{
(string Name, double EntryZ, int Spreads, int Averagings, int WithGrowth)[] expected =
[
("HedgeFund", 3.0, 1, 2, 2),
("Conservativo", 2.5, 2, 3, 3),
("Moderato", 2.0, 2, 3, 3),
("Aggressivo", 1.5, 3, 3, 4),
];
Assert.AreEqual(4, TradingStyles.All.Count);
for (var i = 0; i < expected.Length; i++)
{
var style = TradingStyles.All[i];
Assert.AreEqual(expected[i].Name, style.Name);
Assert.AreEqual(expected[i].EntryZ, style.EntryZ);
Assert.AreEqual(expected[i].Spreads, style.MaxOpenSpreads);
Assert.AreEqual(expected[i].Averagings, style.MaxAveragings);
Assert.AreEqual(expected[i].WithGrowth, style.MaxAveragingsWithGrowth);
}
Assert.AreSame(TradingStyles.Moderato, TradingStyles.Default);
Assert.AreSame(TradingStyles.Aggressivo, TradingStyles.Find("Aggressivo"));
Assert.IsNull(TradingStyles.Find("Spericolato"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTwoProfilesCarryTheDocumentedValues()
{
var fedele = BasketProfiles.Fedele;
Assert.AreEqual("Fedele", fedele.Name);
Assert.IsFalse(fedele.HasBasketStops());
Assert.AreEqual(0.09m, fedele.EquityStop);
Assert.IsTrue(fedele.ResumeAtNextServerDay);
Assert.IsFalse(fedele.CostGate);
Assert.IsNull(fedele.MaxCurrencyExposure);
Assert.IsTrue(fedele.OffRealAccountsOnly);
// The document's 1.5% basket loss is reduced to 1% by SPEC 9.2.
var prudente = BasketProfiles.Prudente;
Assert.AreEqual("Prudente", prudente.Name);
Assert.IsTrue(prudente.HasBasketStops());
Assert.AreEqual(3.5, prudente.StopZ);
Assert.AreEqual(0.01m, prudente.StopLoss);
Assert.IsTrue(prudente.StopOnBrokenRelation);
Assert.AreEqual(96, prudente.StopAfterBars);
Assert.IsTrue(prudente.CostGate);
Assert.AreEqual(2.0m, prudente.MaxCurrencyExposure);
Assert.AreEqual(0.09m, prudente.EquityStop);
Assert.IsTrue(prudente.ResumeAtNextServerDay);
Assert.IsFalse(prudente.OffRealAccountsOnly);
CollectionAssert.AreEqual(new[] { fedele, prudente }, BasketProfiles.All.ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NothingComputedAtABarDependsOnLaterBars()
{
var checkedValues = 0;
Property.ForAll(Walks, c =>
{
var past = c.Cut + 1;
var pastA = c.A[..past];
var pastB = c.B[..past];
var pastIndex = Index(pastA, pastB, c.Sign);
var fullIndex = Index(c.A, c.B, c.Sign);
var pastLog = pastA.Select((a, i) => BasketIndex.LogBp(a, pastB[i])).ToArray();
var fullLog = c.A.Select((a, i) => BasketIndex.LogBp(a, c.B[i])).ToArray();
Assert.AreEqual(pastIndex[c.Cut], fullIndex[c.Cut]);
Assert.AreEqual(pastLog[c.Cut], fullLog[c.Cut]);
var z = BasketIndex.ZScore(pastIndex, c.Cut, window: 20);
Assert.AreEqual(z, BasketIndex.ZScore(fullIndex, c.Cut, window: 20));
Assert.AreEqual(BasketIndex.ZScore(pastLog, c.Cut, window: 20), BasketIndex.ZScore(fullLog, c.Cut, window: 20));
var rvol = BasketIndex.Rvol(pastIndex, c.Cut, baselineBars: 12, shortBars: 4);
Assert.AreEqual(rvol, BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4));
var rho = BasketIndex.Correlation(pastA, pastB, c.Cut, window: 20);
Assert.AreEqual(rho, BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20));
var gates = BasketIndex.AllowsEntry(rvol) && rho is not null;
var pastState = PairStates.Of(z, entryZ: 2.0, gates, watchZ: 1.0);
var fullState = PairStates.Of(
BasketIndex.ZScore(fullIndex, c.Cut, window: 20),
entryZ: 2.0,
BasketIndex.AllowsEntry(BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4))
&& BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20) is not null,
watchZ: 1.0);
Assert.AreEqual(pastState, fullState);
if (z is not null && rvol is not null && rho is not null)
{
checkedValues++;
}
});
// The property is not empty: most cases have every statistic defined.
Assert.IsTrue(checkedValues > Property.DefaultCases / 2, checkedValues.ToString(CultureInfo.InvariantCulture));
}
private static double[] Index(double[] a, double[] b, int sign) =>
[.. a.Select((price, i) => BasketIndex.Pips(price, FxPairs.Get("EURUSD"), b[i], FxPairs.Get("USDCHF"), sign))];
private static Walk Walks(Gen gen)
{
var length = gen.Int(40, 120);
var future = gen.Int(1, 40);
var a = new double[length + future];
var b = new double[length + future];
a[0] = 1.1;
b[0] = 0.9;
for (var i = 1; i < a.Length; i++)
{
a[i] = a[i - 1] * Math.Exp(0.002 * gen.Normal());
b[i] = b[i - 1] * Math.Exp(0.002 * gen.Normal());
}
return new Walk(a, b, gen.Bool() ? 1 : -1, gen.Int(length / 2, length));
}
/// <summary>Two price walks; bars after <see cref="Cut"/> are the future that must not matter.</summary>
private sealed record Walk(double[] A, double[] B, int Sign, int Cut)
{
public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{A.Length} barre, taglio {Cut}, segno {Sign}");
}
}