The independent review of Phase 14 found rules the engine applied differently from the decisions, numbers the report labelled wrongly and a command that left a trial "running" when interrupted. Engine: - The pause after the 9% account stop is read at the decision moment (the bar's close), like every other gate: on daily bars it no longer blocks one day past the server date change. - In a one-pair basket, a level closed by the venue's mandatory stop closes the other levels at the next execution with their own reason, closed_with_stop (counted and labelled in the report); the basket's exit stays mandatory_stop, and a two-leg basket keeps orphan_leg. - The cap of two entries per currency applies to new baskets only, never to the averagings of an open basket, and every leg is valued at the current mid: a Prudente long basket "come dal vivo" now makes its three averagings and Fedele writes no note on them. - The surrogate of the control chains on the mid when the source has an ask, so each mid change keeps its size and the spread stays around the mid instead of moving the mid by a spread at each change of sign. - The financing already charged on positions still open at the end is part of the run's fees (BacktestRun.AccruedFees, zero for the daily engine, kept in stored unit outcomes). Report: the fee row says what it holds (commission and financing, the spread is in the prices) and the cost-stress text matches what the multiplier scales; baskets still open at the end are labelled as such and left out of the share closed at the target; refusal labels say what the engine checks; the ECB-price and cost limitations are no longer printed twice; every count has the Italian thousands separator. Command: Ctrl+C or SIGTERM cancels the run; the trial is recorded as failed with "Prova interrotta prima della fine: rilancia «anubis backtest baskets»." and the command exits 1; a trial that cannot start is failed instead of thrown, and an unexpected error ends with an Italian line, never a stack trace. The laboratory fails a leftover basket trial with an accurate message instead of "Strategia non più disponibile". The Table 6.5 test comment no longer claims each price is the only one that fits the row. The real report is regenerated on the same data and database as the first run, which now counts as a prior trial. refs #127 #129 #131 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
410 lines
22 KiB
C#
410 lines
22 KiB
C#
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using Anubis.Backtest;
|
||
using Anubis.Baskets;
|
||
using Anubis.Core;
|
||
using Anubis.Strategies;
|
||
|
||
namespace Anubis.Tests;
|
||
|
||
/// <summary>
|
||
/// The report of the basket family (Phase 14, issue #131): <c>docs/backtests/basket_reversion.md</c> is written whatever
|
||
/// the verdict, shows the 15 rows of the replica of appendix G with the binding ones counted, the control against chance,
|
||
/// the trial of the basket engine with its orphan legs counted, compares with zero and never with buy and hold, writes
|
||
/// numbers the Italian way and never names the product the research document describes.
|
||
/// </summary>
|
||
[TestClass]
|
||
public sealed class BasketReportTests
|
||
{
|
||
private const string Command = "anubis backtest baskets --to 2026-11-30";
|
||
|
||
/// <summary>SHA-256 of the lower-case name of the product the research document describes: the test never writes it.</summary>
|
||
private const string ProductNameSha256 = "9f00a2f4b75ffa8777d52da7e1a4a5a7c99929f0709b13cb0bc727003bbf9607";
|
||
|
||
private const int ProductNameLength = 6;
|
||
|
||
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 30, 0, TimeSpan.Zero);
|
||
|
||
private static readonly DateOnly First = new(2024, 1, 1);
|
||
|
||
/// <summary>The prototype's totals, positions and baskets of the 15 rows of G.4: what the replica gives on the ECB file.</summary>
|
||
private static readonly (double Total, int Positions, int Baskets)[] Ours =
|
||
[
|
||
(535.5, 1675, 1259), (543.7, 2047, 1543), (257.2, 2390, 1788),
|
||
(753.6, 1953, 1467), (1029.1, 2583, 1929), (-100.8, 2937, 2186),
|
||
(340.1, 1424, 1066), (536.3, 1641, 1223), (138.4, 1936, 1447),
|
||
(647.1, 1977, 1167), (439.5, 2702, 1590), (-47.4, 3650, 2166),
|
||
(531.3, 2133, 1273), (757.4, 3010, 1796), (169.9, 3455, 2109),
|
||
];
|
||
|
||
private static readonly Lazy<BasketTrialSection> _trial = new(BuildTrial);
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheReportIsWrittenWhateverTheVerdict()
|
||
{
|
||
var trial = _trial.Value;
|
||
var passed = BasketReport.Markdown(Input(trial with { Report = trial.Report with { Passed = true } }));
|
||
var failedReport = trial.Report with
|
||
{
|
||
Passed = false,
|
||
Checks = [.. trial.Report.Checks.Select(c => c.Key == ReportCheckKeys.Drawdown ? c with { Value = 0.38, Passed = false } : c)],
|
||
};
|
||
var failed = BasketReport.Markdown(Input(trial with { Report = failedReport }));
|
||
var waiting = BasketReport.Markdown(Input(null, "Mancano i cambi della BCE: la prova del motore non è partita."));
|
||
|
||
foreach (var text in new[] { passed, failed, waiting })
|
||
{
|
||
Assert.IsTrue(text.StartsWith("# Backtest di `basket_reversion` (Rientro tra strumenti)" + Environment.NewLine, StringComparison.Ordinal), text[..80]);
|
||
StringAssert.Contains(text, "Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).");
|
||
StringAssert.Contains(text, "Per rifarlo: `" + Command + "`");
|
||
StringAssert.Contains(text, "## Dati");
|
||
StringAssert.Contains(text, "## Replica dell'appendice G");
|
||
StringAssert.Contains(text, "## Controllo contro il caso (G.5)");
|
||
StringAssert.Contains(text, "## Cosa il backtest non rappresenta");
|
||
Assert.IsFalse(text.Contains("outcome.json", StringComparison.Ordinal), "No outcome file for baskets in this phase.");
|
||
Assert.IsFalse(text.Contains("letto dal bot", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Dati", StringComparison.Ordinal) < text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal) < text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal));
|
||
Assert.IsTrue(text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal) < text.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
|
||
}
|
||
|
||
StringAssert.Contains(passed, "**Esito: superato.**");
|
||
StringAssert.Contains(passed, "## Prova del motore a panieri");
|
||
StringAssert.Contains(passed, "versione basket-1 del motore a panieri");
|
||
StringAssert.Contains(passed, "«come dal vivo»");
|
||
StringAssert.Contains(passed, "Motore finto della prova.");
|
||
Assert.IsTrue(passed.IndexOf("## Prova del motore a panieri", StringComparison.Ordinal) < passed.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
|
||
|
||
StringAssert.Contains(failed, "**Esito: non superato.**");
|
||
StringAssert.Contains(failed, "calo massimo 38,0%");
|
||
StringAssert.Contains(failed, "**non superato**");
|
||
|
||
StringAssert.Contains(waiting, "**Esito: in attesa.** Mancano i cambi della BCE: la prova del motore non è partita.");
|
||
Assert.IsFalse(waiting.Contains("## Prova del motore a panieri", StringComparison.Ordinal));
|
||
StringAssert.Contains(waiting, "file a 1 minuto");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheReplicaTableShowsEveryRowAndCountsTheBindingOnes()
|
||
{
|
||
var text = BasketReport.Markdown(Input(null, "Nessuna prova."));
|
||
var replica = Section(text, "## Replica dell'appendice G");
|
||
|
||
StringAssert.Contains(replica, "| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |");
|
||
foreach (var c in ReplicaSettings.DocumentCases)
|
||
{
|
||
var row = "| " + c.Label + " | " + c.StopLabel + " |";
|
||
Assert.AreEqual(2, Count(replica, row), row + " in the totals and in the break-even table.");
|
||
}
|
||
|
||
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 535,5 | +1,5 | ±26,7 | sì | dentro |");
|
||
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 90 obiettivi | 1.032 | 1.029,1 | −2,9 | ±51,6 | sì | dentro |");
|
||
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 30 obiettivi | −98 | −100,8 | −2,8 | ±25 | no | solo riportata |");
|
||
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | +0,32 | +0,32 | 1.675 | 1.259 | ");
|
||
StringAssert.Contains(replica, "13 righe vincolanti su 13 dentro la tolleranza.");
|
||
StringAssert.Contains(replica, "2 σ · 8 σ · 3 con stop di 30 obiettivi");
|
||
StringAssert.Contains(replica, "2,5 σ · 4 σ · 3 con stop di 30 obiettivi");
|
||
StringAssert.Contains(replica, "mai giudicata");
|
||
|
||
var rows = ReplicaRows();
|
||
rows[0] = rows[0] with { Result = rows[0].Result with { Total = 400 } };
|
||
var off = Section(BasketReport.Markdown(Input(null, "Nessuna prova.") with { Replica = rows }), "## Replica dell'appendice G");
|
||
StringAssert.Contains(off, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 400 | −134 | ±26,7 | sì | **fuori** |");
|
||
StringAssert.Contains(off, "12 righe vincolanti su 13 dentro la tolleranza.");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void OrphanLegsAreCountedInTheReport()
|
||
{
|
||
var trial = _trial.Value;
|
||
var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero);
|
||
ReportBasket[] baskets =
|
||
[
|
||
new("EURUSD-USDCHF", opened, opened.AddDays(3), 1_000m, 2, ["EURUSD", "USDCHF"], "mandatory_stop", -40m),
|
||
new("EURUSD-USDCHF", opened.AddDays(3), opened.AddDays(4), 1_000m, 2, ["EURUSD", "USDCHF"], "orphan_leg", -12m),
|
||
new("AUDNZD", opened.AddDays(5), opened.AddDays(9), 1_000m, 1, ["AUDNZD"], "target", 9m),
|
||
new("AUDNZD", opened.AddDays(10), opened.AddDays(12), 1_000m, 1, ["AUDNZD"], "target", 8m),
|
||
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], BasketReasons.End, -3m),
|
||
];
|
||
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
|
||
{
|
||
["orphan_leg"] = 2,
|
||
["closed_with_stop"] = 3,
|
||
["gate_open_loss"] = 5,
|
||
["weird_code"] = 1,
|
||
};
|
||
var two = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes, Baskets = baskets } })), "## Prova del motore a panieri");
|
||
StringAssert.Contains(two, "Gambe rimaste sole: 2");
|
||
StringAssert.Contains(two, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 3 (");
|
||
StringAssert.Contains(two, "| stop obbligatorio della piattaforma | 1 |");
|
||
StringAssert.Contains(two, "| gamba rimasta sola dopo uno stop obbligatorio | 1 |");
|
||
StringAssert.Contains(two, "| obiettivo raggiunto | 2 |");
|
||
StringAssert.Contains(two, "| ancora aperto alla fine (valutato agli ultimi prezzi) | 1 |");
|
||
StringAssert.Contains(two, "Panieri della variante giudicata: 5.");
|
||
StringAssert.Contains(two, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 5 |");
|
||
StringAssert.Contains(two, "| `weird_code` | 1 |");
|
||
Assert.IsFalse(two.Contains("`closed_with_stop`", StringComparison.Ordinal), "closes, not refusals");
|
||
Assert.IsFalse(two.Contains("fine del periodo", StringComparison.Ordinal), "a basket open at the end was not closed");
|
||
|
||
// Two at the target out of the four closed: the one still open at the end is not counted among the closed.
|
||
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0% dei panieri chiusi");
|
||
|
||
var none = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = new Dictionary<string, int>(), Baskets = [] } })), "## Prova del motore a panieri");
|
||
StringAssert.Contains(none, "Gambe rimaste sole: 0");
|
||
StringAssert.Contains(none, "Chiusure d'ufficio per margine insufficiente: 0");
|
||
StringAssert.Contains(none, "Stop sul valore del conto: 0");
|
||
StringAssert.Contains(none, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 0 (");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheLimitsAreWrittenOnce()
|
||
{
|
||
// With a trial, the engine's own limitations already speak of the ECB prices and of the costs: the report does not
|
||
// repeat its own version of them. Without one, it writes them.
|
||
const string Prices = "- I prezzi sono i cambi di riferimento della BCE, uno al giorno";
|
||
const string Costs = "- I costi sono quelli di eToro letti il 02/12/2026";
|
||
var withTrial = Section(BasketReport.Markdown(Input(_trial.Value)), "## Cosa il backtest non rappresenta");
|
||
var without = Section(BasketReport.Markdown(Input(null, "Nessuna prova.")), "## Cosa il backtest non rappresenta");
|
||
|
||
StringAssert.Contains(withTrial, "- Motore finto della prova.");
|
||
Assert.AreEqual(0, Count(withTrial, Prices), withTrial);
|
||
Assert.AreEqual(0, Count(withTrial, Costs), withTrial);
|
||
Assert.AreEqual(1, Count(without, Prices), without);
|
||
Assert.AreEqual(1, Count(without, Costs), without);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void EveryCodeOfTheEngineHasAnItalianLabel()
|
||
{
|
||
var trial = _trial.Value;
|
||
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
|
||
{
|
||
[BasketReasons.PositionLimit] = 3,
|
||
[BasketReasons.ClockWindow] = 4,
|
||
[BasketReasons.MandatoryStop] = 6,
|
||
[BasketReasons.GateOpenLoss] = 1,
|
||
[BasketReasons.PausedUntilNextDay] = 1,
|
||
[BasketReasons.DailyLossBlock] = 1,
|
||
[BasketReasons.HalfSize] = 1,
|
||
[BasketReasons.BelowVenueMinimum] = 1,
|
||
[BasketReasons.MarginLimit] = 1,
|
||
[BasketReasons.OppositePosition] = 1,
|
||
[BasketReasons.CurrencyExposure] = 1,
|
||
[BasketReasons.CostRule] = 1,
|
||
[BasketReasons.RvolFilter] = 1,
|
||
[BasketReasons.CorrelationLow] = 1,
|
||
[BasketReasons.SwitchTripped] = 1,
|
||
[BasketReasons.MaxOpenBaskets] = 1_569,
|
||
};
|
||
var report = trial.Report with
|
||
{
|
||
Notes = notes,
|
||
LookAhead = trial.Report.LookAhead with { Decisions = 4_817 },
|
||
Overfitting = new ReportOverfitting(16, 12_870, 4, 0.25),
|
||
};
|
||
var text = Section(BasketReport.Markdown(Input(trial with { Report = report })), "## Prova del motore a panieri");
|
||
|
||
// Each label says what the engine does (BasketSimulation, ReasonCatalog).
|
||
StringAssert.Contains(text, "| si supererebbero 9 posizioni aperte (conto Demo condiviso) | 3 |");
|
||
StringAssert.Contains(text, "| fuori dalla finestra oraria | 4 |");
|
||
StringAssert.Contains(text, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 1 |");
|
||
StringAssert.Contains(text, "| volatilità recente oltre il doppio del normale, o non ancora nota | 1 |");
|
||
StringAssert.Contains(text, "| perdita del giorno pari o oltre il 2%: niente ingressi né mediazioni per 24 ore | 1 |");
|
||
StringAssert.Contains(text, "| correlazione tra le gambe sotto 0,6 sul segno atteso, o non ancora nota | 1 |");
|
||
StringAssert.Contains(text, "| esposizione netta su una valuta oltre due ingressi (solo panieri nuovi) | 1 |");
|
||
StringAssert.Contains(text, "| dimensione ridotta a metà o a un quarto (perdita della settimana o calo dal massimo) | 1 |");
|
||
StringAssert.Contains(text, "Posizioni chiuse dallo stop obbligatorio della piattaforma: 6.");
|
||
var refusals = text[text.IndexOf("**Ingressi e mediazioni fermati o annotati**", StringComparison.Ordinal)..];
|
||
Assert.IsFalse(refusals.Contains('`', StringComparison.Ordinal), "a code without a label: " + refusals);
|
||
|
||
// Counts are grouped the Italian way, like every other number of the report.
|
||
StringAssert.Contains(text, "| già aperto il numero massimo di panieri | 1.569 |");
|
||
StringAssert.Contains(text, "4.817 decisioni");
|
||
StringAssert.Contains(text, "su 12.870 combinazioni");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheComparisonIsZeroNeverBuyAndHold()
|
||
{
|
||
var text = BasketReport.Markdown(Input(_trial.Value));
|
||
StringAssert.Contains(text, "| | Strategia | Zero (nessuna operazione) |");
|
||
StringAssert.Contains(text, "zero (nessuna operazione)");
|
||
Assert.IsFalse(text.Contains("comprare e tenere", StringComparison.OrdinalIgnoreCase));
|
||
Assert.IsFalse(text.Contains("buy and hold", StringComparison.OrdinalIgnoreCase));
|
||
StringAssert.Contains(text, "**Sensibilità ai costi** (differenziale, commissioni e finanziamento a carico moltiplicati insieme; gli accrediti di finanziamento restano uguali)");
|
||
StringAssert.Contains(text, "| Commissioni e finanziamento pagati (il differenziale è già nei prezzi) | ");
|
||
Assert.IsFalse(text.Contains("| Costi pagati |", StringComparison.Ordinal));
|
||
StringAssert.Contains(text, "| ×2 |");
|
||
StringAssert.Contains(text, "| ×3 |");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void NumbersAreItalianAndTheProductIsNeverNamed()
|
||
{
|
||
var texts = new[]
|
||
{
|
||
BasketReport.Markdown(Input(_trial.Value)),
|
||
BasketReport.Markdown(Input(null, "Nessuna prova.")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketReport.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketProtocol.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "BasketCommand.cs")),
|
||
File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "backtests", "basket_reversion.md")),
|
||
};
|
||
var text = texts[0];
|
||
StringAssert.Contains(text, "535,5");
|
||
StringAssert.Contains(text, "−100,8");
|
||
Assert.IsFalse(text.Contains("535.5", StringComparison.Ordinal));
|
||
Assert.IsFalse(text.Contains("-100,8", StringComparison.Ordinal), "The minus is U+2212, as in the other reports.");
|
||
StringAssert.Contains(text, "1.000 USD");
|
||
StringAssert.Contains(text, "0,005%");
|
||
StringAssert.Contains(text, "dal 04/01/1999 al 02/12/2026");
|
||
StringAssert.Contains(text, "`f298c1dcc4be`");
|
||
StringAssert.Contains(text, "| 2,5 σ · 10 σ · 3 | nessuno | 150 | 20261202 | +0,32 | ");
|
||
StringAssert.Contains(text, " | 35,0% | 37% |");
|
||
|
||
foreach (var t in texts)
|
||
{
|
||
var lower = t.ToLowerInvariant();
|
||
for (var i = 0; i + ProductNameLength <= lower.Length; i++)
|
||
{
|
||
var window = lower.AsSpan(i, ProductNameLength);
|
||
if (!char.IsLetter(window[0]))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(window.ToString())));
|
||
Assert.AreNotEqual(ProductNameSha256, hash, "The report names the product the research document describes, at " + i + ".");
|
||
}
|
||
}
|
||
}
|
||
|
||
private static BasketReportInput Input(BasketTrialSection? trial, string? missing = null) => new(
|
||
Command,
|
||
Now,
|
||
new BasketDataNotes("Banca centrale europea, cambi di riferimento (eurofxref-hist)", "f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8",
|
||
new DateOnly(1999, 1, 4), new DateOnly(2026, 12, 2), 7_149, 28, new DateOnly(2026, 12, 2)),
|
||
VenueCosts.Etoro,
|
||
ReplicaRows(),
|
||
ControlRows(),
|
||
trial,
|
||
missing);
|
||
|
||
private static List<BasketReplicaRow> ReplicaRows() =>
|
||
[.. ReplicaSettings.DocumentCases.Select((c, i) => new BasketReplicaRow(c, new ReplicaResult(Ours[i].Total, Ours[i].Positions, Ours[i].Baskets, (int)(Ours[i].Baskets * 0.97), 0, [])))];
|
||
|
||
private static List<BasketControlRow> ControlRows()
|
||
{
|
||
var replicas = Enumerable.Range(0, 150).Select(i => -1.8 + (2.7 * i / 149.0)).ToArray();
|
||
return [.. BasketReport.DocumentControl.Select(d => new BasketControlRow(d.Case, new ReplicaControl(0.32, replicas, 0.35), 150, 20_261_202, d.Share))];
|
||
}
|
||
|
||
private static string Section(string text, string heading)
|
||
{
|
||
var start = text.IndexOf(heading, StringComparison.Ordinal);
|
||
Assert.IsTrue(start >= 0, heading);
|
||
var end = text.IndexOf("\n## ", start + heading.Length, StringComparison.Ordinal);
|
||
return end < 0 ? text[start..] : text[start..end];
|
||
}
|
||
|
||
private static int Count(string text, string part)
|
||
{
|
||
var count = 0;
|
||
for (var i = text.IndexOf(part, StringComparison.Ordinal); i >= 0; i = text.IndexOf(part, i + part.Length, StringComparison.Ordinal))
|
||
{
|
||
count++;
|
||
}
|
||
|
||
return count;
|
||
}
|
||
|
||
private static BasketTrialSection BuildTrial()
|
||
{
|
||
var plan = new TrialPlan(
|
||
"basket_reversion",
|
||
"1",
|
||
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal) { ["target"] = [2m, 2.5m, 3m] },
|
||
new TrialData(TrialSources.Research, "ecb", ["EURUSD", "USDCHF", "AUDNZD"], First, First.AddDays(StubEngine.Days - 1)),
|
||
StubEngine.Capital,
|
||
[1m, 2m, 3m],
|
||
TrialValidation.Default,
|
||
TrialThresholds.Default,
|
||
"basket-1",
|
||
Now);
|
||
var hash = TrialPlan.Hash(plan.ToJson());
|
||
var (report, _) = TrialRunner.Run(new Guid("6a1f0c3e-2b7d-4e59-8c1a-9d3e5f7a0b2c"), plan, hash, StubFamily.Instance, new StubEngine(), PriorTrials.None, Now);
|
||
return new BasketTrialSection("Le 28 coppie della BCE, generazione B in σ", plan, hash, report, BasketReport.LikeLive);
|
||
}
|
||
|
||
/// <summary>A research family with one numeric axis, under the basket family's id.</summary>
|
||
private sealed class StubFamily : IResearchFamily
|
||
{
|
||
public static StubFamily Instance { get; } = new();
|
||
|
||
public string Id => "basket_reversion";
|
||
|
||
public string Version => "1";
|
||
|
||
public string Name => "Rientro tra strumenti";
|
||
|
||
public string Description => "Famiglia finta per provare il rapporto dei panieri.";
|
||
|
||
public IReadOnlyList<ParameterSpec> Parameters => [new("target", "Obiettivo", 2.5m, [2m, 2.5m, 3m], 1m, 5m)];
|
||
}
|
||
|
||
/// <summary>An engine with a flat benchmark (zero) and a noisy equity that depends on the target.</summary>
|
||
private sealed class StubEngine : ITrialEngine
|
||
{
|
||
public const int Days = 320;
|
||
public const decimal Capital = 20_000m;
|
||
|
||
public string Currency => "USD";
|
||
|
||
public bool LongOnly => false;
|
||
|
||
public int PeriodsPerYear => 260;
|
||
|
||
public int Sessions => Days;
|
||
|
||
public string Fingerprint() => "f298c1dcc4be41a4|basket:basket-1";
|
||
|
||
public IReadOnlyList<ReportInstrument> Instruments() => [new("EURUSD", "ecb", First, First.AddDays(Days - 1), Days, 0, "file")];
|
||
|
||
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
|
||
{
|
||
var target = (double)parameters["target"];
|
||
var random = new SeededRandom((int)(target * 10));
|
||
var equity = new List<EquityPoint>();
|
||
var value = Capital;
|
||
for (var i = 0; i < Days; i++)
|
||
{
|
||
if (i > 0)
|
||
{
|
||
value *= 1m + (decimal)((0.0002 * target) + (0.006 * random.Normal())) - (0.0001m * (costMultiplier - 1m));
|
||
value = Math.Round(value, 6);
|
||
}
|
||
|
||
equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m));
|
||
}
|
||
|
||
return new BacktestRun(Currency, Capital, equity, [], [], [], []);
|
||
}
|
||
|
||
public BacktestRun Benchmark() =>
|
||
new(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []);
|
||
|
||
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => new([First.AddDays(100)], 12, []);
|
||
|
||
public IReadOnlyList<string> Limitations() => ["Motore finto della prova."];
|
||
|
||
public TrialExpectations Expected(BacktestRun run, double[] returns) => new(null, null);
|
||
}
|
||
}
|