diff --git a/src/Anubis/Baskets/BasketIndex.cs b/src/Anubis/Baskets/BasketIndex.cs new file mode 100644 index 0000000..4ab6d37 --- /dev/null +++ b/src/Anubis/Baskets/BasketIndex.cs @@ -0,0 +1,241 @@ +namespace Anubis.Baskets; + +/// +/// The index of a relation and the statistics on it (sections 4.2, 4.3, 4.7 and 11.3, appendix C): the index in pips and in +/// log basis points, the z-score, the relative volatility Rvol with its filter, the correlation of log returns and the hedge +/// ratio. Statistics are . Every value at bar t reads bars up to t only; which price feeds the index (mid +/// when bid and ask exist, bid otherwise) is the caller's choice. A missing value (not a number) inside a window gives null. +/// +public static class BasketIndex +{ + /// Bars of the z-score window: 100 bars of 15 minutes, 25 hours. + public const int DefaultWindow = 100; + + /// Differences in the short volatility window: 16 bars of 15 minutes, 4 hours. + public const int DefaultShortBars = 16; + + /// Market days of the volatility baseline. + public const int DefaultBaselineDays = 20; + + /// Bars of the baseline for 15-minute bars on a 24×5 market: 20 days × 96 bars. + public const int DefaultBaselineBars = DefaultBaselineDays * 96; + + /// Above this Rvol no new entry opens. + public const double DefaultMaxRvol = 2.0; + + private const double BasisPoints = 10_000; + + /// The pip index of two legs: X = A / pip(A) + s · B / pip(B). + public static double Pips(double priceA, FxPair a, double priceB, FxPair b, int sign) + { + ArgumentNullException.ThrowIfNull(b); + return Pips(priceA, a) + (sign * priceB / (double)b.Pip); + } + + /// The pip index of a single symbol: X = A / pip(A). + public static double Pips(double price, FxPair pair) + { + ArgumentNullException.ThrowIfNull(pair); + return price / (double)pair.Pip; + } + + /// + /// The log index in basis points (section 11.3): X = 10,000 · (ln A − β · ln B), β = 1 unless a hedge ratio is given. + /// For a relation of the 28 pairs in log form pass β = −s. + /// + public static double LogBp(double priceA, double priceB, double beta = 1) => BasisPoints * (Math.Log(priceA) - (beta * Math.Log(priceB))); + + /// The log index of a single symbol: X = 10,000 · ln P. + public static double LogBp(double price) => BasisPoints * Math.Log(price); + + /// + /// The z-score at closed bar : (X(t) − mean) / sample standard deviation (n − 1) of the last + /// values, bar t included. Null with fewer values than the window or a flat window. + /// + public static double? ZScore(IReadOnlyList index, int t, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + if (!Within(index, t) || t + 1 < window) + { + return null; + } + + var deviation = Deviation(index, t - window + 1, t, out var mean); + return deviation is > 0 ? (index[t] - mean) / deviation : null; + } + + /// + /// σ_short at bar : the sample standard deviation of the last first + /// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter. + /// + public static double? ShortSigma(IReadOnlyList index, int t, int shortBars = DefaultShortBars) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(shortBars, 2); + if (!Within(index, t) || t < shortBars) + { + return null; + } + + var differences = new double[shortBars]; + for (var i = 0; i < shortBars; i++) + { + var at = t - shortBars + 1 + i; + differences[i] = index[at] - index[at - 1]; + } + + return Deviation(differences, 0, shortBars - 1, out _); + } + + /// Bars of the volatility baseline for a market with bars a day. + public static int BaselineBars(int barsPerDay, int days = DefaultBaselineDays) => barsPerDay * days; + + /// + /// Rvol at bar : σ_short(t) over σ_base(t), the median of σ_short over the last + /// bars ending at t. Null without enough history for every σ_short of the baseline, or + /// when σ_base is zero. + /// + public static double? Rvol(IReadOnlyList index, int t, int baselineBars = DefaultBaselineBars, int shortBars = DefaultShortBars) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(baselineBars, 1); + if (!Within(index, t) || t - baselineBars + 1 < shortBars) + { + return null; + } + + var sigmas = new double[baselineBars]; + for (var i = 0; i < baselineBars; i++) + { + if (ShortSigma(index, t - baselineBars + 1 + i, shortBars) is not { } sigma) + { + return null; + } + + sigmas[i] = sigma; + } + + var current = sigmas[^1]; + Array.Sort(sigmas); + var middle = baselineBars / 2; + var baseline = baselineBars % 2 == 1 ? sigmas[middle] : (sigmas[middle - 1] + sigmas[middle]) / 2; + return baseline > 0 ? current / baseline : null; + } + + /// The volatility filter: a new entry only with a known Rvol no higher than . + public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max; + + /// + /// Pearson correlation of the log returns of two price series over the last returns ending at + /// bar (window + 1 prices). Null without enough prices, with a missing price or a flat leg. + /// + public static double? Correlation(IReadOnlyList pricesA, IReadOnlyList pricesB, int t, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(pricesA); + ArgumentNullException.ThrowIfNull(pricesB); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + if (!Within(pricesA, t) || !Within(pricesB, t) || t < window) + { + return null; + } + + var x = new double[window]; + var y = new double[window]; + for (var i = 0; i < window; i++) + { + var at = t - window + 1 + i; + x[i] = Math.Log(pricesA[at] / pricesA[at - 1]); + y[i] = Math.Log(pricesB[at] / pricesB[at - 1]); + } + + return Pearson(x, y); + } + + /// + /// The hedge ratio β of a statistical relation: the slope of the least-squares regression of ln A on ln B over the + /// formation window given. It stays fixed until the next reselection. Null with fewer than two points or a flat B. + /// + public static double? HedgeRatio(IReadOnlyList pricesA, IReadOnlyList pricesB) + { + ArgumentNullException.ThrowIfNull(pricesA); + ArgumentNullException.ThrowIfNull(pricesB); + if (pricesA.Count != pricesB.Count) + { + throw new ArgumentException("Le due serie del rapporto di copertura devono avere la stessa lunghezza.", nameof(pricesB)); + } + + if (pricesA.Count < 2) + { + return null; + } + + var y = pricesA.Select(p => Math.Log(p)).ToArray(); + var x = pricesB.Select(p => Math.Log(p)).ToArray(); + if (!y.All(double.IsFinite) || !x.All(double.IsFinite)) + { + return null; + } + + var meanX = x.Average(); + var meanY = y.Average(); + var covariance = 0d; + var variance = 0d; + for (var i = 0; i < x.Length; i++) + { + covariance += (x[i] - meanX) * (y[i] - meanY); + variance += (x[i] - meanX) * (x[i] - meanX); + } + + return variance > 0 ? covariance / variance : null; + } + + private static bool Within(IReadOnlyList values, int t) => t >= 0 && t < values.Count; + + /// Sample standard deviation of values[from..to]; null when a value is missing. + private static double? Deviation(IReadOnlyList values, int from, int to, out double mean) + { + var count = to - from + 1; + var sum = 0d; + for (var i = from; i <= to; i++) + { + sum += values[i]; + } + + mean = sum / count; + if (!double.IsFinite(mean)) + { + return null; + } + + var squares = 0d; + for (var i = from; i <= to; i++) + { + squares += (values[i] - mean) * (values[i] - mean); + } + + return Math.Sqrt(squares / (count - 1)); + } + + private static double? Pearson(double[] x, double[] y) + { + var meanX = x.Average(); + var meanY = y.Average(); + if (!double.IsFinite(meanX) || !double.IsFinite(meanY)) + { + return null; + } + + var sxy = 0d; + var sxx = 0d; + var syy = 0d; + for (var i = 0; i < x.Length; i++) + { + sxy += (x[i] - meanX) * (y[i] - meanY); + sxx += (x[i] - meanX) * (x[i] - meanX); + syy += (y[i] - meanY) * (y[i] - meanY); + } + + return sxx > 0 && syy > 0 ? Math.Clamp(sxy / Math.Sqrt(sxx * syy), -1, 1) : null; + } +} diff --git a/src/Anubis/Baskets/BasketMath.cs b/src/Anubis/Baskets/BasketMath.cs new file mode 100644 index 0000000..df3ec60 --- /dev/null +++ b/src/Anubis/Baskets/BasketMath.cs @@ -0,0 +1,237 @@ +namespace Anubis.Baskets; + +/// Buying or selling (section 4.4): a bought (long) order gains when the price rises, a sold (short) one when it falls. +public enum Direction +{ + Buy, + Sell, +} + +/// The two prices of a quote (section 4.5): a bought order closes at the bid, a sold one at the ask. +public readonly record struct BidAsk(decimal Bid, decimal Ask); + +/// One open order of a basket (section 4.5): pair, direction and entry price. +public sealed record BasketOrder(FxPair Pair, Direction Side, decimal Entry) +{ + /// Pips of the order at a quote: long (bid − entry) / pip, short (entry − ask) / pip. + public decimal Pips(BidAsk quote) => BasketMath.OrderPips(Side, Entry, quote, Pair.Pip); +} + +/// A leg for the exposure per currency (section 4.4, appendix C): units of the base at a price. +public sealed record ExposureLeg(FxPair Pair, Direction Side, decimal Units, decimal Price); + +/// Units on each leg of a unit (section 6.4); when the venue minimum lifted them. +public sealed record LegUnits(decimal Units, bool Raised) +{ + /// The effective lot the ledger records: units / 100,000. + public decimal Lot() => Units / BasketMath.LotUnits; +} + +/// +/// The money arithmetic of a basket, all in (sections 4.5, 4.6, 4.12, 6.4, 6.9 and 11.3, appendices A +/// and C): pip sum, common exit price, distance scale, stop excursion, pip value, equal units raised to the venue minimum, +/// exposure per currency and the three-costs rule. +/// +public static class BasketMath +{ + /// Units in one lot. + public const decimal LotUnits = 100_000m; + + /// The venue's minimum exposure per position, in USD (section 6.4). + public const decimal VenueMinimumUsd = 1_000m; + + /// A unit opens only when its target is at least this many times its cost (section 11.3). + public const decimal CostMultiple = 3m; + + /// Pips of one order: long (bid − entry) / pip, short (entry − ask) / pip. + public static decimal OrderPips(Direction side, decimal entry, BidAsk quote, decimal pip) => + side == Direction.Buy ? (quote.Bid - entry) / pip : (entry - quote.Ask) / pip; + + /// The pip sum of a basket: the pips of every open order, added. + public static decimal PipSum(IEnumerable orders, Func quotes) + { + ArgumentNullException.ThrowIfNull(orders); + ArgumentNullException.ThrowIfNull(quotes); + return orders.Sum(o => o.Pips(quotes(o.Pair))); + } + + /// + /// The common exit price of n equal orders on one symbol (section 4.5, appendix C): mean(entries) + target / n · pip for + /// longs (the bid reaches it), − target / n · pip for shorts (the ask reaches it). At that price the pip sum is the target. + /// + public static decimal CommonExit(IReadOnlyList entries, Direction side, decimal targetPips, decimal pip) + { + ArgumentNullException.ThrowIfNull(entries); + ArgumentOutOfRangeException.ThrowIfZero(entries.Count); + var move = MovePerOrder(targetPips, entries.Count) * pip; + var mean = entries.Sum() / entries.Count; + return side == Direction.Buy ? mean + move : mean - move; + } + + /// Table 4.5: the move beyond the mean entry each of n equal orders needs for the target, in pips (target / n). + public static decimal MovePerOrder(decimal targetPips, int orders) + { + ArgumentOutOfRangeException.ThrowIfLessThan(orders, 1); + return targetPips / orders; + } + + /// The distance factor of Rvol: max(1, min(Rvol, 3)). + public static decimal DistanceFactor(double rvol) => (decimal)Math.Max(1, Math.Min(Finite(rvol), 3)); + + /// The dynamic target factor of Rvol: max(0.7, min(Rvol, 3)). + public static decimal TargetFactor(double rvol) => (decimal)Math.Max(0.7, Math.Min(Finite(rvol), 3)); + + /// + /// The distance of the k-th re-entry (section 4.6, appendix C): Dmin × max(1, min(Rvol, 3)) × g^(k − 1), measured from + /// the last level, k = 1 … MaxReentries. + /// + public static decimal Distance(decimal minDistance, double rvol, decimal growth, int k) + { + ArgumentOutOfRangeException.ThrowIfLessThan(k, 1); + var distance = minDistance * DistanceFactor(rvol); + for (var i = 1; i < k; i++) + { + distance *= growth; + } + + return distance; + } + + /// The distances of every re-entry, k = 1 … . + public static IReadOnlyList Distances(decimal minDistance, double rvol, decimal growth, int maxReentries) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxReentries); + return [.. Enumerable.Range(1, maxReentries).Select(k => Distance(minDistance, rvol, growth, k))]; + } + + /// Whether a basket with levels open may add one: only while levels < 1 + MaxReentries. + public static bool CanAdd(int levels, int maxReentries) => levels >= 1 && levels < 1 + maxReentries; + + /// The distance the next level needs from the last one; null once the last level is open. + public static decimal? NextDistance(int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) => + CanAdd(levels, maxReentries) ? Distance(minDistance, rvol, growth, levels) : null; + + /// + /// Whether to add a level: a level may still be added and the last level has lost at least the distance. The lot of the + /// new level is the lot of the first; it never grows. + /// + public static bool ShouldAdd(decimal lastLevelPips, int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) => + NextDistance(levels, maxReentries, minDistance, rvol, growth) is { } distance && lastLevelPips <= -distance; + + /// The pip sum of n levels, D apart, when the first level stands at E pips (appendix C): n·E + D·n(n − 1)/2. + public static decimal PipSumAtExcursion(int levels, decimal firstLevelPips, decimal distance) + { + ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1); + return (levels * firstLevelPips) + (distance * levels * (levels - 1) / 2); + } + + /// + /// The first-level excursion E ≤ 0 at which n full levels lose of the capital (table 4.12, + /// section 6.9): |n·E + D·n(n − 1)/2| × lot × pip value per lot = threshold × capital. Exact; the document's tables + /// show it rounded half to even. + /// + public static decimal StopExcursion(int levels, decimal distance, decimal lot, decimal pipValuePerLot, decimal threshold, decimal capital) + { + ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(lot); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot); + var pipSum = -(threshold * capital) / (lot * pipValuePerLot); + return (pipSum - (distance * levels * (levels - 1) / 2)) / levels; + } + + /// The lot that loses of the capital at the excursion E (appendix C). + public static decimal LotForRisk(int levels, decimal excursion, decimal distance, decimal pipValuePerLot, decimal threshold, decimal capital) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot); + var pipSum = Math.Abs(PipSumAtExcursion(levels, excursion, distance)); + if (pipSum == 0) + { + throw new ArgumentException("A questa escursione la somma dei pip è zero: nessun lotto la porta alla soglia.", nameof(excursion)); + } + + return threshold * capital / (pipValuePerLot * pipSum); + } + + /// + /// The USD value of one unit of a currency (appendix C): 1 for the dollar, the price of XUSD when it is a pair, 1 / USDX + /// otherwise (usd(JPY) = 1 / USDJPY). + /// + public static decimal UsdPerUnit(string currency, Func price) + { + ArgumentNullException.ThrowIfNull(price); + if (currency == Currencies.Usd) + { + return 1m; + } + + var pair = FxPairs.Of(currency, Currencies.Usd) + ?? throw new ArgumentException($"{currency} non è una delle otto valute.", nameof(currency)); + return pair.Base == Currencies.Usd ? 1m / price(pair) : price(pair); + } + + /// The value of one pip in USD (appendix C): units × pip × usd(quote). + public static decimal PipValue(FxPair pair, decimal units, decimal usdPerQuote) + { + ArgumentNullException.ThrowIfNull(pair); + return units * pair.Pip * usdPerQuote; + } + + /// The value of one pip in USD, the quote currency valued at the prices given. + public static decimal PipValue(FxPair pair, decimal units, Func price) + { + ArgumentNullException.ThrowIfNull(pair); + return PipValue(pair, units, UsdPerUnit(pair.Quote, price)); + } + + /// + /// Equal units on every leg (section 6.4 and the forward-test phase): LotPer10k × capital / 10,000 × 100,000, in whole + /// units. When a leg would be worth less than the venue minimum, every leg rises to the units that bring the weakest leg + /// (the lowest USD value of its base) to the minimum, rounded up to whole units. + /// + public static LegUnits EqualUnits(decimal lotPer10k, decimal capital, IReadOnlyList usdPerBase, decimal minimumUsd = VenueMinimumUsd) + { + ArgumentNullException.ThrowIfNull(usdPerBase); + ArgumentOutOfRangeException.ThrowIfZero(usdPerBase.Count); + var weakest = usdPerBase.Min(); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weakest); + + var units = Math.Floor(lotPer10k * capital / 10_000m * LotUnits); + if (units * weakest >= minimumUsd) + { + return new LegUnits(units, false); + } + + return new LegUnits(Math.Ceiling(minimumUsd / weakest), true); + } + + /// + /// The net position per currency in native units (section 4.4, appendix C): a long of U units of BASEQUOTE at price P is + /// +U of the base and −U·P of the quote; a short reverses both signs. + /// + public static IReadOnlyDictionary Exposure(IEnumerable legs) + { + ArgumentNullException.ThrowIfNull(legs); + var net = new Dictionary(StringComparer.Ordinal); + foreach (var leg in legs) + { + var sign = leg.Side == Direction.Buy ? 1m : -1m; + net[leg.Pair.Base] = net.GetValueOrDefault(leg.Pair.Base) + (sign * leg.Units); + net[leg.Pair.Quote] = net.GetValueOrDefault(leg.Pair.Quote) - (sign * leg.Units * leg.Price); + } + + return net; + } + + /// The net position per currency valued in USD. + public static IReadOnlyDictionary UsdExposure(IReadOnlyDictionary native, Func price) + { + ArgumentNullException.ThrowIfNull(native); + return native.ToDictionary(e => e.Key, e => e.Value * UsdPerUnit(e.Key, price), StringComparer.Ordinal); + } + + /// The three-costs rule (section 11.3): a unit opens only if its target is at least three times its cost. + public static bool PassesCostRule(decimal targetPips, decimal costPips, decimal multiple = CostMultiple) => targetPips >= multiple * costPips; + + private static double Finite(double rvol) => + double.IsFinite(rvol) ? rvol : throw new ArgumentOutOfRangeException(nameof(rvol), rvol, "Rvol deve essere un numero finito."); +} diff --git a/src/Anubis/Baskets/Relations.cs b/src/Anubis/Baskets/Relations.cs new file mode 100644 index 0000000..42f15f9 --- /dev/null +++ b/src/Anubis/Baskets/Relations.cs @@ -0,0 +1,174 @@ +namespace Anubis.Baskets; + +/// The kinds of relation of section 4.1 (chain, ratio, disjoint) and the two of section 11 (statistical, single symbol). +public enum RelationKind +{ + /// The common currency is the quote of one pair and the base of the other: the synthetic is the product. + Chain, + + /// The common currency has the same role in both pairs: the synthetic is the ratio A / B. + Ratio, + + /// No common currency: no synthetic, the sign comes from the correlation. + Disjoint, + + /// Two instruments tied by a hedge ratio β from the regression of log prices. + Statistical, + + /// One symbol on its own. + SingleSymbol, +} + +/// +/// How two of the 28 pairs relate (section 4.1). is the listed pair equivalent to the synthetic: for a +/// chain the product A × B, always a listed pair; for a ratio the quotient A / B, which may be the inverse of the listed pair +/// (). Kind, common currency and cross never depend on the order of the legs; only the +/// orientation of a ratio's quotient does. +/// +public sealed record PairRelation(FxPair A, FxPair B, RelationKind Kind, string? Common, FxPair? Cross, bool CrossInverted) +{ + /// The sign s of the pip index (section 4.2); null when the couple has no sign and cannot be traded. + public int? Sign(double? correlation = null) => Relations.Sign(Kind, correlation); +} + +/// A row of appendix B: leg A ends in the common currency, leg B starts with it, buying both buys the cross. +public sealed record ChainRow(int Row, FxPair A, FxPair B, FxPair Cross, bool Listed); + +/// A two-leg spread as the document writes it (section 3.3), leg A first. +public sealed record DocumentedSpread(FxPair A, FxPair B); + +/// +/// The relations among the 28 pairs (section 4.1, appendix B, appendix C): classification, the 378 couples, the 56 chains in +/// the document's order, the eight documented spreads (section 3.3) and the 14-pair list (section 4.9). +/// +public static class Relations +{ + private static readonly int[] ListedRows = [3, 9, 17, 29, 30, 35]; + + /// The 378 unordered couples of the 28 pairs, each once, in appendix A order: 56 chains, 112 ratios, 210 disjoint. + public static IReadOnlyList Couples { get; } = Array.AsReadOnly(BuildCouples()); + + /// + /// Appendix B: for each common currency c from GBP to CHF, every a before c and every b after c in the currency order, + /// A = a c, B = c b, cross = a b. Rows 3, 9, 17, 29, 30 and 35 are the ones the documented editions list. + /// + public static IReadOnlyList AppendixB { get; } = Array.AsReadOnly(BuildAppendixB()); + + /// The eight spreads of section 3.3, in the document's leg order: six chains and two disjoint couples. + public static IReadOnlyList DocumentedSpreads { get; } = Array.AsReadOnly( + [ + new(FxPairs.Get("EURUSD"), FxPairs.Get("USDCHF")), + new(FxPairs.Get("AUDUSD"), FxPairs.Get("USDCAD")), + new(FxPairs.Get("NZDUSD"), FxPairs.Get("EURNZD")), + new(FxPairs.Get("USDCAD"), FxPairs.Get("EURUSD")), + new(FxPairs.Get("EURAUD"), FxPairs.Get("AUDCAD")), + new(FxPairs.Get("GBPUSD"), FxPairs.Get("EURGBP")), + new(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF")), + new(FxPairs.Get("EURCHF"), FxPairs.Get("AUDCAD")), + ]); + + /// The 14-pair list (section 4.9): the twelve documented symbols plus EURCAD and AUDNZD, in appendix A order. + public static IReadOnlyList FourteenPairs { get; } = Array.AsReadOnly( + new[] + { + "EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD", + "AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF", + }.Select(FxPairs.Get).ToArray()); + + /// Classifies two different pairs; the result never depends on which one is given first, except for a ratio's orientation. + public static PairRelation Classify(FxPair a, FxPair b) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + if (a == b) + { + throw new ArgumentException($"Una relazione vuole due coppie diverse, non {a.Name} due volte.", nameof(b)); + } + + var common = Shared(a, b); + if (common is null) + { + return new PairRelation(a, b, RelationKind.Disjoint, null, null, false); + } + + // Chain: x/c × c/y = x/y. The listed pairs give x before c before y, so the cross is always listed. + if (a.Quote == common && b.Base == common) + { + return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(a.Base, b.Quote), false); + } + + if (a.Base == common && b.Quote == common) + { + return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(b.Base, a.Quote), false); + } + + // Ratio. Both quote c: (c per x) / (c per y) = y per x, the pair x/y. Both base c: (x per c) / (y per c) = x per y, + // the pair y/x. The listed pair may be the other way round. + var otherA = a.Base == common ? a.Quote : a.Base; + var otherB = b.Base == common ? b.Quote : b.Base; + var syntheticBase = a.Quote == common ? otherA : otherB; + var cross = FxPairs.Of(otherA, otherB)!; + return new PairRelation(a, b, RelationKind.Ratio, common, cross, cross.Base != syntheticBase); + } + + /// + /// The sign s of the pip index X = A / pip(A) + s · B / pip(B) (section 4.2, appendix C): +1 for a chain, −1 for a ratio, + /// −sign(ρ) for a disjoint couple. A disjoint couple with ρ zero, unknown or not a number has no sign: null. + /// + public static int? Sign(RelationKind kind, double? correlation) => kind switch + { + RelationKind.Chain => 1, + RelationKind.Ratio => -1, + RelationKind.Disjoint => correlation is { } rho && rho != 0 && !double.IsNaN(rho) ? -Math.Sign(rho) : null, + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Il segno dell'indice in pip vale solo per catena, rapporto e disgiunta."), + }; + + private static string? Shared(FxPair a, FxPair b) + { + if (a.Base == b.Base || a.Base == b.Quote) + { + return a.Base; + } + + return a.Quote == b.Base || a.Quote == b.Quote ? a.Quote : null; + } + + private static PairRelation[] BuildCouples() + { + var pairs = FxPairs.All; + var couples = new List(pairs.Count * (pairs.Count - 1) / 2); + for (var i = 0; i < pairs.Count; i++) + { + for (var j = i + 1; j < pairs.Count; j++) + { + couples.Add(Classify(pairs[i], pairs[j])); + } + } + + return [.. couples]; + } + + private static ChainRow[] BuildAppendixB() + { + var order = Currencies.Order; + var rows = new List(56); + for (var c = 1; c < order.Count - 1; c++) + { + for (var a = 0; a < c; a++) + { + for (var b = c + 1; b < order.Count; b++) + { + var row = rows.Count + 1; + rows.Add(new ChainRow( + row, + FxPairs.Get(order[a] + order[c]), + FxPairs.Get(order[c] + order[b]), + FxPairs.Get(order[a] + order[b]), + ListedRows.Contains(row))); + } + } + } + + return [.. rows]; + } +} diff --git a/src/Anubis/Baskets/ServerClock.cs b/src/Anubis/Baskets/ServerClock.cs new file mode 100644 index 0000000..53cb62a --- /dev/null +++ b/src/Anubis/Baskets/ServerClock.cs @@ -0,0 +1,92 @@ +using Anubis.Data; + +namespace Anubis.Baskets; + +/// +/// A window of the day on a wall clock (section 4.7), half-open: is inside, is not. When +/// comes before the window crosses midnight. +/// +public sealed record DailyWindow(TimeOnly From, TimeOnly To) +{ + public bool Contains(TimeOnly time) => From <= To ? time >= From && time < To : time >= From || time < To; +} + +/// +/// The server clock of the research document (section 4.7 and appendix C): New York time plus seven hours, so it follows +/// the United States' daylight saving only (UTC+2 in winter, UTC+3 in summer). The server day changes at 17:00 New York. +/// Every window is half-open: the weekend rule (no new entries from Friday 16:00 to Monday 02:00 server time), the hourly +/// window (10:00 to 20:00 server time, when it is on) and the daily venue pause (16:55 to 18:10 New York time). +/// +public static class ServerClock +{ + /// How far the server clock is ahead of New York. + public static readonly TimeSpan AheadOfNewYork = TimeSpan.FromHours(7); + + /// First server time of the weekend rule, on Friday. + public static readonly TimeOnly WeekendFrom = new(16, 0); + + /// First server time after the weekend rule, on Monday. + public static readonly TimeOnly WeekendTo = new(2, 0); + + /// The hourly window, in server time. + public static DailyWindow Session { get; } = new(new TimeOnly(10, 0), new TimeOnly(20, 0)); + + /// The daily venue pause, in New York time: no entries and no averaging inside it. + public static DailyWindow DailyPauseNewYork { get; } = new(new TimeOnly(16, 55), new TimeOnly(18, 10)); + + /// The server wall clock at a moment. + public static DateTime ToServer(DateTimeOffset moment) => NewYork(moment) + AheadOfNewYork; + + /// The moment a server wall-clock time names. In the hour New York's clock goes back, standard time wins. + public static DateTimeOffset FromServer(DateTime server) + { + var newYork = DateTime.SpecifyKind(server - AheadOfNewYork, DateTimeKind.Unspecified); + return new DateTimeOffset(newYork, Zones.NewYork.GetUtcOffset(newYork)).ToUniversalTime(); + } + + /// How far the server clock is ahead of UTC at a moment: two hours in winter, three in summer. + public static TimeSpan OffsetFromUtc(DateTimeOffset moment) => ToServer(moment) - moment.UtcDateTime; + + /// The server day of a moment: the date of the server clock. + public static DateOnly Day(DateTimeOffset moment) => DateOnly.FromDateTime(ToServer(moment)); + + /// The moment of a server time on a server day. + public static DateTimeOffset At(DateOnly day, TimeOnly time) => FromServer(day.ToDateTime(time)); + + /// Server midnight: 17:00 New York of the day before. + public static DateTimeOffset DayStart(DateOnly day) => At(day, TimeOnly.MinValue); + + /// The start of the server day after the one of : when entries resume after the equity stop. + public static DateTimeOffset NextDayStart(DateTimeOffset moment) => DayStart(Day(moment).AddDays(1)); + + /// True from Friday 16:00 to Monday 02:00 server time (Monday 02:00 excluded). + public static bool InWeekend(DateTimeOffset moment) + { + var server = ToServer(moment); + var time = TimeOnly.FromDateTime(server); + return server.DayOfWeek switch + { + DayOfWeek.Friday => time >= WeekendFrom, + DayOfWeek.Saturday or DayOfWeek.Sunday => true, + DayOfWeek.Monday => time < WeekendTo, + _ => false, + }; + } + + /// True inside the hourly window, in server time; replaces 10:00–20:00. + public static bool InSession(DateTimeOffset moment, DailyWindow? window = null) => + (window ?? Session).Contains(TimeOnly.FromDateTime(ToServer(moment))); + + /// True inside the daily venue pause, in New York time; replaces 16:55–18:10. + public static bool InDailyPause(DateTimeOffset moment, DailyWindow? pause = null) => + (pause ?? DailyPauseNewYork).Contains(TimeOnly.FromDateTime(NewYork(moment))); + + /// + /// Whether the clock allows a new entry: outside the weekend rule and the daily pause, and inside the hourly window when + /// it is on. + /// + public static bool EntriesAllowed(DateTimeOffset moment, bool sessionOn) => + !InWeekend(moment) && !InDailyPause(moment) && (!sessionOn || InSession(moment)); + + private static DateTime NewYork(DateTimeOffset moment) => TimeZoneInfo.ConvertTime(moment, Zones.NewYork).DateTime; +} diff --git a/src/Anubis/Baskets/Styles.cs b/src/Anubis/Baskets/Styles.cs new file mode 100644 index 0000000..d7a58f3 --- /dev/null +++ b/src/Anubis/Baskets/Styles.cs @@ -0,0 +1,153 @@ +namespace Anubis.Baskets; + +/// The state of a pair on the panel (section 4.9): ferma, in osservazione, pronta, aperta. +public enum PairState +{ + /// Ferma: |z| below the watch threshold. + Idle, + + /// In osservazione: |z| at or above the watch threshold. + Watch, + + /// Pronta: |z| at or above the entry threshold, but a gate blocks the entry. + Armed, + + /// Aperta: every gate passes, or a unit is already open. + Open, +} + +/// The states of a pair, the entry signal and the closing of the spread (sections 4.3 and 4.9). +public static class PairStates +{ + /// |z| from which a pair is watched. + public const double DefaultWatchZ = 1.5; + + /// |z| at or below which the spread counts as closed. + public const double DefaultSpreadClosedZ = 0.5; + + /// + /// The state at a closed bar: with a unit open or with |z| ≥ entry and every gate passing; + /// with |z| ≥ entry and a gate blocking; with |z| ≥ watch; + /// otherwise, and without a z-score. + /// + public static PairState Of(double? z, double entryZ, bool gatesPass, bool hasOpenUnit = false, double watchZ = DefaultWatchZ) + { + if (hasOpenUnit) + { + return PairState.Open; + } + + if (z is not { } value || double.IsNaN(value)) + { + return PairState.Idle; + } + + var size = Math.Abs(value); + if (size >= entryZ) + { + return gatesPass ? PairState.Open : PairState.Armed; + } + + return size >= watchZ ? PairState.Watch : PairState.Idle; + } + + /// The entry signal: buy the spread at z ≤ −entry, sell it at z ≥ +entry, nothing otherwise. + public static Direction? Signal(double? z, double entryZ) => z switch + { + { } value when value <= -entryZ => Direction.Buy, + { } value when value >= entryZ => Direction.Sell, + _ => null, + }; + + /// Whether the spread has closed: |z| ≤ . + public static bool SpreadClosed(double? z, double closedZ = DefaultSpreadClosedZ) => z is { } value && Math.Abs(value) <= closedZ; +} + +/// +/// One of the four styles of section 4.7: entry threshold, spreads open at once, averagings; the growth variant (1.3) allows +/// . +/// +public sealed record TradingStyle(string Name, double EntryZ, int MaxOpenSpreads, int MaxAveragings, int MaxAveragingsWithGrowth); + +/// The four styles of section 4.7; Moderato is the default. +public static class TradingStyles +{ + public static TradingStyle HedgeFund { get; } = new("HedgeFund", 3.0, 1, 2, 2); + + public static TradingStyle Conservativo { get; } = new("Conservativo", 2.5, 2, 3, 3); + + public static TradingStyle Moderato { get; } = new("Moderato", 2.0, 2, 3, 3); + + public static TradingStyle Aggressivo { get; } = new("Aggressivo", 1.5, 3, 3, 4); + + public static TradingStyle Default => Moderato; + + public static IReadOnlyList All { get; } = Array.AsReadOnly(new[] { HedgeFund, Conservativo, Moderato, Aggressivo }); + + /// The style with this name, or null. + public static TradingStyle? Find(string name) => All.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.Ordinal)); +} + +/// +/// A risk profile of the basket logic (sections 5 and 7.1, appendix D). Fractions are of the balance or of equity: +/// 0.09 is 9%. A null stop is a stop that does not exist; a null exposure cap means the cap is only logged. +/// +/// Fedele or Prudente. +/// Basket stop when |z| reaches this value. +/// Basket stop when its loss reaches this fraction of equity. +/// Basket stop when the relation breaks (the correlation loses its expected sign). +/// Basket stop after this many bars open. +/// Everything closes when open loss ÷ balance reaches this fraction. +/// After the equity stop entries resume at the next server day. +/// The three-costs rule blocks entries (otherwise it is only logged). +/// Net exposure per currency, in multiples of one entry's exposure. +/// Allowed only in backtest, simulator and Demo. +public sealed record BasketProfile( + string Name, + double? StopZ, + decimal? StopLoss, + bool StopOnBrokenRelation, + int? StopAfterBars, + decimal EquityStop, + bool ResumeAtNextServerDay, + bool CostGate, + decimal? MaxCurrencyExposure, + bool OffRealAccountsOnly) +{ + /// Whether any basket stop is on. + public bool HasBasketStops() => StopZ is not null || StopLoss is not null || StopOnBrokenRelation || StopAfterBars is not null; +} + +/// +/// The two profiles: Fedele, the document as written (no basket stop, equity stop at 9% with resume at the next server day, +/// only off real accounts); Prudente, the same logic with the basket stops (z 3.5, loss 1% — the document's 1.5% reduced by +/// SPEC 9.2 — broken relation, 96 bars), the cost gate and the currency exposure cap 2.0. +/// +public static class BasketProfiles +{ + public static BasketProfile Fedele { get; } = new( + "Fedele", + StopZ: null, + StopLoss: null, + StopOnBrokenRelation: false, + StopAfterBars: null, + EquityStop: 0.09m, + ResumeAtNextServerDay: true, + CostGate: false, + MaxCurrencyExposure: null, + OffRealAccountsOnly: true); + + public static BasketProfile Prudente { get; } = new( + "Prudente", + StopZ: 3.5, + StopLoss: 0.01m, + StopOnBrokenRelation: true, + StopAfterBars: 96, + EquityStop: 0.09m, + ResumeAtNextServerDay: true, + CostGate: true, + MaxCurrencyExposure: 2.0m, + OffRealAccountsOnly: false); + + public static IReadOnlyList All { get; } = Array.AsReadOnly(new[] { Fedele, Prudente }); +} diff --git a/tests/Anubis.Tests/BasketMathTests.cs b/tests/Anubis.Tests/BasketMathTests.cs new file mode 100644 index 0000000..1822c50 --- /dev/null +++ b/tests/Anubis.Tests/BasketMathTests.cs @@ -0,0 +1,278 @@ +using System.Globalization; +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// The money side of the basket maths (Phase 12, issue #119): pip sum and common exit, table 4.5, the distance scale, the +/// stop excursions of table 4.12 and section 6.9, pip value, units raised to the venue minimum, exposure and the three-costs +/// rule. Every expected number is the document's, or worked out by hand in the comment next to it. +/// +[TestClass] +public sealed class BasketMathTests +{ + private static readonly decimal[] AudusdEntries = [0.69456m, 0.69003m, 0.68739m]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThreeAudusdBuysWithTarget69ExitAtTheCommonPrice() + { + var pair = FxPairs.Get("AUDUSD"); + + // mean = 2.07198 / 3 = 0.69066; target / n = 6.9 / 3 = 2.3 pips = 0.00023; P* = 0.69089. + var exit = BasketMath.CommonExit(AudusdEntries, Direction.Buy, 6.9m, pair.Pip); + Assert.IsTrue(Math.Abs(exit - 0.69089m) <= 0.1m * pair.Pip, exit.ToString(CultureInfo.InvariantCulture)); + + // At that bid each order has −36.7, +8.6 and +35.0 pips, +6.9 in all. + var quote = new BidAsk(0.69089m, 0.69095m); + var orders = AudusdEntries.Select(e => new BasketOrder(pair, Direction.Buy, e)).ToArray(); + CollectionAssert.AreEqual(new[] { -36.7m, 8.6m, 35.0m }, orders.Select(o => o.Pips(quote)).ToArray()); + Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => quote)); + Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => new BidAsk(exit, exit + 0.00006m))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ShortOrdersExitBelowTheMeanAndCountPipsOnTheAsk() + { + var pair = FxPairs.Get("USDJPY"); + decimal[] entries = [157.20m, 157.60m, 158.00m]; + + // mean 157.60, target 9 over 3 orders = 3 pips = 0.03 below: 157.57. + var exit = BasketMath.CommonExit(entries, Direction.Sell, 9m, pair.Pip); + Assert.AreEqual(157.57m, exit); + + var orders = entries.Select(e => new BasketOrder(pair, Direction.Sell, e)).ToArray(); + Assert.AreEqual(9m, BasketMath.PipSum(orders, _ => new BidAsk(157.55m, exit))); + CollectionAssert.AreEqual(new[] { -37m, 3m, 43m }, orders.Select(o => o.Pips(new BidAsk(157.55m, exit))).ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(1, "10.00")] + [DataRow(2, "5.00")] + [DataRow(3, "3.33")] + [DataRow(4, "2.50")] + [DataRow(5, "2.00")] + [DataRow(8, "1.25")] + public void TheMovePerOrderFollowsTable45(int orders, string expected) + { + var move = BasketMath.MovePerOrder(10m, orders); + Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), Math.Round(move, 2)); + + // The same identity as the common exit: P* − mean = target / n pips. + var entries = Enumerable.Range(0, orders).Select(i => 1.1000m - (i * 0.0040m)).ToArray(); + var exit = BasketMath.CommonExit(entries, Direction.Buy, 10m, 0.0001m); + AssertClose(move * 0.0001m, exit - entries.Average(), 0.0000000000000000001m); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(0.8, "1.0", "40", "40", "40", "40")] + [DataRow(0.8, "1.3", "40", "52", "67.6", "87.88")] + [DataRow(1.5, "1.0", "60", "60", "60", "60")] + [DataRow(1.5, "1.3", "60", "78", "101.4", "131.82")] + [DataRow(4.0, "1.0", "120", "120", "120", "120")] + [DataRow(4.0, "1.3", "120", "156", "202.8", "263.64")] + public void TheDistanceScaleFollowsRvolAndTheGrowth(double rvol, string growth, string d1, string d2, string d3, string d4) + { + var g = decimal.Parse(growth, CultureInfo.InvariantCulture); + decimal[] expected = [.. new[] { d1, d2, d3, d4 }.Select(d => decimal.Parse(d, CultureInfo.InvariantCulture))]; + + for (var k = 1; k <= 4; k++) + { + Assert.AreEqual(expected[k - 1], BasketMath.Distance(40m, rvol, g, k), $"k = {k}"); + } + + CollectionAssert.AreEqual(expected, BasketMath.Distances(40m, rvol, g, maxReentries: 4).ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoLevelIsAddedAfterTheLast() + { + // Three re-entries: four levels at most; the k-th addition is the one made with k levels open. + for (var levels = 1; levels <= 3; levels++) + { + Assert.IsTrue(BasketMath.CanAdd(levels, maxReentries: 3)); + Assert.AreEqual(BasketMath.Distance(40m, 1.0, 1.3m, levels), BasketMath.NextDistance(levels, 3, 40m, 1.0, 1.3m)); + } + + Assert.IsFalse(BasketMath.CanAdd(4, maxReentries: 3)); + Assert.IsNull(BasketMath.NextDistance(4, 3, 40m, 1.0, 1.3m)); + Assert.IsFalse(BasketMath.ShouldAdd(-10_000m, levels: 4, maxReentries: 3, 40m, 1.0, 1.3m)); + + // With four re-entries (growth variant) the fifth level is the last. + Assert.IsTrue(BasketMath.CanAdd(4, maxReentries: 4)); + Assert.IsFalse(BasketMath.CanAdd(5, maxReentries: 4)); + Assert.IsFalse(BasketMath.CanAdd(0, maxReentries: 3)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ALevelIsAddedOnlyWhenTheLastLevelHasLostTheDistance() + { + // Second level (k = 1): 40 pips; third (k = 2) with growth 1.3: 52 pips, measured from the last level. + Assert.IsFalse(BasketMath.ShouldAdd(-39.9m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsTrue(BasketMath.ShouldAdd(-40m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsFalse(BasketMath.ShouldAdd(-51.9m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsTrue(BasketMath.ShouldAdd(-52m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("0.01", "40", -2310)] + [DataRow("0.02", "40", -1185)] + [DataRow("0.05", "40", -510)] + [DataRow("0.10", "40", -285)] + [DataRow("0.01", "65", -2348)] + [DataRow("0.02", "65", -1222)] + [DataRow("0.05", "65", -548)] + [DataRow("0.10", "65", -322)] + public void TheEightExcursionsOfTable412(string lot, string distance, int expected) + { + var l = decimal.Parse(lot, CultureInfo.InvariantCulture); + var d = decimal.Parse(distance, CultureInfo.InvariantCulture); + + // Account 10,000 USD, stop at 9%, 10 USD per lot per pip, 1 + 3 levels; shown values rounded half to even. + var excursion = BasketMath.StopExcursion(4, d, l, 10m, 0.09m, 10_000m); + Assert.AreEqual((decimal)expected, Math.Round(excursion)); + + // At that excursion the pip sum loses exactly the 9%: 900 USD. + Assert.AreEqual(-900m, BasketMath.PipSumAtExcursion(4, excursion, d) * l * 10m); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(500, -172)] + [DataRow(1000, -285)] + [DataRow(2500, -622)] + [DataRow(5000, -1185)] + [DataRow(10000, -2310)] + [DataRow(25000, -5685)] + public void TheCapitalTableOfSection69(int capital, int expected) + { + // Lot 0.01 (the pip sum is worth 0.1 USD), D = 40, four levels, 9% of capital. + Assert.AreEqual((decimal)expected, Math.Round(BasketMath.StopExcursion(4, 40m, 0.01m, 10m, 0.09m, capital))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheLotForAGivenRiskInvertsTheExcursion() + { + // 0.09 × 10,000 / (10 × |4 × −285 + 6 × 40|) = 900 / 9,000 = 0.10. + Assert.AreEqual(0.10m, BasketMath.LotForRisk(4, -285m, 40m, 10m, 0.09m, 10_000m)); + Assert.AreEqual(4 * -100m + (6 * 40m), BasketMath.PipSumAtExcursion(4, -100m, 40m)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipValueOfAYenPairIsUnitsTimesPipOverUsdjpy() + { + // The ECB test day of the plan: USDJPY = 176.79 / 1.1193. + var usdjpy = 176.79m / 1.1193m; + var prices = Prices(("USDJPY", usdjpy)); + + Assert.AreEqual(1m / usdjpy, BasketMath.UsdPerUnit(Currencies.Jpy, prices)); + AssertClose(10m / usdjpy, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices)); + AssertClose(9.21m / usdjpy, BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, prices)); + AssertClose(8.47m / usdjpy, BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, prices)); + AssertClose(0.0633124m, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices), 0.0000001m); + + // Appendix A, units per 1,000 USD with USDJPY about 160.3: 0.062, 0.057 and 0.053 USD per pip. + var appendix = Prices(("USDJPY", 160.3m)); + Assert.AreEqual(0.062m, Math.Round(BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, appendix), 3)); + Assert.AreEqual(0.057m, Math.Round(BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, appendix), 3)); + Assert.AreEqual(0.053m, Math.Round(BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, appendix), 3)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipValueOfOtherQuotesUsesTheirDollarValue() + { + var prices = Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m), ("AUDUSD", 0.6623m)); + + Assert.AreEqual(1m, BasketMath.UsdPerUnit(Currencies.Usd, prices)); + Assert.AreEqual(1.0856m, BasketMath.UsdPerUnit(Currencies.Eur, prices)); + Assert.AreEqual(0.1m, BasketMath.PipValue(FxPairs.Get("EURUSD"), 1000m, prices)); + Assert.AreEqual(0.1m / 0.847m, BasketMath.PipValue(FxPairs.Get("USDCHF"), 1000m, prices)); + + // Appendix A: 1,510 AUDUSD units per 1,000 USD are worth 0.151 USD per pip. + Assert.AreEqual(0.151m, BasketMath.PipValue(FxPairs.Get("AUDUSD"), 1510m, prices)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void BothLegsRiseToTheUnitsThatBringTheWeakestToTheVenueMinimum() + { + // 0.01 lot per 10,000 USD on 10,000 USD: 1,000 units, worth 662.3 USD on an AUD base, under the 1,000 USD minimum. + // 1,000 / 0.6623 = 1,509.89, rounded up: 1,510 on both legs (appendix A). + var aud = BasketMath.EqualUnits(0.01m, 10_000m, [1.0856m, 0.6623m]); + Assert.AreEqual(1510m, aud.Units); + Assert.IsTrue(aud.Raised); + Assert.AreEqual(0.0151m, aud.Lot()); + + // NZD base: 1,000 / 0.54172 = 1,845.97, rounded up: 1,846. (Appendix A rounds to the nearest unit: at exactly 0.5417 + // the minimum needs 1,846.04, so 1,847 rounded up.) + var nzd = BasketMath.EqualUnits(0.01m, 10_000m, [0.6623m, 0.54172m]); + Assert.AreEqual(1846m, nzd.Units); + Assert.IsTrue(nzd.Units * 0.54172m >= 1000m); + Assert.AreEqual(1847m, BasketMath.EqualUnits(0.01m, 10_000m, [0.5417m]).Units); + + // Above the minimum nothing moves: 2,000 units are 1,083 USD on the NZD leg. + var enough = BasketMath.EqualUnits(0.01m, 20_000m, [0.6623m, 0.54172m]); + Assert.AreEqual(2000m, enough.Units); + Assert.IsFalse(enough.Raised); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheNetExposureOfEqualUnitsOnEurusdAndUsdchf() + { + // Long 1,000 EURUSD at 1.0856: +1,000 EUR, −1,085.6 USD. Long 1,000 USDCHF at 0.847: +1,000 USD, −847 CHF. + var exposure = BasketMath.Exposure( + [ + new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Buy, 1000m, 1.0856m), + new ExposureLeg(FxPairs.Get("USDCHF"), Direction.Buy, 1000m, 0.847m), + ]); + + Assert.AreEqual(3, exposure.Count); + Assert.AreEqual(1000m, exposure[Currencies.Eur]); + Assert.AreEqual(-85.6m, exposure[Currencies.Usd]); + Assert.AreEqual(-86m, Math.Round(exposure[Currencies.Usd])); + Assert.AreEqual(-847m, exposure[Currencies.Chf]); + + // Selling reverses every sign; in dollars the base is valued at its own price. + var sold = BasketMath.Exposure([new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Sell, 1000m, 1.0856m)]); + Assert.AreEqual(-1000m, sold[Currencies.Eur]); + Assert.AreEqual(1085.6m, sold[Currencies.Usd]); + var dollars = BasketMath.UsdExposure(exposure, Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m))); + Assert.AreEqual(1085.6m, dollars[Currencies.Eur]); + AssertClose(-1000m, dollars[Currencies.Chf]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheThreeCostsRulePassesThreeOfTheFiveDocumentedSpreads() + { + decimal[] costs = [2.1m, 2.5m, 6.9m, 2.9m, 4.7m]; + var passing = costs.Where(c => BasketMath.PassesCostRule(10m, c)).ToArray(); + + CollectionAssert.AreEqual(new[] { 2.1m, 2.5m, 2.9m }, passing); + Assert.IsFalse(BasketMath.PassesCostRule(10m, 6.9m)); + Assert.IsFalse(BasketMath.PassesCostRule(10m, 4.7m)); + + // Exactly three times the cost still passes. + Assert.IsTrue(BasketMath.PassesCostRule(9m, 3m)); + Assert.IsFalse(BasketMath.PassesCostRule(8.99m, 3m)); + } + + private static Func Prices(params (string Pair, decimal Price)[] prices) + { + var map = prices.ToDictionary(p => p.Pair, p => p.Price, StringComparer.Ordinal); + return pair => map[pair.Name]; + } + + private static void AssertClose(decimal expected, decimal actual, decimal tolerance = 0.000000000001m) => + Assert.IsTrue(Math.Abs(expected - actual) <= tolerance, $"{expected} ≠ {actual}"); +} diff --git a/tests/Anubis.Tests/BasketRelationTests.cs b/tests/Anubis.Tests/BasketRelationTests.cs new file mode 100644 index 0000000..efb6fda --- /dev/null +++ b/tests/Anubis.Tests/BasketRelationTests.cs @@ -0,0 +1,225 @@ +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// The relations among the 28 pairs (Phase 12, issue #119): the counts of section 4.1, appendix B row by row, the eight +/// documented spreads of section 3.3, the sign of the index and the 14-pair list. +/// +[TestClass] +public sealed class BasketRelationTests +{ + /// Appendix B, written out by hand from the document: row, leg A, leg B, synthetic cross. + private static readonly string[][] AppendixB = + [ + ["EURGBP", "GBPAUD", "EURAUD"], ["EURGBP", "GBPNZD", "EURNZD"], ["EURGBP", "GBPUSD", "EURUSD"], + ["EURGBP", "GBPCAD", "EURCAD"], ["EURGBP", "GBPCHF", "EURCHF"], ["EURGBP", "GBPJPY", "EURJPY"], + ["EURAUD", "AUDNZD", "EURNZD"], ["EURAUD", "AUDUSD", "EURUSD"], ["EURAUD", "AUDCAD", "EURCAD"], + ["EURAUD", "AUDCHF", "EURCHF"], ["EURAUD", "AUDJPY", "EURJPY"], ["GBPAUD", "AUDNZD", "GBPNZD"], + ["GBPAUD", "AUDUSD", "GBPUSD"], ["GBPAUD", "AUDCAD", "GBPCAD"], ["GBPAUD", "AUDCHF", "GBPCHF"], + ["GBPAUD", "AUDJPY", "GBPJPY"], ["EURNZD", "NZDUSD", "EURUSD"], ["EURNZD", "NZDCAD", "EURCAD"], + ["EURNZD", "NZDCHF", "EURCHF"], ["EURNZD", "NZDJPY", "EURJPY"], ["GBPNZD", "NZDUSD", "GBPUSD"], + ["GBPNZD", "NZDCAD", "GBPCAD"], ["GBPNZD", "NZDCHF", "GBPCHF"], ["GBPNZD", "NZDJPY", "GBPJPY"], + ["AUDNZD", "NZDUSD", "AUDUSD"], ["AUDNZD", "NZDCAD", "AUDCAD"], ["AUDNZD", "NZDCHF", "AUDCHF"], + ["AUDNZD", "NZDJPY", "AUDJPY"], ["EURUSD", "USDCAD", "EURCAD"], ["EURUSD", "USDCHF", "EURCHF"], + ["EURUSD", "USDJPY", "EURJPY"], ["GBPUSD", "USDCAD", "GBPCAD"], ["GBPUSD", "USDCHF", "GBPCHF"], + ["GBPUSD", "USDJPY", "GBPJPY"], ["AUDUSD", "USDCAD", "AUDCAD"], ["AUDUSD", "USDCHF", "AUDCHF"], + ["AUDUSD", "USDJPY", "AUDJPY"], ["NZDUSD", "USDCAD", "NZDCAD"], ["NZDUSD", "USDCHF", "NZDCHF"], + ["NZDUSD", "USDJPY", "NZDJPY"], ["EURCAD", "CADCHF", "EURCHF"], ["EURCAD", "CADJPY", "EURJPY"], + ["GBPCAD", "CADCHF", "GBPCHF"], ["GBPCAD", "CADJPY", "GBPJPY"], ["AUDCAD", "CADCHF", "AUDCHF"], + ["AUDCAD", "CADJPY", "AUDJPY"], ["NZDCAD", "CADCHF", "NZDCHF"], ["NZDCAD", "CADJPY", "NZDJPY"], + ["USDCAD", "CADCHF", "USDCHF"], ["USDCAD", "CADJPY", "USDJPY"], ["EURCHF", "CHFJPY", "EURJPY"], + ["GBPCHF", "CHFJPY", "GBPJPY"], ["AUDCHF", "CHFJPY", "AUDJPY"], ["NZDCHF", "CHFJPY", "NZDJPY"], + ["USDCHF", "CHFJPY", "USDJPY"], ["CADCHF", "CHFJPY", "CADJPY"], + ]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCouplesOfTheTwentyEightPairsAre56Chains112RatiosAnd210Disjoint() + { + var couples = Relations.Couples; + + Assert.AreEqual(378, couples.Count); + Assert.AreEqual(378, couples.Select(c => (c.A.Name, c.B.Name)).Distinct().Count()); + Assert.AreEqual(56, couples.Count(c => c.Kind == RelationKind.Chain)); + Assert.AreEqual(112, couples.Count(c => c.Kind == RelationKind.Ratio)); + Assert.AreEqual(210, couples.Count(c => c.Kind == RelationKind.Disjoint)); + + // Every pair is the synthetic cross of exactly six couples that share a currency, one per other currency (section 4.1). + foreach (var pair in FxPairs.All) + { + Assert.AreEqual(6, couples.Count(c => c.Cross == pair), pair.Name); + } + + Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Disjoint).All(c => c.Common is null && c.Cross is null)); + Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Chain).All(c => !c.CrossInverted)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AppendixBIsReproducedRowByRow() + { + var rows = Relations.AppendixB; + int[] listed = [3, 9, 17, 29, 30, 35]; + + Assert.AreEqual(56, rows.Count); + for (var i = 0; i < AppendixB.Length; i++) + { + var row = rows[i]; + var expected = AppendixB[i]; + Assert.AreEqual(i + 1, row.Row); + Assert.AreEqual(expected[0], row.A.Name, $"riga {i + 1}"); + Assert.AreEqual(expected[1], row.B.Name, $"riga {i + 1}"); + Assert.AreEqual(expected[2], row.Cross.Name, $"riga {i + 1}"); + Assert.AreEqual(listed.Contains(i + 1), row.Listed, $"riga {i + 1}"); + + // The common currency is the quote of A and the base of B; the classification agrees with the row. + Assert.AreEqual(row.A.Quote, row.B.Base); + var relation = Relations.Classify(row.A, row.B); + Assert.AreEqual(RelationKind.Chain, relation.Kind); + Assert.AreEqual(row.Cross, relation.Cross); + Assert.AreEqual(row.A.Quote, relation.Common); + } + + // The 56 rows are the 56 chains of the 378 couples, each once. + var chains = Relations.Couples.Where(c => c.Kind == RelationKind.Chain).Select(c => Key(c.A, c.B)).ToHashSet(); + CollectionAssert.AreEquivalent(chains.ToList(), rows.Select(r => Key(r.A, r.B)).ToList()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEightDocumentedSpreadsAreSixChainsAndTwoDisjointWhateverTheLegOrder() + { + (string A, string B, RelationKind Kind, string? Cross)[] expected = + [ + ("EURUSD", "USDCHF", RelationKind.Chain, "EURCHF"), + ("AUDUSD", "USDCAD", RelationKind.Chain, "AUDCAD"), + ("NZDUSD", "EURNZD", RelationKind.Chain, "EURUSD"), + ("USDCAD", "EURUSD", RelationKind.Chain, "EURCAD"), + ("EURAUD", "AUDCAD", RelationKind.Chain, "EURCAD"), + ("GBPUSD", "EURGBP", RelationKind.Chain, "EURUSD"), + ("NZDUSD", "AUDCHF", RelationKind.Disjoint, null), + ("EURCHF", "AUDCAD", RelationKind.Disjoint, null), + ]; + + var spreads = Relations.DocumentedSpreads; + Assert.AreEqual(8, spreads.Count); + for (var i = 0; i < expected.Length; i++) + { + var (a, b, kind, cross) = expected[i]; + Assert.AreEqual(a, spreads[i].A.Name); + Assert.AreEqual(b, spreads[i].B.Name); + + var forward = Relations.Classify(FxPairs.Get(a), FxPairs.Get(b)); + var backward = Relations.Classify(FxPairs.Get(b), FxPairs.Get(a)); + Assert.AreEqual(kind, forward.Kind, $"{a}–{b}"); + Assert.AreEqual(kind, backward.Kind, $"{b}–{a}"); + Assert.AreEqual(cross, forward.Cross?.Name, $"{a}–{b}"); + Assert.AreEqual(cross, backward.Cross?.Name, $"{b}–{a}"); + Assert.AreEqual(forward.Common, backward.Common); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoClassificationDependsOnTheOrderOfTheLegs() + { + foreach (var couple in Relations.Couples) + { + var swapped = Relations.Classify(couple.B, couple.A); + Assert.AreEqual(couple.Kind, swapped.Kind); + Assert.AreEqual(couple.Cross, swapped.Cross); + Assert.AreEqual(couple.Common, swapped.Common); + + // Only the orientation of a ratio's synthetic A/B turns over with the legs. + if (couple.Kind == RelationKind.Ratio) + { + Assert.AreNotEqual(couple.CrossInverted, swapped.CrossInverted); + } + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ARatioNamesItsSyntheticCrossAndWhetherItIsTheInverse() + { + // Both quote USD: EURUSD / GBPUSD = EURGBP (section 4.1); swapped it is 1/EURGBP. + var both = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("GBPUSD")); + Assert.AreEqual(RelationKind.Ratio, both.Kind); + Assert.AreEqual("USD", both.Common); + Assert.AreEqual("EURGBP", both.Cross?.Name); + Assert.IsFalse(both.CrossInverted); + Assert.IsTrue(Relations.Classify(FxPairs.Get("GBPUSD"), FxPairs.Get("EURUSD")).CrossInverted); + + // Both base EUR: EURUSD / EURGBP = USD per GBP = GBPUSD. + var bases = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("EURGBP")); + Assert.AreEqual(RelationKind.Ratio, bases.Kind); + Assert.AreEqual("GBPUSD", bases.Cross?.Name); + Assert.IsFalse(bases.CrossInverted); + Assert.IsTrue(Relations.Classify(FxPairs.Get("EURGBP"), FxPairs.Get("EURUSD")).CrossInverted); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheSignIsPlusForChainsMinusForRatiosAndAgainstTheCorrelationForDisjoint() + { + Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, null)); + Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, 0.9)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, null)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, -0.9)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Disjoint, 0.3)); + Assert.AreEqual(1, Relations.Sign(RelationKind.Disjoint, -0.3)); + + // With no correlation, or a zero one, a disjoint couple has no sign and cannot be traded. + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, 0)); + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, null)); + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, double.NaN)); + + var disjoint = Relations.Classify(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF")); + Assert.AreEqual(-1, disjoint.Sign(0.5)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ACoupleOfAPairWithItselfIsRefused() + { + var pair = FxPairs.Get("EURUSD"); + Assert.ThrowsExactly(() => Relations.Classify(pair, pair)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFourteenPairListIsTheTwelveDocumentedSymbolsPlusEurcadAndAudnzd() + { + string[] expected = + [ + "EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD", + "AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF", + ]; + + var list = Relations.FourteenPairs; + CollectionAssert.AreEqual(expected, list.Select(p => p.Name).ToArray()); + + // Appendix A order, no yen: the order of the 28 with the others left out. + CollectionAssert.AreEqual(FxPairs.All.Where(list.Contains).ToArray(), list.ToArray()); + Assert.IsFalse(list.Any(p => p.Quote == Currencies.Jpy)); + + // Every leg of the eight documented spreads is in the list. + Assert.IsTrue(Relations.DocumentedSpreads.All(s => list.Contains(s.A) && list.Contains(s.B))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipIsOneHundredthForYenPairsAndOneTenThousandthForTheOthers() + { + string[] yen = ["EURJPY", "GBPJPY", "AUDJPY", "NZDJPY", "USDJPY", "CADJPY", "CHFJPY"]; + foreach (var pair in FxPairs.All) + { + Assert.AreEqual(yen.Contains(pair.Name) ? 0.01m : 0.0001m, pair.Pip, pair.Name); + } + + Assert.AreEqual(7, FxPairs.All.Count(p => p.Pip == 0.01m)); + } + + private static string Key(FxPair a, FxPair b) => string.CompareOrdinal(a.Name, b.Name) < 0 ? a.Name + b.Name : b.Name + a.Name; +} diff --git a/tests/Anubis.Tests/BasketSignalTests.cs b/tests/Anubis.Tests/BasketSignalTests.cs new file mode 100644 index 0000000..083914b --- /dev/null +++ b/tests/Anubis.Tests/BasketSignalTests.cs @@ -0,0 +1,322 @@ +using System.Globalization; +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// 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. +/// +[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)); + } + + /// Two price walks; bars after are the future that must not matter. + 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}"); + } +} diff --git a/tests/Anubis.Tests/ServerClockTests.cs b/tests/Anubis.Tests/ServerClockTests.cs new file mode 100644 index 0000000..161fac0 --- /dev/null +++ b/tests/Anubis.Tests/ServerClockTests.cs @@ -0,0 +1,162 @@ +using System.Globalization; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The server clock of the research document (Phase 12, issue #119): New York time plus seven hours, the server day, the daily +/// pause, the hourly window and the weekend rule. Four dates cover winter, summer and the weeks in which the United States +/// and Europe change the clock on different days (2026: US 8 March and 1 November, Europe 29 March and 25 October). +/// +[TestClass] +public sealed class ServerClockTests +{ + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15", 2, "2026-01-15T08:00:00Z", "2026-01-14T22:00:00Z")] + [DataRow("2026-03-16", 3, "2026-03-16T07:00:00Z", "2026-03-15T21:00:00Z")] + [DataRow("2026-07-15", 3, "2026-07-15T07:00:00Z", "2026-07-14T21:00:00Z")] + [DataRow("2026-10-27", 3, "2026-10-27T07:00:00Z", "2026-10-26T21:00:00Z")] + public void TheServerClockIsNewYorkPlusSevenHoursOnFourDates(string day, int offsetHours, string tenServerUtc, string midnightUtc) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var ten = Utc(tenServerUtc); + var midnight = Utc(midnightUtc); + + Assert.AreEqual(ten, ServerClock.At(date, new TimeOnly(10, 0))); + Assert.AreEqual(midnight, ServerClock.DayStart(date)); + Assert.AreEqual(TimeSpan.FromHours(offsetHours), ServerClock.OffsetFromUtc(ten)); + Assert.AreEqual(date.ToDateTime(new TimeOnly(10, 0)), ServerClock.ToServer(ten)); + + // The server day starts at server midnight, not a tick earlier. + Assert.AreEqual(date, ServerClock.Day(midnight)); + Assert.AreEqual(date.AddDays(-1), ServerClock.Day(midnight.AddTicks(-1))); + Assert.AreEqual(date, ServerClock.Day(ten)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15")] + [DataRow("2026-03-16")] + [DataRow("2026-07-15")] + [DataRow("2026-10-27")] + public void TheServerDayChangesAtFivePmNewYork(string day) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var five = Zones.At(date, new TimeOnly(17, 0), Zones.NewYork); + + Assert.AreEqual(date, ServerClock.Day(five.AddSeconds(-1))); + Assert.AreEqual(date.AddDays(1), ServerClock.Day(five)); + Assert.AreEqual(ServerClock.DayStart(date.AddDays(1)), five); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15", "2026-01-15T21:55:00Z", "2026-01-15T23:10:00Z")] + [DataRow("2026-03-16", "2026-03-16T20:55:00Z", "2026-03-16T22:10:00Z")] + [DataRow("2026-07-15", "2026-07-15T20:55:00Z", "2026-07-15T22:10:00Z")] + [DataRow("2026-10-27", "2026-10-27T20:55:00Z", "2026-10-27T22:10:00Z")] + public void TheDailyPauseRunsFrom1655To1810NewYorkHalfOpen(string day, string fromUtc, string toUtc) + { + var from = Utc(fromUtc); + var to = Utc(toUtc); + Assert.AreEqual(Zones.At(DateOnly.Parse(day, CultureInfo.InvariantCulture), new TimeOnly(16, 55), Zones.NewYork), from); + + Assert.IsFalse(ServerClock.InDailyPause(from.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InDailyPause(from)); + Assert.IsTrue(ServerClock.InDailyPause(from.AddMinutes(30))); + Assert.IsTrue(ServerClock.InDailyPause(to.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InDailyPause(to)); + + // The pause crosses server midnight; no entries inside it, whatever else allows them. + Assert.IsTrue(ServerClock.InDailyPause(ServerClock.DayStart(DateOnly.Parse(day, CultureInfo.InvariantCulture).AddDays(1)))); + Assert.IsFalse(ServerClock.EntriesAllowed(from, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(to, sessionOn: false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-16T14:00:00Z", "2026-01-19T00:00:00Z")] + [DataRow("2026-07-17T13:00:00Z", "2026-07-19T23:00:00Z")] + public void TheWeekendRuleBlocksFromFriday1600ToMonday0200ServerTimeHalfOpen(string fridayUtc, string mondayUtc) + { + var friday = Utc(fridayUtc); + var monday = Utc(mondayUtc); + Assert.AreEqual(DayOfWeek.Friday, ServerClock.ToServer(friday).DayOfWeek); + Assert.AreEqual(new TimeOnly(16, 0), TimeOnly.FromDateTime(ServerClock.ToServer(friday))); + Assert.AreEqual(DayOfWeek.Monday, ServerClock.ToServer(monday).DayOfWeek); + Assert.AreEqual(new TimeOnly(2, 0), TimeOnly.FromDateTime(ServerClock.ToServer(monday))); + + Assert.IsFalse(ServerClock.InWeekend(friday.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InWeekend(friday)); + Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(1))); + Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(2))); + Assert.IsTrue(ServerClock.InWeekend(monday.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InWeekend(monday)); + Assert.IsFalse(ServerClock.InWeekend(monday.AddDays(3))); + + Assert.IsFalse(ServerClock.EntriesAllowed(friday, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(monday, sessionOn: false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15")] + [DataRow("2026-03-16")] + [DataRow("2026-07-15")] + [DataRow("2026-10-27")] + public void TheHourlyWindowRunsFrom1000To2000ServerTimeHalfOpen(string day) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var ten = ServerClock.At(date, new TimeOnly(10, 0)); + var eight = ServerClock.At(date, new TimeOnly(20, 0)); + + Assert.IsFalse(ServerClock.InSession(ten.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InSession(ten)); + Assert.IsTrue(ServerClock.InSession(eight.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InSession(eight)); + + // The window only matters when it is switched on. + Assert.IsFalse(ServerClock.EntriesAllowed(eight, sessionOn: true)); + Assert.IsTrue(ServerClock.EntriesAllowed(eight, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(ten, sessionOn: true)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AfterTheEquityStopEntriesResumeAtTheNextServerDay() + { + // Thursday 15 January 2026, 15:00 New York = 22:00 server: the next server day starts at 17:00 New York. + var stop = new DateTimeOffset(2026, 1, 15, 20, 0, 0, TimeSpan.Zero); + Assert.AreEqual(new DateTimeOffset(2026, 1, 15, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(stop)); + + // One minute after the change the next day is a whole day later. + var after = new DateTimeOffset(2026, 1, 15, 22, 1, 0, TimeSpan.Zero); + Assert.AreEqual(new DateTimeOffset(2026, 1, 16, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(after)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AServerTimeTurnsBackIntoTheSameMoment() + { + var gen = new Gen(Property.DefaultSeed); + var start = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero); + for (var i = 0; i < 500; i++) + { + var moment = start.AddMinutes(gen.Int(0, 3 * 365 * 24 * 60)); + var server = ServerClock.ToServer(moment); + + // Away from the hour in which New York's clock goes back, a server time names one moment only. + if (server.DayOfWeek == DayOfWeek.Sunday && server.Hour is >= 7 and < 10) + { + continue; + } + + Assert.AreEqual(moment, ServerClock.FromServer(server), moment.ToString("O", CultureInfo.InvariantCulture)); + } + } + + private static DateTimeOffset Utc(string text) => + DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); +}