Fase 12 — Dati e matematica dei panieri (#187)
Research-only data and maths for basket mean reversion (ADR 0028): a seam between the trial judge and the engines, the basket maths in src/Anubis/Baskets, sub-day research bars, ECB crosses and FX minute import. refs #118, refs #119, refs #120, refs #121 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #187.
This commit is contained in:
1 parent
93cdf7850d
commit
e0a438a0b2
40 files changed
+4464
-110
No files matched your search
@@ -0,0 +1,278 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Baskets;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<FxPair, decimal> 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}");
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using Anubis.Baskets;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class BasketRelationTests
|
||||
{
|
||||
/// <summary>Appendix B, written out by hand from the document: row, leg A, leg B, synthetic cross.</summary>
|
||||
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<ArgumentException>(() => 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;
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
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));
|
||||
// A flat window of a value with no exact binary form: its mean misses by one rounding step, still no z.
|
||||
Assert.IsNull(BasketIndex.ZScore(Enumerable.Repeat(10856.1, 100).ToArray(), 99));
|
||||
Assert.IsNull(BasketIndex.ZScore(Enumerable.Repeat(0.1, 100).ToArray(), 99));
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
20240102 030000;1.094500;1.094800;1.094400;1.094700;0
|
||||
20240102 030100;1.094700;1.095200;1.094600;1.095100;0
|
||||
20240102 030700;1.095100;1.095300;1.094900;1.095000;0
|
||||
20240102 031400;1.095000;1.095000;1.094100;1.094300;0
|
||||
20240102 031500;1.094300;1.094600;1.094200;1.094500;0
|
||||
|
@@ -0,0 +1,6 @@
|
||||
Gmt time,Open,High,Low,Close,Volume
|
||||
02.01.2024 08:00:00.000,1.09462,1.09492,1.09452,1.09482,10.5
|
||||
02.01.2024 08:01:00.000,1.09482,1.09532,1.09472,1.09522,20.25
|
||||
02.01.2024 08:07:00.000,1.09522,1.09542,1.09502,1.09512,3
|
||||
02.01.2024 08:14:00.000,1.09512,1.09512,1.09422,1.09442,1.5
|
||||
02.01.2024 08:15:00.000,1.09442,1.09472,1.09432,1.09462,7
|
||||
|
@@ -0,0 +1,7 @@
|
||||
Gmt time,Open,High,Low,Close,Volume
|
||||
02.01.2024 08:00:00.000,1.09450,1.09480,1.09440,1.09470,10.5
|
||||
02.01.2024 08:01:00.000,1.09470,1.09520,1.09460,1.09510,20.25
|
||||
02.01.2024 08:07:00.000,1.09510,1.09530,1.09490,1.09500,3
|
||||
02.01.2024 08:14:00.000,1.09500,1.09500,1.09410,1.09430,1.5
|
||||
02.01.2024 08:15:00.000,1.09430,1.09460,1.09420,1.09450,7
|
||||
06.01.2024 12:00:00.000,1.09450,1.09450,1.09450,1.09450,0
|
||||
|
@@ -0,0 +1 @@
|
||||
{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"crypto_trend","strategy_name":"Trend crypto","strategy_version":"1","plan_hash":"7ec3317ccccbafae965e26b5c3346bfb4b5b98aec00bceb947e3dc996868e7d1","data_fingerprint":"c642391a4ac6bb996b606faa124a920f145d7e48348fd9992e8dc8847e7f5210","currency":"EUR","periods_per_year":365,"sessions":800,"instruments":[{"symbol":"BTCEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"ETHEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"SOLEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"}],"chosen":"coin_vol=10;max_stop=10","metrics":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":42498.58399720671700250,"total_return":3.2498583997206714,"annual_return":0.9375426829552627,"volatility":0.07235876643893155,"sharpe":9.178841572568931,"daily_sharpe":0.48044252607481563,"max_drawdown":0.026175829689565357,"drawdown_peak":"2026-10-11","drawdown_low":"2026-10-16","trades":36,"winners":10,"profit_factor":35.29456708299872,"average_win":2313.081459858028508055,"average_loss":-25.206335956407039201923076923,"fees":396.81028898370354480,"exposure":0.23565100560758143,"years":[{"year":2024,"start":10000,"end":10000,"result":0,"return":0},{"year":2025,"start":10000,"end":11331.10279399256161285,"result":1331.10279399256161285,"return":0.13311027939925602},{"year":2026,"start":11331.10279399256161285,"end":42498.58399720671700250,"result":31167.48120321415538965,"return":2.7506132253727587}],"net_result":32498.58399720671700250,"win_rate":0.2777777777777778},"benchmark":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":166213.82941437167155,"total_return":15.621382941437169,"annual_return":2.6141681851348806,"volatility":0.14608381895658237,"sharpe":8.877533265620782,"daily_sharpe":0.46467132848163395,"max_drawdown":0.09004021309394361,"drawdown_peak":"2026-10-11","drawdown_low":"2026-11-24","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.9099499956572297,"exposure":0.9974278743768157,"years":[{"year":2024,"start":10000,"end":15368.88961128832475,"result":5368.88961128832475,"return":0.5368889611288326},{"year":2025,"start":15368.88961128832475,"end":51003.69143985236835,"result":35634.80182856404360,"return":2.3186321673096395},{"year":2026,"start":51003.69143985236835,"end":166213.82941437167155,"result":115210.13797451930320,"return":2.2588588143739425}],"net_result":156213.82941437167155,"win_rate":0},"costs":[{"multiplier":1,"net_result":32498.58399720671700250,"total_return":3.2498583997206714,"sharpe":9.178841572568931,"max_drawdown":0.026175829689565357,"fees":396.81028898370354480},{"multiplier":2,"net_result":31681.95878299984471576,"total_return":3.1681958782999846,"sharpe":9.045311963181552,"max_drawdown":0.02651561512819553,"fees":784.70618400521720504},{"multiplier":3,"net_result":31370.57922715067109828,"total_return":3.1370579227150674,"sharpe":8.94483685023732,"max_drawdown":0.0274714489120567,"fees":1172.66034249574190652}],"variants":[{"parameters":"coin_vol=10;max_stop=10","sharpe":0.48044252607481563,"plateau_score":0.4653655889498502,"net_result":32498.58399720671700250,"max_drawdown":0.026175829689565357,"trades":36,"chosen":true,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=15","sharpe":0.445931236512579,"plateau_score":0.445931236512579,"net_result":26183.75750214343511961,"max_drawdown":0.029641772278433863,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=20","sharpe":0.4223858225329875,"plateau_score":0.4223858225329875,"net_result":24328.79097386721189274,"max_drawdown":0.029754173892141213,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=10","sharpe":0.4930869429792893,"plateau_score":0.4639457230048902,"net_result":50498.43419278263970438,"max_drawdown":0.025774756298243173,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=15","sharpe":0.4420016502327168,"plateau_score":0.4420016502327168,"net_result":38197.30057159239968207,"max_drawdown":0.033017070317847674,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=20","sharpe":0.41763453843434895,"plateau_score":0.41763453843434895,"net_result":33625.32347837452987842,"max_drawdown":0.03612622409318185,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=10","sharpe":0.48560767004198907,"plateau_score":0.46432514386048657,"net_result":51112.96885923040428466,"max_drawdown":0.026505594831178845,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=15","sharpe":0.4366043121879511,"plateau_score":0.4366043121879511,"net_result":38707.02428Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"crypto_trend","strategy_name":"Trend crypto","strategy_version":"1","plan_hash":"11f428e680695b378647e6aaa13aea82e3b18da3782d1a1d834aa7948a38d695","data_fingerprint":"c642391a4ac6bb996b606faa124a920f145d7e48348fd9992e8dc8847e7f5210","currency":"EUR","periods_per_year":365,"sessions":800,"instruments":[{"symbol":"BTCEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"ETHEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"SOLEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"}],"chosen":"coin_vol=10;max_stop=10","metrics":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":42515.803080578265635540,"total_return":3.251580308057827,"annual_return":0.9379015078266391,"volatility":0.07852841581547972,"sharpe":8.465947304810848,"daily_sharpe":0.44312793467261424,"max_drawdown":0.035651925733458024,"drawdown_peak":"2026-08-28","drawdown_low":"2026-09-05","trades":35,"winners":10,"profit_factor":30.15635208816501,"average_win":2264.676659182941375404,"average_loss":-30.039132751361173816,"fees":441.799860621142987760,"exposure":0.26147000965005857,"years":[{"year":2024,"start":10000,"end":10000,"result":0,"return":0},{"year":2025,"start":10000,"end":11099.7845636557723395,"result":1099.7845636557723395,"return":0.10997845636557724},{"year":2026,"start":11099.7845636557723395,"end":42515.803080578265635540,"result":31416.018516922493296040,"return":2.8303268713690657}],"net_result":32515.803080578265635540,"win_rate":0.2857142857142857},"benchmark":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":166213.82941437167155,"total_return":15.621382941437169,"annual_return":2.6141681851348806,"volatility":0.14608381895658237,"sharpe":8.877533265620782,"daily_sharpe":0.46467132848163395,"max_drawdown":0.09004021309394361,"drawdown_peak":"2026-10-11","drawdown_low":"2026-11-24","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.9099499956572297,"exposure":0.9974278743768157,"years":[{"year":2024,"start":10000,"end":15368.88961128832475,"result":5368.88961128832475,"return":0.5368889611288326},{"year":2025,"start":15368.88961128832475,"end":51003.69143985236835,"result":35634.80182856404360,"return":2.3186321673096395},{"year":2026,"start":51003.69143985236835,"end":166213.82941437167155,"result":115210.13797451930320,"return":2.2588588143739425}],"net_result":156213.82941437167155,"win_rate":0},"costs":[{"multiplier":1,"net_result":32515.803080578265635540,"total_return":3.251580308057827,"sharpe":8.465947304810848,"max_drawdown":0.035651925733458024,"fees":441.799860621142987760},{"multiplier":2,"net_result":31604.7097350250246126,"total_return":3.1604709735025027,"sharpe":8.331667571175304,"max_drawdown":0.03575808521269184,"fees":872.5110473917330314},{"multiplier":3,"net_result":31012.068464926335629035,"total_return":3.1012068464926337,"sharpe":8.222893267893769,"max_drawdown":0.03586474574965844,"fees":1296.530436665625798465}],"variants":[{"parameters":"coin_vol=10;max_stop=10","sharpe":0.48044252607481563,"plateau_score":0.4653655889498502,"net_result":32498.58399720671700250,"max_drawdown":0.026175829689565357,"trades":36,"chosen":true,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=15","sharpe":0.445931236512579,"plateau_score":0.445931236512579,"net_result":26183.75750214343511961,"max_drawdown":0.029641772278433863,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=20","sharpe":0.4223858225329875,"plateau_score":0.4223858225329875,"net_result":24328.79097386721189274,"max_drawdown":0.029754173892141213,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=10","sharpe":0.4930869429792893,"plateau_score":0.4639457230048902,"net_result":50498.43419278263970438,"max_drawdown":0.025774756298243173,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=15","sharpe":0.4420016502327168,"plateau_score":0.4420016502327168,"net_result":38197.30057159239968207,"max_drawdown":0.033017070317847674,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=20","sharpe":0.41763453843434895,"plateau_score":0.41763453843434895,"net_result":33625.32347837452987842,"max_drawdown":0.03612622409318185,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=10","sharpe":0.48560767004198907,"plateau_score":0.46432514386048657,"net_result":51112.96885923040428466,"max_drawdown":0.026505594831178845,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=15","sharpe":0.4366043121879511,"plateau_score":0.4366043121879511,"net_result":38707.0242885537Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"sma_cross","strategy_name":"Incrocio di medie (esempio)","strategy_version":"1","plan_hash":"990e63ec6f56622482e7a01e5c394a50b7c4ab71e49ae5648525cacf566ae1b1","data_fingerprint":"4d526d1396e3809f960d671c57f9ca3017f7cdc7198fa4781519169ba9630644","currency":"EUR","periods_per_year":365,"sessions":1349,"instruments":[{"symbol":"BTC-EUR","venue":"okx","first":"2018-01-01","last":"2022-02-08","bars":1500,"actions":0,"source":""}],"chosen":"fast=10;slow=50","metrics":{"from":"2018-06-01","to":"2022-02-08","initial_capital":10000,"final_equity":6285.4325248044152,"total_return":-0.3714567475195585,"annual_return":-0.11822555620871933,"volatility":0.35324063837526276,"sharpe":-0.17944546690357913,"daily_sharpe":-0.009392605017770376,"max_drawdown":0.6890295232626155,"drawdown_peak":"2018-12-05","drawdown_low":"2020-08-01","trades":16,"winners":7,"profit_factor":0.2622557627792188,"average_win":255.25905750743714285714285714,"average_loss":-757.02749255855977777777777778,"fees":409.512752353050,"exposure":0.40622683231406903,"years":[{"year":2018,"start":10000,"end":8685.755700826393,"result":-1314.244299173607,"return":-0.1314244299173607},{"year":2019,"start":8685.755700826393,"end":4374.272033425322,"result":-4311.483667401071,"return":-0.4963855553744001},{"year":2020,"start":4374.272033425322,"end":4271.497995114922,"result":-102.774038310400,"return":-0.02349511816482097},{"year":2021,"start":4271.497995114922,"end":5482.2471804670268,"result":1210.7491853521048,"return":0.2834483796402978},{"year":2022,"start":5482.2471804670268,"end":6285.4325248044152,"result":803.1853443373884,"return":0.14650659080077566}],"net_result":-3714.5674751955848,"win_rate":0.4375},"benchmark":{"from":"2018-06-01","to":"2022-02-08","initial_capital":10000,"final_equity":1428.644570017173,"total_return":-0.8571355429982828,"annual_return":-0.40977062822712385,"volatility":0.5265283233161793,"sharpe":-0.7366093915972111,"daily_sharpe":-0.038555897716660306,"max_drawdown":0.9147532355023699,"drawdown_peak":"2018-06-10","drawdown_low":"2021-11-10","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.91001444273,"exposure":0.9753449358029199,"years":[{"year":2018,"start":10000,"end":6350.615563974605,"result":-3649.384436025395,"return":-0.36493844360253946},{"year":2019,"start":6350.615563974605,"end":2391.41269070224,"result":-3959.202873272365,"return":-0.6234360800757482},{"year":2020,"start":2391.41269070224,"end":1717.725401513074,"result":-673.687289189166,"return":-0.28171101199238735},{"year":2021,"start":1717.725401513074,"end":1251.834328409172,"result":-465.891073103902,"return":-0.27122558279310394},{"year":2022,"start":1251.834328409172,"end":1428.644570017173,"result":176.810241608001,"return":0.14124092748973505}],"net_result":-8571.355429982827,"win_rate":0},"costs":[{"multiplier":1,"net_result":-3714.5674751955848,"total_return":-0.3714567475195585,"sharpe":-0.17944546690357913,"max_drawdown":0.6890295232626155,"fees":409.512752353050},{"multiplier":2,"net_result":-4213.435391198960,"total_return":-0.42134353911989597,"sharpe":-0.24253938590781685,"max_drawdown":0.701247870371674,"fees":793.032851375020},{"multiplier":3,"net_result":-4673.1546177568774,"total_return":-0.4673154617756877,"sharpe":-0.30535037551200916,"max_drawdown":0.7129997025296625,"fees":1152.407422350312}],"variants":[{"parameters":"fast=10;slow=50","sharpe":-0.009392605017770376,"plateau_score":-0.014421152695077044,"net_result":-3714.5674751955848,"max_drawdown":0.6890295232626155,"trades":16,"chosen":true,"outside_grid":false},{"parameters":"fast=10;slow=100","sharpe":-0.012439903845665106,"plateau_score":-0.018249437198971447,"net_result":-3759.8615550387032,"max_drawdown":0.49358888719810523,"trades":9,"chosen":false,"outside_grid":false},{"parameters":"fast=10;slow=150","sharpe":-0.01960343681733535,"plateau_score":-0.01960343681733535,"net_result":-4456.3707526755608,"max_drawdown":0.5566227548691635,"trades":7,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=50","sharpe":-0.022543401299485562,"plateau_score":-0.022543401299485562,"net_result":-5457.5870981397256,"max_drawdown":0.6584030293650209,"trades":16,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=100","sharpe":-0.013308700617387134,"plateau_score":-0.024154091365139782,"net_result":-3932.8860477973112,"max_drawdown":0.5226121704934336,"trades":7,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=150","sharpe":-0.03220857559618516,"plateau_score":-0.03220857559618516,"net_result":-5699.2247211905662,"max_drawdown":0.6560257168475645,"trades":6,"chosen":false,"outside_grid":false},{"parameters":"fast=30;slow=50","sharpe":-0.02809129797366409,"plateau_score":-0.02809129797366409,"net_result":-6052.8336160531412,"max_drawdown":0.7113621829037103,"trades":16,"chosen":false,"outside_grid":false},{"parameters":"fast=30;slow=100","sharpe":-0.03083313673334694,"plateauLine truncated
|
||||
@@ -0,0 +1,689 @@
|
||||
using System.IO.Compression;
|
||||
using Anubis.Baskets;
|
||||
using Anubis.Brokers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Bars shorter than a day for research, the 28 currency pairs from the ECB rates and the import of one-minute FX files
|
||||
/// (Phase 12, issue #120).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ResearchBarsTests
|
||||
{
|
||||
private static readonly DateTimeOffset _jan2 = new(2024, 1, 2, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static ResearchBar Minute(DateTimeOffset at, decimal open, decimal high, decimal low, decimal close, decimal volume = 1m) =>
|
||||
new(at, open, high, low, close, volume);
|
||||
|
||||
// ---- Timeframes ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TimeframesKnowTheirLengthAndWhichAreIntraday()
|
||||
{
|
||||
CollectionAssert.AreEqual(new[] { "1m", "15m", "30m", "1h", "4h", "8h", "1d" }, Timeframes.All.ToArray());
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(1), Timeframes.Length(Timeframes.Minute));
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(15), Timeframes.Length(Timeframes.Minutes15));
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(30), Timeframes.Length(Timeframes.Minutes30));
|
||||
Assert.AreEqual(TimeSpan.FromHours(1), Timeframes.Length(Timeframes.Hour));
|
||||
Assert.AreEqual(TimeSpan.FromHours(4), Timeframes.Length(Timeframes.Hours4));
|
||||
Assert.AreEqual(TimeSpan.FromHours(8), Timeframes.Length(Timeframes.Hours8));
|
||||
Assert.AreEqual(TimeSpan.FromDays(1), Timeframes.Length(Timeframes.Day));
|
||||
Assert.IsTrue(Timeframes.IsIntraday("15m"));
|
||||
Assert.IsTrue(Timeframes.IsIntraday("1m"));
|
||||
Assert.IsFalse(Timeframes.IsIntraday("1d"));
|
||||
Assert.IsFalse(Timeframes.IsIntraday("1w"), "an unknown timeframe is not intraday");
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Timeframes.Length("1w"));
|
||||
}
|
||||
|
||||
// ---- Aggregator ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorNeverFillsAGapAndEmitsPartialBuckets()
|
||||
{
|
||||
var minutes = new[]
|
||||
{
|
||||
Minute(_jan2.AddMinutes(31), 10m, 12m, 9m, 11m, 2m),
|
||||
Minute(_jan2, 5m, 6m, 4m, 5.5m, 1m),
|
||||
};
|
||||
|
||||
var bars = BarAggregator.Aggregate(minutes, Timeframes.Minutes15);
|
||||
|
||||
Assert.AreEqual(2, bars.Count, "the empty bucket of 00:15 gives no bar");
|
||||
Assert.AreEqual(new ResearchBar(_jan2, 5m, 6m, 4m, 5.5m, 1m), bars[0], "a bucket with one minute out of fifteen is still a bar");
|
||||
Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(30), 10m, 12m, 9m, 11m, 2m), bars[1]);
|
||||
Assert.AreEqual(0, BarAggregator.Aggregate([], Timeframes.Hour).Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorLeavesOutTheBucketThatHasNotClosed()
|
||||
{
|
||||
var minutes = Enumerable.Range(0, 21).Select(i => Minute(_jan2.AddMinutes(i), 1m + i, 2m + i, 0.5m + i, 1.5m + i)).ToList();
|
||||
|
||||
var early = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(25));
|
||||
Assert.AreEqual(1, early.Count, "00:15–00:30 ends after 00:25: not emitted");
|
||||
Assert.AreEqual(_jan2, early[0].OpensAt);
|
||||
|
||||
var closed = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(30));
|
||||
Assert.AreEqual(2, closed.Count, "a bucket that ends exactly at the cut is complete");
|
||||
Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(15), 16m, 22m, 15.5m, 21.5m, 6m), closed[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void FourHourBucketsOfBinanceMinutesStartOnUtcMultiples()
|
||||
{
|
||||
// Binance archives: 4h klines open at 00, 04, 08 … UTC; minutes carry quote volume and trades.
|
||||
var start = new DateTimeOffset(2024, 3, 10, 3, 58, 0, TimeSpan.Zero);
|
||||
var minutes = Enumerable.Range(0, 4)
|
||||
.Select(i => Minute(start.AddMinutes(i), 100m + i, 101m + i, 99m + i, 100.5m + i, 0.25m) with { QuoteVolume = 10.1m, Trades = 3 + i })
|
||||
.ToList();
|
||||
|
||||
var bars = BarAggregator.Aggregate(minutes, Timeframes.Hours4);
|
||||
|
||||
Assert.AreEqual(2, bars.Count);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 0, 0, 0, TimeSpan.Zero), bars[0].OpensAt);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 4, 0, 0, TimeSpan.Zero), bars[1].OpensAt);
|
||||
Assert.AreEqual(new ResearchBar(bars[0].OpensAt, 100m, 102m, 99m, 101.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 7 }, bars[0]);
|
||||
Assert.AreEqual(new ResearchBar(bars[1].OpensAt, 102m, 104m, 101m, 103.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 11 }, bars[1]);
|
||||
|
||||
// One minute without quote volume or trades: the sums would be wrong, so they stay empty.
|
||||
minutes[3] = minutes[3] with { QuoteVolume = null, Trades = null };
|
||||
var partial = BarAggregator.Aggregate(minutes, Timeframes.Hours4);
|
||||
Assert.AreEqual(20.2m, partial[0].QuoteVolume);
|
||||
Assert.IsNull(partial[1].QuoteVolume);
|
||||
Assert.IsNull(partial[1].Trades);
|
||||
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 8, 0, 0, TimeSpan.Zero),
|
||||
BarAggregator.BucketOf(new DateTimeOffset(2024, 3, 10, 12, 59, 0, TimeSpan.FromHours(1)), TimeSpan.FromHours(4)), "UTC, whatever the offset given");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorKeepsDecimalsExactAndRefusesUnalignedOrDuplicateMinutes()
|
||||
{
|
||||
var minutes = new[]
|
||||
{
|
||||
Minute(_jan2, 1.123456789012345678m, 1.2m, 1.1m, 1.15m, 0.1m),
|
||||
Minute(_jan2.AddMinutes(1), 1.15m, 1.3m, 1.000000000000000001m, 1.25m, 0.2m),
|
||||
};
|
||||
var bar = BarAggregator.Aggregate(minutes, Timeframes.Minutes30).Single();
|
||||
Assert.AreEqual(0.3m, bar.Volume, "0.1 + 0.2 is 0.3 in decimal");
|
||||
Assert.AreEqual(1.123456789012345678m, bar.Open);
|
||||
Assert.AreEqual(1.000000000000000001m, bar.Low);
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate([Minute(_jan2.AddSeconds(30), 1m, 1m, 1m, 1m)], Timeframes.Minutes15));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate([minutes[0], minutes[0]], Timeframes.Minutes15));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate(minutes, Timeframes.Day + "x"));
|
||||
}
|
||||
|
||||
// ---- Calendars ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFxWeekOpensSundayAndClosesFridayAtFivePmNewYorkAcrossDaylightSaving()
|
||||
{
|
||||
var fx = BarCalendars.Fx;
|
||||
var quarter = TimeSpan.FromMinutes(15);
|
||||
static DateTimeOffset Utc(int month, int day, int hour, int minute) => new(2024, month, day, hour, minute, 0, TimeSpan.Zero);
|
||||
|
||||
// Friday 8 March 2024 closes at 17:00 EST (22:00 UTC); the US clocks move on Sunday 10 March, so it reopens
|
||||
// at 17:00 EDT (21:00 UTC). Europe moves on 31 March: the two are different weeks.
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 8, 21, 45), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 8, 22, 0), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 9, 12, 0), quarter), "Saturday");
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 20, 45), quarter));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 10, 21, 0), quarter));
|
||||
|
||||
// November: Friday 1 closes at 17:00 EDT (21:00 UTC), Sunday 3 reopens at 17:00 EST (22:00 UTC).
|
||||
Assert.IsTrue(fx.IsOpen(Utc(11, 1, 20, 45), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(11, 1, 21, 0), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(11, 3, 21, 45), quarter));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(11, 3, 22, 0), quarter));
|
||||
|
||||
var march = fx.Moments(Utc(3, 8, 0, 0), Utc(3, 11, 0, 0), quarter).ToList();
|
||||
Assert.AreEqual(Utc(3, 8, 21, 45), march.Last(t => t < Utc(3, 9, 0, 0)));
|
||||
Assert.AreEqual(Utc(3, 10, 21, 0), march.First(t => t > Utc(3, 9, 0, 0)));
|
||||
Assert.AreEqual(88 + 12, march.Count, "Friday until 22:00 UTC, then Sunday from 21:00 UTC");
|
||||
|
||||
// A bar that straddles the opening is open: it holds traded minutes.
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 10, 20, 0), TimeSpan.FromHours(4)));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 16, 0), TimeSpan.FromHours(4)));
|
||||
|
||||
// Daily bars: Monday to Friday, the days the ECB publishes.
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 0, 0), TimeSpan.FromDays(1)));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 11, 0, 0), TimeSpan.FromDays(1)));
|
||||
Assert.IsTrue(BarCalendars.Always.IsOpen(Utc(3, 9, 12, 0), quarter));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CalendarsCountTheirPeriodsPerYearAndExchangesKeepOnlyTheirSessions()
|
||||
{
|
||||
Assert.AreEqual(35040, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromMinutes(15)));
|
||||
Assert.AreEqual(365, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
Assert.AreEqual(24960, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromMinutes(15)), "52 weeks × 5 days × 96");
|
||||
Assert.AreEqual(260, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
|
||||
var day = new DateOnly(2024, 7, 2);
|
||||
var session = new MarketSession(day, Zones.At(day, new TimeOnly(9, 30), Zones.NewYork), Zones.At(day, new TimeOnly(16, 0), Zones.NewYork));
|
||||
var exchange = BarCalendars.Exchange([session]);
|
||||
Assert.AreEqual("exchange", exchange.Name);
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 15, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)));
|
||||
Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 30, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "09:30 EDT");
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 20, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "16:00 EDT is the close");
|
||||
Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1)));
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 3, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1)), "no session that day");
|
||||
Assert.AreEqual(26, exchange.Moments(session.OpenUtc.AddHours(-2), session.CloseUtc.AddHours(2), TimeSpan.FromMinutes(15)).Count());
|
||||
Assert.AreEqual(252 * 26, exchange.PeriodsPerYear(TimeSpan.FromMinutes(15)));
|
||||
Assert.AreEqual(252, exchange.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
}
|
||||
|
||||
// ---- BarDataset ----
|
||||
|
||||
private static Dictionary<string, IReadOnlyList<ResearchBar>> TwoSymbols() => new(StringComparer.Ordinal)
|
||||
{
|
||||
["BBB"] = [Minute(_jan2, 1m, 2m, 0.5m, 1.5m), Minute(_jan2.AddMinutes(30), 3m, 4m, 2.5m, 3.5m), Minute(_jan2.AddMinutes(45), 5m, 6m, 4.5m, 5.5m)],
|
||||
["AAA"] = [Minute(_jan2, 10m, 20m, 5m, 15m), Minute(_jan2.AddMinutes(15), 11m, 21m, 6m, 16m), Minute(_jan2.AddMinutes(30), 12m, 22m, 7m, 17m)],
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetSharesOneClockAndLeavesMissingBarsEmpty()
|
||||
{
|
||||
var bars = TwoSymbols();
|
||||
bars["AAA"] = [.. bars["AAA"], Minute(_jan2.AddDays(4).AddHours(12), 1m, 1m, 1m, 1m)]; // Saturday: outside the FX week.
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), bars);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "AAA", "BBB" }, data.Symbols.ToArray(), "ordinal order");
|
||||
CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15), _jan2.AddMinutes(30), _jan2.AddMinutes(45) }, data.Clock.ToArray());
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(15), data.Length);
|
||||
Assert.AreEqual(24960, data.PeriodsPerYear);
|
||||
Assert.IsTrue(data.Has("BBB", 0));
|
||||
Assert.IsFalse(data.Has("BBB", 1));
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("BBB").Close[1]), "a missing bar is NaN, never the previous close");
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("BBB").Open[1]));
|
||||
Assert.AreEqual(3.5, data.Bars("BBB").Close[2]);
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("AAA").Close[3]));
|
||||
Assert.AreEqual(16.0, data.Bars("AAA").Close[data.IndexOf(_jan2.AddMinutes(15))]);
|
||||
Assert.AreEqual(-1, data.IndexOf(_jan2.AddMinutes(7)));
|
||||
Assert.AreEqual(0, data.Dropped, "the Saturday bar is outside [from, to): not counted");
|
||||
Assert.IsNull(data.Ask("AAA"));
|
||||
|
||||
var week = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddDays(7), bars);
|
||||
Assert.AreEqual(1, week.Dropped, "a bar on Saturday is outside the FX week");
|
||||
Assert.AreEqual(5 * 96, week.Clock.Count, "Tuesday 00:00 UTC to the next Tuesday, without Friday 22:00 to Sunday 22:00 UTC");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetThroughNeverShowsABarThatHasNotClosed()
|
||||
{
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols());
|
||||
|
||||
var cut = data.Through(_jan2.AddMinutes(37));
|
||||
CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15) }, cut.Clock.ToArray(), "the bar of 00:30 closes at 00:45");
|
||||
Assert.AreEqual(2, cut.Bars("AAA").Close.Count);
|
||||
Assert.AreEqual(_jan2.AddMinutes(30), cut.ClosesAt(1));
|
||||
Assert.AreEqual(3, data.Through(_jan2.AddMinutes(45)).Clock.Count, "a bar that closes exactly at the cut is known");
|
||||
Assert.AreEqual(0, data.Through(_jan2.AddMinutes(14)).Clock.Count);
|
||||
|
||||
var middle = data.Between(_jan2.AddMinutes(15), _jan2.AddMinutes(45));
|
||||
CollectionAssert.AreEqual(new[] { _jan2.AddMinutes(15), _jan2.AddMinutes(30) }, middle.Clock.ToArray());
|
||||
Assert.AreEqual(17.0, middle.Bars("AAA").Close[1]);
|
||||
Assert.IsTrue(double.IsNaN(middle.Bars("BBB").Close[0]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetFingerprintChangesWhenOnePriceChanges()
|
||||
{
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols());
|
||||
Assert.AreEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint());
|
||||
Assert.AreEqual(64, data.Fingerprint().Length);
|
||||
|
||||
var changed = TwoSymbols();
|
||||
changed["BBB"] = [changed["BBB"][0], changed["BBB"][1] with { Close = 3.5000001m }, changed["BBB"][2]];
|
||||
Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), changed).Fingerprint());
|
||||
Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint(), "the calendar is part of the data");
|
||||
Assert.AreNotEqual(data.Fingerprint(), data.Through(_jan2.AddMinutes(45)).Fingerprint());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BarDatasetReadsBidAndAskSeriesFromTheResearchStore()
|
||||
{
|
||||
var folder = TempFolder.Create("bardataset");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(folder);
|
||||
await store.WriteAsync("dukascopy", "EURUSD-BID", Timeframes.Minutes15, [Minute(_jan2, 1.1m, 1.2m, 1.0m, 1.15m)], CancellationToken.None).ConfigureAwait(false);
|
||||
await store.WriteAsync("dukascopy", "EURUSD-ASK", Timeframes.Minutes15, [Minute(_jan2, 1.1001m, 1.2001m, 1.0001m, 1.1501m)], CancellationToken.None).ConfigureAwait(false);
|
||||
await store.WriteAsync("dukascopy", "USDJPY-BID", Timeframes.Minutes15, [Minute(_jan2.AddMinutes(15), 150m, 151m, 149m, 150.5m)], CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
var data = await BarDataset.LoadQuotesAsync(store, "dukascopy", ["USDJPY", "EURUSD"], Timeframes.Minutes15, _jan2, _jan2.AddMinutes(30), CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { "EURUSD", "USDJPY" }, data.Symbols.ToArray());
|
||||
Assert.AreEqual("24x5", data.Calendar.Name);
|
||||
Assert.AreEqual(1.15, data.Bars("EURUSD").Close[0]);
|
||||
Assert.AreEqual(1.1501, data.Ask("EURUSD")!.Close[0]);
|
||||
Assert.IsNull(data.Ask("USDJPY"), "no ask file for the pair: no ask columns");
|
||||
Assert.AreEqual(150.5, data.Bars("USDJPY").Close[1]);
|
||||
|
||||
var plain = await BarDataset.LoadAsync(store, "dukascopy", ["EURUSD-BID"], Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddMinutes(30), CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
Assert.AreEqual(1.15, plain.Bars("EURUSD-BID").Close[0]);
|
||||
Assert.IsTrue(double.IsNaN(plain.Bars("EURUSD-BID").Close[1]));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ECB crosses ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTwentyEightPairsComeFromTheSevenEcbRates()
|
||||
{
|
||||
CollectionAssert.AreEquivalent(new[] { "GBP", "AUD", "NZD", "USD", "CAD", "CHF", "JPY" }, EcbCrosses.Rates.ToArray());
|
||||
var rates = Ecb.ParseHistoryCsv(Fixture.Text("free/ecb-hist.csv"), EcbCrosses.Rates);
|
||||
var crosses = EcbCrosses.Build(rates);
|
||||
|
||||
CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), crosses.Keys.ToArray(), "the pairs and their order come from the shared list");
|
||||
Assert.AreEqual(56, crosses.Values.Sum(b => b.Count), "28 pairs × 2 days");
|
||||
|
||||
var day = new DateTimeOffset(2026, 11, 9, 0, 0, 0, TimeSpan.Zero);
|
||||
decimal On(string pair, DateTimeOffset at) => crosses[pair].Single(b => b.OpensAt == at).Close;
|
||||
var usdjpy = crosses["USDJPY"].Single(b => b.OpensAt == day);
|
||||
Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy.Close);
|
||||
Assert.AreEqual(new ResearchBar(day, usdjpy.Close, usdjpy.Close, usdjpy.Close, usdjpy.Close, 0m), usdjpy, "O = H = L = C at 00:00 UTC, volume 0");
|
||||
Assert.AreEqual(176.79m, On("EURJPY", day), "a EUR pair is the rate itself");
|
||||
Assert.AreEqual(0.8343m, On("EURGBP", day));
|
||||
var expected = new Dictionary<string, decimal>
|
||||
{
|
||||
["USDJPY"] = 157.94693112m,
|
||||
["GBPUSD"] = 1.34160374m,
|
||||
["GBPJPY"] = 211.90219346m,
|
||||
["AUDUSD"] = 0.68939394m,
|
||||
["AUDCAD"] = 0.97222222m,
|
||||
["AUDNZD"] = 1.22819660m,
|
||||
["NZDUSD"] = 0.56130585m,
|
||||
["USDCAD"] = 1.41025641m,
|
||||
["USDCHF"] = 0.81872599m,
|
||||
["CADCHF"] = 0.58055116m,
|
||||
["CADJPY"] = 111.99873297m,
|
||||
["CHFJPY"] = 192.91793976m,
|
||||
};
|
||||
foreach (var (pair, value) in expected)
|
||||
{
|
||||
Assert.AreEqual(value, Math.Round(On(pair, day), 8), pair);
|
||||
}
|
||||
|
||||
var friday = day.AddDays(-3);
|
||||
Assert.AreEqual(158.32512315m, Math.Round(On("USDJPY", friday), 8));
|
||||
Assert.AreEqual(1.33848828m, Math.Round(On("GBPUSD", friday), 8));
|
||||
|
||||
// A day without the franc: only the seven pairs with CHF lose that day.
|
||||
var withoutFranc = rates.Where(r => !(r.Quote == "CHF" && r.Date == new DateOnly(2026, 11, 6))).ToList();
|
||||
var partial = EcbCrosses.Build(withoutFranc);
|
||||
Assert.AreEqual(49, partial.Values.Sum(b => b.Count));
|
||||
foreach (var pair in FxPairs.All)
|
||||
{
|
||||
Assert.AreEqual(pair.Base == "CHF" || pair.Quote == "CHF" ? 1 : 2, partial[pair.Name].Count, pair.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] EcbZip()
|
||||
{
|
||||
using var zip = new MemoryStream();
|
||||
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
|
||||
using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open()))
|
||||
{
|
||||
writer.Write(Fixture.Text("free/ecb-hist.csv"));
|
||||
}
|
||||
|
||||
return zip.ToArray();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataEcbWritesTheTwentyEightPairsAndOfflineReusesTheCachedHistory()
|
||||
{
|
||||
var data = TempFolder.Create("data-ecb");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip());
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], output, env, http).ConfigureAwait(false), output.ToString());
|
||||
Assert.AreEqual(1, http.Requests.Count);
|
||||
StringAssert.Contains(output.ToString(), "Coppie di valute dai cambi BCE: 28 coppie, 2 giorni, dal 2026-11-06 al 2026-11-09.");
|
||||
|
||||
var research = Path.Combine(data, "research");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(research, Ecb.HistoryFile)), "the same cached zip as backtest base");
|
||||
var store = new ResearchStore(research);
|
||||
var series = store.Series();
|
||||
Assert.AreEqual(28, series.Count);
|
||||
Assert.IsTrue(series.All(s => s.Venue == "ecb" && s.Timeframe == Timeframes.Day), string.Join(", ", series));
|
||||
CollectionAssert.AreEquivalent(FxPairs.All.Select(p => p.Name).ToArray(), series.Select(s => s.Symbol).ToArray());
|
||||
var usdjpy = await store.ReadAsync("ecb", "USDJPY", Timeframes.Day, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false);
|
||||
Assert.AreEqual(2, usdjpy.Count);
|
||||
Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy[1].Close, "the file keeps every decimal");
|
||||
|
||||
var offline = new FakeHttp();
|
||||
using var again = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--offline", "--platform", "docker", "--data-dir", data], again, env, offline).ConfigureAwait(false), again.ToString());
|
||||
Assert.AreEqual(0, offline.Requests.Count, "offline with the cached zip: no request");
|
||||
StringAssert.Contains(again.ToString(), "28 coppie");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BacktestBaseStillPrintsTheSameEcbLineFromTheSharedLoader()
|
||||
{
|
||||
var research = TempFolder.Create("ecb-loader");
|
||||
try
|
||||
{
|
||||
var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 8, 0, 0, TimeSpan.Zero));
|
||||
var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip());
|
||||
using var output = new StringWriter();
|
||||
var rates = await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, output).ConfigureAwait(false);
|
||||
Assert.AreEqual("Cambi BCE EUR/USD: 2 giorni, dal 2026-11-06 al 2026-11-09." + Environment.NewLine, output.ToString());
|
||||
Assert.AreEqual(2, rates.Count);
|
||||
Assert.IsTrue(rates.All(r => r.Quote == "USD"), "only the dollar, as before");
|
||||
Assert.AreEqual(1, http.Requests.Count, "offline but without the cached zip: downloaded once");
|
||||
Assert.AreEqual(Path.Combine(research, "ecb-eurofxref-hist.zip"), Ecb.HistoryPath(research));
|
||||
|
||||
await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, TextWriter.Null).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, http.Requests.Count, "offline with the cached zip: no request");
|
||||
await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: false, TextWriter.Null).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, http.Requests.Count, "online: downloaded again");
|
||||
|
||||
var missing = new FakeHttp().On("eurofxref-hist.zip", "", System.Net.HttpStatusCode.NotFound);
|
||||
var error = await Assert.ThrowsExactlyAsync<MarketDataException>(() =>
|
||||
Ecb.LoadHistoryAsync(new ApiHttp(missing.Client(), clock, "ecb"), Path.Combine(research, "empty"), offline: true, ["USD"], CancellationToken.None)).ConfigureAwait(false);
|
||||
Assert.AreEqual("BCE: lo storico dei cambi non è disponibile.", error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(research);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- FX minute files ----
|
||||
|
||||
private const string HistDataFile = "fx/DAT_ASCII_EURUSD_M1_2024.csv";
|
||||
private const string DukascopyBid = "fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv";
|
||||
private const string DukascopyAsk = "fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv";
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task FifteenMinuteBarsFromMinutesMatchTheHandComputedOnesInBothFormats()
|
||||
{
|
||||
// Constructed samples (no real file yet): the same bid prices in both formats, HistData at fixed UTC−5.
|
||||
var folder = TempFolder.Create("fx-15m");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(folder);
|
||||
var importer = new FxMinuteImporter(store);
|
||||
var eight = new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero);
|
||||
async Task<List<ResearchBar>> Read(string venue, string series, string timeframe) =>
|
||||
await store.ReadAsync(venue, series, timeframe, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false);
|
||||
|
||||
var histdata = await importer.ImportAsync(Fixture.Path(HistDataFile), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, histdata.Count);
|
||||
Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "1m", 5, eight, eight.AddMinutes(15), histdata[0].Notes), histdata[0]);
|
||||
Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "15m", 2, eight, eight.AddMinutes(15), histdata[1].Notes), histdata[1]);
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 0m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 0m),
|
||||
}, await Read("histdata", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
Assert.AreEqual(eight, (await Read("histdata", "EURUSD-BID", "1m").ConfigureAwait(false))[0].OpensAt, "03:00 at UTC−5 is 08:00 UTC");
|
||||
Assert.IsTrue(histdata[0].Notes.Any(n => n.StartsWith(IssueKinds.Gap, StringComparison.Ordinal)), "the missing minutes are reported against the FX week");
|
||||
|
||||
var bid = await importer.ImportAsync(Fixture.Path(DukascopyBid), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual("dukascopy", bid[0].Venue);
|
||||
Assert.AreEqual("EURUSD-BID", bid[0].Symbol);
|
||||
Assert.AreEqual(5, bid[0].Bars, "the flat Saturday bar is left out");
|
||||
Assert.IsTrue(bid[0].Notes.Any(n => n.Contains("1 barre fuori dall'orario del mercato", StringComparison.Ordinal)), string.Join(" | ", bid[0].Notes));
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 35.25m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 7m),
|
||||
}, await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
|
||||
var ask = await importer.ImportAsync(Fixture.Path(DukascopyAsk), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual("EURUSD-ASK", ask[1].Symbol);
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.09462m, 1.09542m, 1.09422m, 1.09442m, 35.25m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.09442m, 1.09472m, 1.09432m, 1.09462m, 7m),
|
||||
}, await Read("dukascopy", "EURUSD-ASK", "15m").ConfigureAwait(false));
|
||||
|
||||
// The same minutes through the pure aggregator give the same bars.
|
||||
var minutes = await Read("dukascopy", "EURUSD-BID", "1m").ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(BarAggregator.Aggregate(minutes, Timeframes.Minutes15).ToList(), await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataFxWritesMinuteAndFifteenMinuteSeriesForBothFormats()
|
||||
{
|
||||
var data = TempFolder.Create("data-fx");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
using var output = new StringWriter();
|
||||
foreach (var file in new[] { HistDataFile, DukascopyBid, DukascopyAsk })
|
||||
{
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["fx", Fixture.Path(file), "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString());
|
||||
}
|
||||
|
||||
var text = output.ToString();
|
||||
StringAssert.Contains(text, "histdata EURUSD-BID 1m: 5 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC).");
|
||||
StringAssert.Contains(text, "histdata EURUSD-BID 15m: 2 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC).");
|
||||
StringAssert.Contains(text, "dukascopy EURUSD-ASK 15m: 2 barre");
|
||||
var series = new ResearchStore(Path.Combine(data, "research")).Series();
|
||||
CollectionAssert.AreEquivalent(new[]
|
||||
{
|
||||
("dukascopy", "EURUSD-ASK", "15m"), ("dukascopy", "EURUSD-ASK", "1m"), ("dukascopy", "EURUSD-BID", "15m"), ("dukascopy", "EURUSD-BID", "1m"),
|
||||
("histdata", "EURUSD-BID", "15m"), ("histdata", "EURUSD-BID", "1m"),
|
||||
}, series.ToArray());
|
||||
|
||||
// A HistData file renamed: the pair comes from --symbol.
|
||||
var renamed = Path.Combine(data, "import", "minuti.csv");
|
||||
File.Copy(Fixture.Path(HistDataFile), renamed);
|
||||
using var named = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["fx", renamed, "--symbol", "gbpusd", "--platform", "docker", "--data-dir", data], named, env).ConfigureAwait(false), named.ToString());
|
||||
StringAssert.Contains(named.ToString(), "histdata GBPUSD-BID 15m: 2 barre");
|
||||
using var nameless = new StringWriter();
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["fx", renamed, "--platform", "docker", "--data-dir", data], nameless, env).ConfigureAwait(false));
|
||||
StringAssert.Contains(nameless.ToString(), "--symbol");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataFxRefusesAnUnknownFormatInItalian()
|
||||
{
|
||||
var data = TempFolder.Create("data-fx-unknown");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
var metatrader = Path.Combine(data, "DAT_MT_EURUSD_M1_2024.csv");
|
||||
await File.WriteAllTextAsync(metatrader, "2024.01.01,17:00,1.104270,1.104290,1.104270,1.104290,0\n").ConfigureAwait(false);
|
||||
var local = Path.Combine(data, "EURUSD_Candlestick_1_M_BID_01.01.2024-31.12.2024.csv");
|
||||
await File.WriteAllTextAsync(local, "Local time,Open,High,Low,Close,Volume\n02.01.2024 09:00:00.000 GMT+0100,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false);
|
||||
var sideless = Path.Combine(data, "EURUSD_Candlestick_1_M_01.01.2024-31.12.2024.csv");
|
||||
await File.WriteAllTextAsync(sideless, "Gmt time,Open,High,Low,Close,Volume\n02.01.2024 08:00:00.000,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false);
|
||||
|
||||
foreach (var (file, words) in new[]
|
||||
{
|
||||
(metatrader, "Formato non riconosciuto"), (local, "ora locale"), (sideless, "_BID_"),
|
||||
})
|
||||
{
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["fx", file, "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString());
|
||||
StringAssert.StartsWith(output.ToString(), "Non riuscito: ");
|
||||
StringAssert.Contains(output.ToString(), words);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, new ResearchStore(Path.Combine(data, "research")).Series().Count, "nothing written");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataFxSaysWhyWhenEveryBarFallsOutsideTheMarketWeek()
|
||||
{
|
||||
var data = TempFolder.Create("data-fx-weekend");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
const string NL = "\n";
|
||||
var saturday = Path.Combine(data, "EURUSD_Candlestick_1_M_BID_06.01.2024-06.01.2024.csv");
|
||||
await File.WriteAllTextAsync(saturday, "Gmt time,Open,High,Low,Close,Volume" + NL + "06.01.2024 08:00:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL
|
||||
+ "06.01.2024 08:01:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL + "06.01.2024 08:02:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL).ConfigureAwait(false);
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["fx", saturday, "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString());
|
||||
StringAssert.StartsWith(output.ToString(), "Non riuscito: ");
|
||||
StringAssert.Contains(output.ToString(), "tutte le 3 barre lette cadono fuori dall'orario del mercato");
|
||||
Assert.AreEqual(0, new ResearchStore(Path.Combine(data, "research")).Series().Count, "nothing written");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ABrokenEcbHistoryNeverReplacesTheGoodOneAndIsRefusedInItalian()
|
||||
{
|
||||
var data = TempFolder.Create("data-ecb-broken");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
using (var first = new StringWriter())
|
||||
{
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], first, env, new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip())).ConfigureAwait(false), first.ToString());
|
||||
}
|
||||
|
||||
var cached = Path.Combine(data, "research", Ecb.HistoryFile);
|
||||
var good = await File.ReadAllBytesAsync(cached).ConfigureAwait(false);
|
||||
|
||||
// The ECB answers with a page that is not the history: the command stops in Italian and the good copy stays.
|
||||
var page = new FakeHttp().OnBytes("eurofxref-hist.zip", System.Text.Encoding.UTF8.GetBytes("<html>Manutenzione</html>"));
|
||||
using (var output = new StringWriter())
|
||||
{
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], output, env, page).ConfigureAwait(false), output.ToString());
|
||||
StringAssert.StartsWith(output.ToString(), "Non riuscito: BCE: il file scaricato non è lo storico dei cambi");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(good, await File.ReadAllBytesAsync(cached).ConfigureAwait(false), "the good history is untouched");
|
||||
Assert.IsFalse(File.Exists(cached + ".tmp"));
|
||||
|
||||
// A cached copy cut short (an old interrupted write): offline, the command says so instead of crashing.
|
||||
await File.WriteAllBytesAsync(cached, good.AsSpan(0, good.Length / 2).ToArray()).ConfigureAwait(false);
|
||||
using (var output = new StringWriter())
|
||||
{
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["ecb", "--offline", "--platform", "docker", "--data-dir", data], output, env, new FakeHttp()).ConfigureAwait(false), output.ToString());
|
||||
StringAssert.StartsWith(output.ToString(), "Non riuscito: BCE: il file già scaricato non è lo storico dei cambi");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task DataUsageListsTheNewCommandsAndTimeframes()
|
||||
{
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(2, await DataCommand.RunAsync(["nothing"], output, ServerHarness.DockerSqlite()).ConfigureAwait(false));
|
||||
var usage = output.ToString();
|
||||
StringAssert.Contains(usage, "<1d|1m|15m|30m|1h|4h|8h>");
|
||||
StringAssert.Contains(usage, "anubis data ecb [--offline]");
|
||||
StringAssert.Contains(usage, "anubis data fx <file.csv> [--symbol EURUSD]");
|
||||
}
|
||||
|
||||
// ---- CSV importer ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CsvParseIsPureAndReadsAFixedOffsetAllYear()
|
||||
{
|
||||
var mapping = new CsvMapping { Delimiter = ";", HasHeader = false, TimeFormat = "yyyyMMdd HHmmss", TimeZone = "UTC-05:00" };
|
||||
var parsed = CsvImporter.Parse(["20240102 030000;1;2;0.5;1.5;0", "", "20240702 030000;1;2;0.5;1.5;0", "20240703 0300;1;2;0.5;1.5;0"], mapping);
|
||||
|
||||
Assert.AreEqual(4, parsed.Lines);
|
||||
Assert.AreEqual(1, parsed.Errors);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[0].OpensAt);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 7, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[1].OpensAt, "no daylight saving: still 08:00 UTC in July");
|
||||
StringAssert.StartsWith(parsed.Notes[0], "riga 4: ");
|
||||
Assert.AreEqual("1 righe non lette su 4", parsed.Notes[^1]);
|
||||
Assert.AreEqual(TimeSpan.FromHours(5.5), CsvImporter.ZoneOf("UTC+05:30").BaseUtcOffset);
|
||||
Assert.AreEqual(TimeSpan.Zero, CsvImporter.ZoneOf("UTC").BaseUtcOffset);
|
||||
Assert.ThrowsExactly<TimeZoneNotFoundException>(() => CsvImporter.ZoneOf("Nowhere/Atlantis"));
|
||||
Assert.ThrowsExactly<TimeZoneNotFoundException>(() => CsvImporter.ZoneOf("UTC-05:60"), "a typo in the minutes is refused, not read as UTC-06:00");
|
||||
Assert.ThrowsExactly<TimeZoneNotFoundException>(() => CsvImporter.ZoneOf("UTC+00:90"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task CsvImporterChecksIntradayBarsAtTheirOwnLength()
|
||||
{
|
||||
var folder = TempFolder.Create("csv-15m");
|
||||
try
|
||||
{
|
||||
var csv = Path.Combine(folder, "btcusdt-15m.csv");
|
||||
await File.WriteAllTextAsync(csv,
|
||||
"time,open,high,low,close,volume\n" +
|
||||
"2024-01-02 00:00:00,100,101,99,100.5,1\n" +
|
||||
"2024-01-02 00:15:00,100.5,102,100,101,1\n" +
|
||||
"2024-01-02 00:45:00,101,103,100,102,1\n").ConfigureAwait(false);
|
||||
var mapping = new CsvMapping { Timeframe = Timeframes.Minutes15, TimeFormat = "yyyy-MM-dd HH:mm:ss" };
|
||||
var store = new ResearchStore(Path.Combine(folder, "research"));
|
||||
|
||||
var result = await new CsvImporter(store).ImportAsync(csv, mapping, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
Assert.AreEqual(3, result.Bars);
|
||||
Assert.IsFalse(result.Notes.Any(n => n.StartsWith(IssueKinds.Duplicate, StringComparison.Ordinal)), "three bars of one day are not duplicates: " + string.Join(" | ", result.Notes));
|
||||
Assert.AreEqual("gap 2024-01-02 00:30: Manca una barra da 15m", result.Notes.Single());
|
||||
Assert.AreEqual(3, (await store.ReadAsync("import", "BTCUSDT", "15m", DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false)).Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Baskets;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The seam between the trial judge and the engines (Phase 12, issue #118): the judge takes any <see cref="ITrialEngine"/>
|
||||
/// and any <see cref="IResearchFamily"/>, the report gains an optional basket section, the plateau rule knows choice axes,
|
||||
/// and nothing of what exists moves (the golden reports are in <see cref="TrialSeamTests"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class TrialEngineTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
|
||||
private static readonly Guid Id = new("0b7e2c1d-5a3f-4e8b-9c6d-2f1a0e9d8c7b");
|
||||
private static readonly DateOnly First = new(2024, 1, 1);
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AnEngineThatIsNotDailyIsJudgedWithItsOwnSessionsYearFingerprintInstrumentsBenchmarkAndLimits()
|
||||
{
|
||||
var engine = new StubEngine();
|
||||
var (report, summary) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
|
||||
|
||||
Assert.AreEqual(StubFamily.FamilyId, report.Strategy);
|
||||
Assert.AreEqual("Famiglia finta", report.StrategyName);
|
||||
Assert.AreEqual("USD", report.Currency);
|
||||
Assert.AreEqual("USD", summary.Currency);
|
||||
Assert.AreEqual(StubEngine.Year, report.PeriodsPerYear);
|
||||
Assert.AreEqual(StubEngine.SessionCount, report.Sessions);
|
||||
Assert.AreEqual("stub-data", report.DataFingerprint);
|
||||
CollectionAssert.AreEqual(engine.Instruments().ToList(), report.Instruments.ToList());
|
||||
CollectionAssert.AreEqual(new[] { "Motore finto della prova." }, report.Limitations.ToList());
|
||||
|
||||
// The benchmark is the engine's own (here: stay flat), not buy and hold.
|
||||
Assert.AreEqual(0d, report.Benchmark.TotalReturn);
|
||||
Assert.IsTrue(report.Curve.All(p => p.Benchmark == StubEngine.Capital));
|
||||
|
||||
// Figures are annualised with the engine's periods per year.
|
||||
var chosen = report.Variants.Single(v => v.Chosen).Parameters;
|
||||
var expected = BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), StubEngine.Year);
|
||||
Assert.AreEqual(expected.Sharpe, report.Metrics.Sharpe);
|
||||
Assert.AreEqual(expected.AnnualReturn, report.Metrics.AnnualReturn);
|
||||
Assert.AreNotEqual(BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), 365).Sharpe, report.Metrics.Sharpe);
|
||||
|
||||
// What the engine expects and its look-ahead check reach the report as they are.
|
||||
Assert.AreEqual(7.5m, report.ExpectedSlippageBp);
|
||||
CollectionAssert.AreEqual(new[] { -0.01, -0.02 }, report.ExpectedPathP5!.ToList());
|
||||
Assert.AreEqual(42, report.LookAhead.Decisions);
|
||||
Assert.IsTrue(report.LookAhead.Passed);
|
||||
Assert.AreEqual(6, report.Variants.Count);
|
||||
Assert.IsNull(report.Baskets);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheJudgeCallsTheEngineInTheOrderOfToday()
|
||||
{
|
||||
var engine = new StubEngine();
|
||||
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
|
||||
var chosen = report.Variants.Single(v => v.Chosen).Parameters;
|
||||
string[] expected =
|
||||
[
|
||||
"run a=1;kind=0 x1", "run a=1;kind=1 x1", "run a=2;kind=0 x1", "run a=2;kind=1 x1", "run a=3;kind=0 x1", "run a=3;kind=1 x1",
|
||||
$"run {chosen} x2", $"run {chosen} x3", "benchmark", $"look_ahead {chosen} 6",
|
||||
];
|
||||
CollectionAssert.AreEqual(expected, engine.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AJudgedVariantOutsideTheGridRunsOnceMoreOnTheEngine()
|
||||
{
|
||||
var engine = new StubEngine();
|
||||
var (report, _) = TrialRunner.Run(Id, StubPlan() with { Judged = "a=4;kind=1" }, "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
|
||||
Assert.AreEqual("a=4;kind=1", report.Judged);
|
||||
Assert.AreEqual("run a=4;kind=1 x1", engine.Calls[6]);
|
||||
Assert.IsTrue(report.Variants[^1].OutsideGrid);
|
||||
Assert.AreEqual(2, report.Limitations.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheReportHasNoBasketsKeyWhenTheRunHasNone()
|
||||
{
|
||||
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine(), PriorTrials.None, Now);
|
||||
Assert.IsNull(report.Baskets);
|
||||
Assert.IsFalse(report.ToJson().Contains("\"baskets\"", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheReportCarriesTheBasketsOfTheRunWithUnitsLevelsLegsAndExitReasonAsItsLastSection()
|
||||
{
|
||||
var opened = new DateTimeOffset(2024, 3, 4, 14, 15, 0, TimeSpan.Zero);
|
||||
BacktestBasket[] baskets =
|
||||
[
|
||||
new("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, ["EURUSD", "USDCHF"], "target", 12.5m),
|
||||
new("AUDUSD", opened.AddDays(1), null, 2_000m, 1, ["AUDUSD"], null, -3.25m),
|
||||
];
|
||||
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now);
|
||||
|
||||
Assert.IsNotNull(report.Baskets);
|
||||
Assert.AreEqual(2, report.Baskets.Count);
|
||||
var first = report.Baskets[0];
|
||||
Assert.AreEqual(new ReportBasket("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, first.Legs, "target", 12.5m), first);
|
||||
CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, first.Legs.ToList());
|
||||
Assert.IsNull(report.Baskets[1].Closed);
|
||||
Assert.IsNull(report.Baskets[1].ExitReason);
|
||||
|
||||
var json = report.ToJson();
|
||||
StringAssert.Contains(json, "\"units\":1000");
|
||||
StringAssert.Contains(json, "\"levels\":3");
|
||||
StringAssert.Contains(json, "\"legs\":[\"EURUSD\",\"USDCHF\"]");
|
||||
StringAssert.Contains(json, "\"exit_reason\":\"target\"");
|
||||
Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"seconds\":", StringComparison.Ordinal), "The baskets come after every other field.");
|
||||
Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"expected_slippage_bp\":", StringComparison.Ordinal));
|
||||
Assert.IsTrue(json.EndsWith("]}", StringComparison.Ordinal));
|
||||
|
||||
var back = BacktestReport.FromJson(json);
|
||||
Assert.AreEqual(2, back.Baskets!.Count);
|
||||
CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, back.Baskets[0].Legs.ToList());
|
||||
Assert.AreEqual(json, back.ToJson());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheReportKeepsOnlyTheLastBasketsUpToTheLimitOfTheTrades()
|
||||
{
|
||||
var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero);
|
||||
var baskets = Enumerable.Range(0, TrialRunner.MaxTrades + 5)
|
||||
.Select(i => new BacktestBasket("EURUSD", opened.AddHours(i), opened.AddHours(i + 1), 1_000m, 1, ["EURUSD"], "target", i))
|
||||
.ToArray();
|
||||
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now);
|
||||
Assert.AreEqual(TrialRunner.MaxTrades, report.Baskets!.Count);
|
||||
Assert.AreEqual(5m, report.Baskets[0].Result);
|
||||
Assert.AreEqual(TrialRunner.MaxTrades + 4m, report.Baskets[^1].Result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheDailyEngineThroughTheNewOverloadGivesTheReportOfTheOldOne()
|
||||
{
|
||||
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: First));
|
||||
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
|
||||
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
|
||||
First.AddDays(60), First.AddDays(399), 10_000m, grid), Now).Plan;
|
||||
var hash = TrialPlan.Hash(plan.ToJson());
|
||||
var family = MovingAverageCrossFamily.Instance;
|
||||
|
||||
var engine = new DailyTrialEngine(plan, family, data);
|
||||
Assert.AreEqual(data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To), engine.Sessions);
|
||||
Assert.AreEqual(data.PeriodsPerYear, engine.PeriodsPerYear);
|
||||
Assert.AreEqual(data.Currency, engine.Currency);
|
||||
Assert.AreEqual(data.Fingerprint(), engine.Fingerprint());
|
||||
CollectionAssert.AreEqual(TrialRunner.Limitations(plan, family, data).ToList(), engine.Limitations().ToList());
|
||||
|
||||
var old = TrialRunner.Run(Id, plan, hash, family, data, PriorTrials.None, Now);
|
||||
var seam = TrialRunner.Run(Id, plan, hash, family, engine, PriorTrials.None, Now);
|
||||
Assert.AreEqual((old.Report with { Seconds = 0 }).ToJson(), (seam.Report with { Seconds = 0 }).ToJson());
|
||||
Assert.AreEqual(old.Summary.Chosen, seam.Summary.Chosen);
|
||||
Assert.AreEqual(old.Summary.NetResult, seam.Summary.NetResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hashes of plans built the way the laboratory and the protocols build them, recorded on commit 88b2883 before the
|
||||
/// seam: a plan written today has the same hash, so the trial ids derived from it and the recorded outcomes do not move.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public void APlanBuiltTodayHasTheHashItHadBeforeTheSeam()
|
||||
{
|
||||
var expected = new Dictionary<string, string>
|
||||
{
|
||||
[StrategyNames.CryptoTrend] = "2a30b537ecf0d6a0d94794c5d9fe97695cc912d5a1ada6ca9c10382853d7b3cb",
|
||||
["equity_momentum"] = "9555ef93f3d90ae54ede9068f4db7dc38697f283ac586de6dff324c3475f4cd7",
|
||||
["equity_meanrev"] = "5b64b09419ba153703909c81b13b9934938d6f8ba1b984fc00330980ff0e082c",
|
||||
[StrategyNames.StockAthBreakout] = "5bf77e99a0d2e4372002e9cc306cec84a98acee3804ace5dda8ab24ca90fb378",
|
||||
[StrategyNames.CryptoRelativeMomentum] = "99a85eb937c80bbe14a5113973271fc73ca3f5f7ac966321bca3a9e44204985e",
|
||||
[MovingAverageCrossFamily.FamilyId] = "952279ca4cd6193b08da61b96ecd12cac86c925a10c946099798dccb0c3326ca",
|
||||
[BuyAndHoldFamily.FamilyId] = "8266b414ea78d9ad1317ce578f23e3def2bb37bcb28a6103fae1bab6bc082a06",
|
||||
};
|
||||
var written = new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero);
|
||||
Assert.AreEqual(expected.Count, StrategyCatalog.All.Count);
|
||||
foreach (var family in StrategyCatalog.All)
|
||||
{
|
||||
var plan = Laboratory.BuildPlan(new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, ["BTCEUR", "ETHEUR"],
|
||||
CryptoTrendProtocol.From, new DateOnly(2026, 10, 31), CryptoTrendProtocol.Capital), written).Plan;
|
||||
Assert.AreEqual(expected[family.Id], TrialPlan.Hash(plan.ToJson()), family.Id);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ThePlateauRuleNeverTreatsTwoValuesOfAChoiceAxisAsNeighbours()
|
||||
{
|
||||
var variants = ParameterGrid.Of(StubFamily.Instance);
|
||||
Assert.AreEqual(6, variants.Count);
|
||||
Assert.IsTrue(variants.All(v => v.Choices is [false, true]));
|
||||
|
||||
// Grid order: a = 1, 2, 3 outside, kind = 0, 1 inside. Kind 0 is a valley on the numeric axis, kind 1 a flat hill.
|
||||
double[] values = [3, 5, 0, 5, 3, 5];
|
||||
var scores = Validation.PlateauScores(variants, values);
|
||||
|
||||
// Kind 1 is averaged only with kind 1: no score is dragged down by the other choice.
|
||||
Assert.AreEqual(5d, scores[1]);
|
||||
Assert.AreEqual(5d, scores[3]);
|
||||
Assert.AreEqual(5d, scores[5]);
|
||||
|
||||
// The numeric axis still averages one step either side: (3 + 0) / 2 at the ends, min(0, 2) in the middle.
|
||||
Assert.AreEqual(1.5, scores[0]);
|
||||
Assert.AreEqual(0d, scores[2]);
|
||||
Assert.AreEqual(1.5, scores[4]);
|
||||
Assert.AreEqual(1, Validation.ChoosePlateau(variants, values));
|
||||
|
||||
// Without the choice mark the same grid mixes the two kinds, as the numeric rule always did.
|
||||
var plain = variants.Select(v => v with { Choices = null }).ToList();
|
||||
Assert.AreEqual(3.25, Validation.PlateauScores(plain, values)[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AGridWithoutChoiceAxesMarksNoVariant()
|
||||
{
|
||||
Assert.IsTrue(ParameterGrid.Of(MovingAverageCrossFamily.Instance).All(v => v.Choices is null));
|
||||
Assert.IsTrue(StrategyCatalog.All.SelectMany(f => f.Parameters).All(p => !p.Choices));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void EveryStrategyFamilyIsAResearchFamilyAndTheCatalogStillKnowsWhoNeedsTheWholeHistory()
|
||||
{
|
||||
Assert.IsTrue(typeof(IResearchFamily).IsAssignableFrom(typeof(IStrategyFamily)));
|
||||
foreach (var family in StrategyCatalog.All)
|
||||
{
|
||||
Assert.IsInstanceOfType<IResearchFamily>(family, family.Id);
|
||||
}
|
||||
|
||||
Assert.IsTrue(StrategyCatalog.Find(StrategyNames.StockAthBreakout) is { NeedsFullHistory: true });
|
||||
Assert.IsFalse(StrategyCatalog.Find(StrategyNames.CryptoTrend) is { NeedsFullHistory: true });
|
||||
IResearchFamily research = StockAthBreakoutFamily.Instance;
|
||||
Assert.IsTrue(research.NeedsFullHistory);
|
||||
IResearchFamily cross = MovingAverageCrossFamily.Instance;
|
||||
Assert.IsFalse(cross.Accepts(new StrategyParameters([KeyValuePair.Create("fast", 50m), KeyValuePair.Create("slow", 20m)])));
|
||||
Assert.AreEqual("fast=20;slow=100", StrategyParameters.Of(cross, "fast=50;slow=20").ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AResearchFamilyWithoutStrategiesHasItsGridAndItsParameters()
|
||||
{
|
||||
Assert.AreEqual("a=2;kind=1", StrategyParameters.Of(StubFamily.Instance, "a=2;kind=1").ToString());
|
||||
Assert.AreEqual("a=2;kind=0", StrategyParameters.Of(StubFamily.Instance, null).ToString());
|
||||
Assert.AreEqual(6, ParameterGrid.Of(StubFamily.Instance).Count);
|
||||
Assert.IsFalse(typeof(IStrategyFamily).IsAssignableFrom(typeof(StubFamily)));
|
||||
}
|
||||
|
||||
private static TrialPlan StubPlan() => new(
|
||||
StubFamily.FamilyId,
|
||||
StubFamily.Instance.Version,
|
||||
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal) { ["a"] = [1m, 2m, 3m], ["kind"] = [0m, 1m] },
|
||||
new TrialData(TrialSources.Research, "dukascopy", ["EURUSD"], First, First.AddDays(StubEngine.Days - 1)),
|
||||
StubEngine.Capital,
|
||||
[1m, 2m, 3m],
|
||||
TrialValidation.Default,
|
||||
TrialThresholds.Default,
|
||||
"stub",
|
||||
Now);
|
||||
|
||||
/// <summary>A research family that cannot build a strategy: a numeric axis and a choice axis.</summary>
|
||||
private sealed class StubFamily : IResearchFamily
|
||||
{
|
||||
public const string FamilyId = "stub_baskets";
|
||||
|
||||
public static StubFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public string Name => "Famiglia finta";
|
||||
|
||||
public string Description => "Famiglia finta per provare il giunto del giudice.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("a", "Numero", 2m, [1m, 2m, 3m], 1m, 9m, Whole: true),
|
||||
new("kind", "Tipo", 0m, [0m, 1m], 0m, 1m, Whole: true) { Choices = true },
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>An engine that is not daily: it builds its runs by hand, records every call and has its own figures.</summary>
|
||||
private sealed class StubEngine : ITrialEngine
|
||||
{
|
||||
public const int Days = 320;
|
||||
public const int SessionCount = 7_680;
|
||||
public const int Year = 6_048;
|
||||
public const decimal Capital = 10_000m;
|
||||
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
public IReadOnlyList<BacktestBasket> Baskets { get; init; } = [];
|
||||
|
||||
public string Currency => "USD";
|
||||
|
||||
public int PeriodsPerYear => Year;
|
||||
|
||||
public int Sessions => SessionCount;
|
||||
|
||||
public string Fingerprint() => "stub-data";
|
||||
|
||||
public IReadOnlyList<ReportInstrument> Instruments() => [new("EURUSD", "dukascopy", First, First.AddDays(Days - 1), SessionCount, 0, "file")];
|
||||
|
||||
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
|
||||
{
|
||||
Calls.Add(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
|
||||
return Build(parameters, costMultiplier, Baskets);
|
||||
}
|
||||
|
||||
public BacktestRun Benchmark()
|
||||
{
|
||||
Calls.Add("benchmark");
|
||||
return new BacktestRun(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []);
|
||||
}
|
||||
|
||||
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
|
||||
{
|
||||
Calls.Add(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
|
||||
return new LookAheadResult([First.AddDays(100)], 42, []);
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> Limitations() => ["Motore finto della prova."];
|
||||
|
||||
public TrialExpectations Expected(BacktestRun run, double[] returns) => new(7.5m, [-0.01, -0.02]);
|
||||
|
||||
/// <summary>A noisy equity whose drift depends on the parameters; costs lower it a little each day.</summary>
|
||||
public static BacktestRun Build(StrategyParameters parameters, decimal costMultiplier, IReadOnlyList<BacktestBasket> baskets)
|
||||
{
|
||||
var a = parameters.Whole("a");
|
||||
var kind = parameters.Whole("kind");
|
||||
var gen = new Gen((a * 10) + kind);
|
||||
var drift = (0.0004 * a) - (0.0006 * kind);
|
||||
var equity = new List<EquityPoint>();
|
||||
var value = Capital;
|
||||
for (var i = 0; i < Days; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
value *= 1m + (decimal)(drift + (0.01 * gen.Normal())) - (0.0001m * (costMultiplier - 1m));
|
||||
value = Math.Round(value, 6);
|
||||
}
|
||||
|
||||
equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m));
|
||||
}
|
||||
|
||||
return new BacktestRun("USD", Capital, equity, [], [], [], []) { Baskets = baskets };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The golden reports of the trial judge (Phase 12, issue #118). They were written before the seam between the judge and the
|
||||
/// engines, so the seam must leave every byte of the report as it was. Elapsed seconds are the only field set to zero.
|
||||
/// To rewrite them on purpose: <c>ANUBIS_WRITE_GOLDEN=1</c>, then read the diff.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class TrialSeamTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
|
||||
private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12");
|
||||
private static readonly DateOnly Through = new(2026, 12, 31);
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public void TheReportOfTheAverageCrossDoesNotMove()
|
||||
{
|
||||
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03));
|
||||
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
|
||||
new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan;
|
||||
var prior = new PriorTrials(2, 18, [0.4, 0.9, -0.1]);
|
||||
var report = TrialRunner.Run(Id, plan, TrialPlan.Hash(plan.ToJson()), MovingAverageCrossFamily.Instance, data, prior, Now).Report;
|
||||
Same("sma_cross", report);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public async Task TheReportOfTheCryptoTrendProtocolDoesNotMove()
|
||||
{
|
||||
Same("crypto_trend", await CryptoTrendAsync(null).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public async Task TheReportOfAJudgedVariantOutsideTheGridDoesNotMove()
|
||||
{
|
||||
Same("crypto_trend_judged", await CryptoTrendAsync("coin_vol=12;max_stop=15").ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private static async Task<BacktestReport> CryptoTrendAsync(string? judged)
|
||||
{
|
||||
var folder = TempFolder.Create("golden-report");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(folder);
|
||||
var seed = 21u;
|
||||
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" })
|
||||
{
|
||||
var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
|
||||
(decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList();
|
||||
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var plan = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow,
|
||||
CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan with
|
||||
{ Judged = judged };
|
||||
var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false);
|
||||
return TrialRunner.Run(Id, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(StrategyNames.CryptoTrend)!, data, PriorTrials.None, Now).Report;
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Same(string name, BacktestReport report)
|
||||
{
|
||||
var json = (report with { Seconds = 0 }).ToJson();
|
||||
var relative = Path.Combine("golden", name + ".report.json");
|
||||
if (Environment.GetEnvironmentVariable("ANUBIS_WRITE_GOLDEN") == "1")
|
||||
{
|
||||
var target = Path.Combine(Repo.Root.FullName, "tests", "Anubis.Tests", "Fixtures", relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
File.WriteAllText(target, json);
|
||||
}
|
||||
|
||||
Assert.AreEqual(Fixture.Text(relative), json, $"The report of {name} changed.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user