diff --git a/src/Anubis/Backtest/BasketReport.cs b/src/Anubis/Backtest/BasketReport.cs new file mode 100644 index 0000000..6f360ba --- /dev/null +++ b/src/Anubis/Backtest/BasketReport.cs @@ -0,0 +1,492 @@ +using System.Globalization; +using System.Text; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Backtest; + +/// Where the data of the basket report come from: the ECB file, its fingerprint, its period and the replica's cut. +/// The source, in Italian, as the report shows it. +/// SHA-256 of the data (the report shows the first 12 characters). +/// The first day with a fixing. +/// The last day with a fixing. +/// The days with a fixing. +/// The crosses built from the rates. +/// The last day the replica of appendix G uses: the end of the research document. +public sealed record BasketDataNotes(string Source, string Fingerprint, DateOnly First, DateOnly Last, int Days, int Pairs, DateOnly ReplicaThrough); + +/// One row of table G.4 and what the replica gave on it. +public sealed record BasketReplicaRow(ReplicaCase Case, ReplicaResult Result); + +/// One row of the control against chance (G.5): our control, how it ran, and the document's share «pari o migliori». +public sealed record BasketControlRow(ReplicaCase Case, ReplicaControl Control, int Repetitions, int Seed, double DocumentShare); + +/// A row of the document's table G.5 for «Forex 1999–2026»: the case, its observed break-even, its share and repetitions. +public sealed record BasketDocumentControl(ReplicaCase Case, double Observed, double Share, int Repetitions); + +/// The trial of the basket engine shown in the report: its name, plan, plan hash, report and mode. +/// or . +public sealed record BasketTrialSection(string Name, TrialPlan Plan, string PlanHash, BacktestReport Report, string Mode); + +/// +/// Everything the basket report shows. is null when the trial of the engine did not run, and +/// then says why, in Italian. +/// +public sealed record BasketReportInput( + string Command, + DateTimeOffset ComputedAt, + BasketDataNotes Data, + VenueCosts Costs, + IReadOnlyList Replica, + IReadOnlyList Control, + BasketTrialSection? Trial, + string? TrialMissing); + +/// +/// The report of the basket family, docs/backtests/basket_reversion.md (Phase 14, issue #131), in plain Italian and +/// written whatever the verdict: the data and the costs, the replica of appendix G of the research document against its +/// 15 totals, the control against chance of G.5, the trial of the basket engine with its baskets, exit reasons, orphan legs +/// and refusals, and what the backtest does not model. The comparison is zero, no trading at all (ADR 0026 point 5), never +/// buy and hold; the share of baskets closed at the target is shown and never judged. The family only does research: there +/// is no outcome file for it in this phase. +/// +public static class BasketReport +{ + /// The trial-registry id of the family (ADR 0026 point 10). + public const string Strategy = "basket_reversion"; + + public const string ReportPath = "docs/backtests/" + Strategy + ".md"; + + /// The mode with the account limits of the bot: the one that gives verdicts (ADR 0026). + public const string LikeLive = "come_dal_vivo"; + + /// The mode with the document's rules only: replication and experiments, no verdict. + public const string ToTheLetter = "alla_lettera"; + + /// Note reason of a leg left alone when a mandatory stop closed the other one. + public const string OrphanLeg = "orphan_leg"; + + /// Note reason of a liquidation for want of margin. + public const string Liquidation = "liquidation"; + + /// Note reason of the 9% stop on the account value. + public const string AccountStop = "account_stop"; + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + /// The exits of a basket, in the order the report lists them, with their Italian labels. + private static readonly (string Code, string Label)[] Exits = + [ + ("target", "obiettivo raggiunto"), + ("stop_basket", "stop del paniere"), + (AccountStop, "stop sul valore del conto (9%)"), + ("mandatory_stop", "stop obbligatorio della piattaforma"), + (OrphanLeg, "gamba rimasta sola dopo uno stop obbligatorio"), + (Liquidation, "chiusura d'ufficio per margine insufficiente"), + ("end", "fine del periodo"), + ]; + + /// Why the engine did not open or add, with their Italian labels. + private static readonly Dictionary Refusals = new(StringComparer.Ordinal) + { + ["gate_open_loss"] = "perdita aperta oltre il 2%: nessun paniere nuovo", + ["paused_until_next_day"] = "fermo dopo lo stop del 9% fino al cambio di data del server", + ["daily_loss_block"] = "perdita del giorno oltre il 2%: niente ingressi né mediazioni per 24 ore", + ["half_size"] = "dimensione dimezzata (perdita della settimana o calo dal massimo)", + ["below_venue_minimum"] = "livello sotto il minimo della piattaforma", + ["margin_limit"] = "margine impegnato oltre il 40%", + ["position_limit"] = "troppe posizioni aperte", + ["opposite_position"] = "posizione opposta sullo stesso strumento", + ["currency_exposure"] = "esposizione su una valuta oltre il limite", + ["cost_rule"] = "obiettivo sotto tre volte il costo del paniere", + ["rvol_filter"] = "volatilità recente oltre il doppio del normale", + ["correlation_low"] = "correlazione sotto 0,6", + ["switch_tripped"] = "interruttore scattato (calo del 15%)", + ["max_open_baskets"] = "già aperto il numero massimo di panieri", + }; + + /// + /// The four «Forex 1999–2026» rows of table G.5: 2,5·10·3 and 2,5·4·3, without stop and with a stop of 90 targets; the + /// observed break-even per position, the share of shuffled series equal or better, 150 repetitions each. + /// + public static IReadOnlyList DocumentControl { get; } = Array.AsReadOnly( + [ + new BasketDocumentControl(ReplicaSettings.DocumentCases[0], 0.32, 0.37, 150), + new BasketDocumentControl(ReplicaSettings.DocumentCases[1], 0.26, 0.33, 150), + new BasketDocumentControl(ReplicaSettings.DocumentCases[9], 0.33, 0.33, 150), + new BasketDocumentControl(ReplicaSettings.DocumentCases[10], 0.16, 0.32, 150), + ]); + + /// The Markdown of the report. + public static string Markdown(BasketReportInput input) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(input.Data); + ArgumentNullException.ThrowIfNull(input.Costs); + ArgumentNullException.ThrowIfNull(input.Replica); + ArgumentNullException.ThrowIfNull(input.Control); + var b = new StringBuilder(); + var trial = input.Trial; + b.Append("# Backtest di `").Append(Strategy).AppendLine("` (Rientro tra strumenti)").AppendLine(); + if (trial is null) + { + b.Append("**Esito: in attesa.** ").AppendLine(input.TrialMissing ?? "La prova del motore a panieri non è stata fatta."); + } + else + { + b.Append("**Esito: ").Append(trial.Report.Passed ? "superato" : "non superato").Append(".** ").AppendLine(Verdict(trial)); + } + + b.AppendLine().AppendLine("Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).").AppendLine(); + b.AppendLine(trial is null + ? Text($"Calcolato il {input.ComputedAt:yyyy-MM-dd}: replica e controllo contro il caso, senza la prova del motore a panieri.") + : Text($"Calcolato il {input.ComputedAt:yyyy-MM-dd} con la versione {trial.Plan.Engine} del motore a panieri e la versione {trial.Plan.StrategyVersion} della famiglia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.")) + .AppendLine(); + b.Append("Per rifarlo: `").Append(input.Command).AppendLine("`.").AppendLine(); + + DataSection(b, input); + ReplicaSection(b, input); + ControlSection(b, input); + if (trial is not null) + { + TrialSection(b, trial, input.Costs); + } + + LimitsSection(b, input); + return b.ToString(); + } + + private static string Verdict(BasketTrialSection trial) + { + var mode = ModeName(trial.Mode); + if (trial.Report.Passed) + { + return $"La prova {mode} supera tutte le soglie fissate prima del calcolo."; + } + + var failed = trial.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, trial.Report.Currency)).ToList(); + return failed.Count == 0 + ? $"La prova {mode} non supera le soglie fissate prima del calcolo." + : $"La prova {mode} non supera: {string.Join("; ", failed)}."; + } + + private static void DataSection(StringBuilder b, BasketReportInput input) + { + var d = input.Data; + var c = input.Costs; + b.AppendLine("## Dati").AppendLine(); + b.AppendLine(Text($"- Cambi di riferimento della BCE: {EcbCrosses.Rates.Count} valute contro l'euro ({string.Join(", ", EcbCrosses.Rates)}), da cui {d.Pairs} coppie incrociate. Fonte: {d.Source}.")); + b.AppendLine(Text($"- Periodo: dal {d.First:dd/MM/yyyy} al {d.Last:dd/MM/yyyy}, {d.Days.ToString("#,0", It)} giorni con il cambio. Impronta dei dati `{Short(d.Fingerprint)}`.")); + b.AppendLine(d.Last < d.ReplicaThrough + ? Text($"- La replica dell'appendice G usa i dati fino al {d.ReplicaThrough:dd/MM/yyyy}, la fine del documento; qui i dati finiscono prima, il {d.Last:dd/MM/yyyy}.") + : Text($"- La replica dell'appendice G usa i dati fino al {d.ReplicaThrough:dd/MM/yyyy}, la fine del documento.")); + b.AppendLine("- I cambi della BCE sono prezzi di riferimento, uno al giorno: non sono prezzi a cui si possa comprare o vendere. La prova decide sul cambio di oggi ed esegue su quello di domani, con il differenziale della tabella dei costi."); + b.AppendLine(Text($"- Costi: {VenueName(c.Venue)}, letti il {c.AsOf:dd/MM/yyyy}. Fonte: {c.Source}")); + b.AppendLine(Text($"- Minimo {Amount(c.MinimumUsd)} USD per posizione, leva {c.DefaultLeverage} per posizione, mai oltre quella del conto reale.")); + var estimated = c.Pairs.Where(p => p.FinancingEstimated).Select(p => p.Pair).ToList(); + if (estimated.Count > 0) + { + b.AppendLine(Text($"- Il finanziamento notturno di {estimated.Count} coppie su {c.Pairs.Count} non è nel documento: per prudenza pagano, su entrambi i lati, il costo più alto tra quelli noti. Sono segnate come stimate nella tabella.")); + } + + b.AppendLine(); + b.AppendLine("**Tabella dei costi** (differenziale in pip; finanziamento in USD per 100.000 USD di esposizione a notte, positivo se si paga)").AppendLine(); + b.AppendLine("| Coppia | Differenziale | In pausa | Leva massima | Commissione per lato | Finanziamento acquisto | Finanziamento vendita | Finanziamento |"); + b.AppendLine("|---|---:|---:|---:|---:|---:|---:|---|"); + foreach (var p in c.Pairs) + { + b.AppendLine(Text($"| {p.Pair} | {Amount(p.Spread)} | {Amount(p.PauseSpread)} | {p.MaxLeverage} | {Amount(p.CommissionPerSide * 100m)}% | {Signed(p.FinancingBuy)} | {Signed(p.FinancingSell)} | {(p.FinancingEstimated ? "stimato" : "dal documento")} |")); + } + + b.AppendLine(); + } + + private static void ReplicaSection(StringBuilder b, BasketReportInput input) + { + b.AppendLine("## Replica dell'appendice G").AppendLine(); + b.AppendLine("La replica segue alla lettera il metodo G.3 del documento di ricerca: ognuna delle coppie da sola, sui logaritmi dei prezzi, ingresso e uscita sulla stessa chiusura, nessun costo e nessuna regola del conto. Non è il motore a panieri e non dà nessun giudizio: dice solo se i numeri del documento si ritrovano sugli stessi dati. I risultati sono in obiettivi (un obiettivo è la distanza del take profit).") + .AppendLine(); + if (input.Replica.Count == 0) + { + b.AppendLine("Non calcolata in questa esecuzione.").AppendLine(); + return; + } + + b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |"); + b.AppendLine("|---|---|---:|---:|---:|---:|---|---|"); + foreach (var (c, r) in input.Replica) + { + var outcome = !c.Binding ? "solo riportata" : c.Passes(r.Total) ? "dentro" : "**fuori**"; + b.AppendLine(Text($"| {c.Label} | {c.StopLabel} | {Targets(c.DocumentTotal)} | {Targets(r.Total)} | {SignedTargets(r.Total - c.DocumentTotal)} | ±{Targets(c.Tolerance)} | {(c.Binding ? "sì" : "no")} | {outcome} |")); + } + + var binding = input.Replica.Where(r => r.Case.Binding).ToList(); + var inside = binding.Count(r => r.Case.Passes(r.Result.Total)); + b.AppendLine(); + b.AppendLine(Text($"{inside} righe vincolanti su {binding.Count} dentro la tolleranza. Una riga è vincolante quando il totale del documento supera 100 obiettivi in valore assoluto: allora il nostro deve avere lo stesso segno e restare entro il più grande tra 25 obiettivi e il 5% del totale del documento.")); + var reported = input.Replica.Where(r => !r.Case.Binding).ToList(); + if (reported.Count > 0) + { + b.AppendLine(); + b.AppendLine("Solo riportate, perché vicine allo zero: " + string.Join("; ", reported.Select(r => + Text($"{r.Case.Label} {StopWords(r.Case.StopLabel)}, documento {Targets(r.Case.DocumentTotal)}, Anubis {Targets(r.Result.Total)} ({(Math.Sign(r.Result.Total) == Math.Sign(r.Case.DocumentTotal) ? "stesso segno" : "segno diverso")})"))) + "."); + } + + b.AppendLine(); + b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Pareggio del documento | Pareggio di Anubis | Posizioni | Panieri | Chiusi all'obiettivo |"); + b.AppendLine("|---|---|---:|---:|---:|---:|---:|"); + foreach (var (c, r) in input.Replica) + { + b.AppendLine(Text($"| {c.Label} | {c.StopLabel} | {Ratio(c.DocumentBreakEven)} | {Ratio(r.BreakEven)} | {r.Positions.ToString("#,0", It)} | {r.Baskets.ToString("#,0", It)} | {Share(r.AtTargetShare)} |")); + } + + b.AppendLine(); + b.AppendLine("Il pareggio è il costo per posizione, in obiettivi, che porterebbe il totale a zero: totale diviso posizioni. La quota di panieri chiusi all'obiettivo è mostrata e mai giudicata: alta com'è, non prova nulla sul guadagno.") + .AppendLine(); + } + + private static void ControlSection(StringBuilder b, BasketReportInput input) + { + b.AppendLine("## Controllo contro il caso (G.5)").AppendLine(); + b.AppendLine("Ogni giorno le variazioni di tutte le coppie cambiano segno insieme con probabilità un mezzo: restano volatilità, code e legami tra le coppie, sparisce ogni tendenza a rientrare o a proseguire. Poi la replica gira di nuovo sulle serie ricostruite. Si conta quante volte il pareggio delle serie rimescolate è pari o migliore di quello osservato.") + .AppendLine(); + if (input.Control.Count == 0) + { + b.AppendLine("Non calcolato in questa esecuzione.").AppendLine(); + return; + } + + b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Ripetizioni | Seme | Pareggio osservato | Mediana rimescolate | 5°–95° percentile | Pari o migliori: Anubis | Pari o migliori: documento |"); + b.AppendLine("|---|---|---:|---:|---:|---:|---:|---:|---:|"); + foreach (var row in input.Control) + { + var replicas = row.Control.Replicas.Where(double.IsFinite).Order().ToArray(); + var spread = replicas.Length == 0 ? "—" : Ratio(Rank(replicas, 0.05)) + "; " + Ratio(Rank(replicas, 0.95)); + b.AppendLine(Text($"| {row.Case.Label} | {row.Case.StopLabel} | {row.Repetitions} | {row.Seed.ToString(CultureInfo.InvariantCulture)} | {Ratio(row.Control.Observed)} | {Ratio(Median(replicas))} | {spread} | {Share(row.Control.Share)} | {Pct(row.DocumentShare, 0)} |")); + } + + b.AppendLine(); + b.AppendLine("Una quota alta vuol dire che il risultato osservato è uno dei tanti che il caso produce da solo. Il documento ha fatto 150 ripetizioni per riga, senza dire il seme.") + .AppendLine(); + } + + private static void TrialSection(StringBuilder b, BasketTrialSection trial, VenueCosts costs) + { + var r = trial.Report; + var m = r.Metrics; + var h = r.Benchmark; + var annual = Math.Sqrt(r.PeriodsPerYear); + b.AppendLine("## Prova del motore a panieri").AppendLine(); + b.AppendLine(Text($"{trial.Name}. Modo {ModeName(trial.Mode)}: le regole del documento più i limiti del bot (SPEC 9.2) e quelli del margine; solo questo modo dà un giudizio (ADR 0026).")) + .AppendLine(); + b.AppendLine(Text($"Dal {m.From:dd/MM/yyyy} al {m.To:dd/MM/yyyy}, {r.Sessions.ToString("#,0", It)} punti di patrimonio giornalieri, capitale iniziale {Money(m.InitialCapital, r.Currency)}. Costi di {VenueName(costs.Venue)} del {costs.AsOf:dd/MM/yyyy}. Impronta del piano `{Short(trial.PlanHash)}`, dei dati `{Short(r.DataFingerprint)}`. Varianti della griglia: {r.Variants.Count}; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: {r.TrialsCounted}.")) + .AppendLine(); + + b.AppendLine("| Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |"); + b.AppendLine("|---|---:|---:|---:|---:|---:|---|"); + var doubled = r.Costs.FirstOrDefault(c => c.Multiplier == 2m); + b.Append("| `").Append(r.Judged ?? r.Chosen).Append("` | ").Append(Pct(m.AnnualReturn)).Append(" | ").Append(Pct(-m.MaxDrawdown)) + .Append(" | ").Append(doubled is null ? "—" : Money(doubled.NetResult, r.Currency)).Append(" | ").Append(Num(r.DeflatedSharpe.Value)) + .Append(" | ").Append(r.Overfitting is { } o ? Num(o.Probability) : "—").Append(" | ").Append(r.Passed ? "superata" : "non superata").AppendLine(" |"); + b.AppendLine(); + + b.AppendLine("Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni né perdite.").AppendLine(); + b.AppendLine("| | Strategia | Zero (nessuna operazione) |").AppendLine("|---|---:|---:|"); + Row(b, "Risultato netto", Money(m.NetResult, r.Currency), Money(h.NetResult, r.Currency)); + Row(b, "Rendimento totale", Pct(m.TotalReturn), Pct(h.TotalReturn)); + Row(b, "Rendimento annuo", Pct(m.AnnualReturn), Pct(h.AnnualReturn)); + Row(b, "Volatilità annua", Pct(m.Volatility), Pct(h.Volatility)); + Row(b, "Calo massimo", Pct(-m.MaxDrawdown), Pct(-h.MaxDrawdown)); + Row(b, "Sharpe annuo", Num(m.Sharpe), Num(h.Sharpe)); + Row(b, "Costi pagati", Money(m.Fees, r.Currency), Money(h.Fees, r.Currency)); + b.AppendLine(); + + b.AppendLine("**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)").AppendLine(); + b.AppendLine("| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo |").AppendLine("|---|---:|---:|---:|---:|"); + foreach (var c in r.Costs) + { + b.AppendLine(Text($"| ×{c.Multiplier:0} | {Money(c.NetResult, r.Currency)} | {Pct(c.TotalReturn)} | {Num(c.Sharpe)} | {Pct(-c.MaxDrawdown)} |")); + } + + b.AppendLine(); + b.AppendLine("**Convalide**").AppendLine(); + if (r.WalkForward is { } wf) + { + b.AppendLine(Text($"- Finestre che avanzano ({wf.Windows.Count}, con {wf.Purge} giorni di stacco): rendimento fuori campione {Pct(wf.Return)}, Sharpe annuo {Num(wf.Sharpe * annual)}.")); + } + + if (r.Combinatorial is { } cv) + { + b.AppendLine(Text($"- K-fold purgato combinatorio ({cv.Groups} gruppi, {cv.TestGroups} di prova, {cv.Splits} divisioni): Sharpe annuo medio dei percorsi {Num(cv.MeanSharpe * annual)}, peggiore {Num(cv.WorstSharpe * annual)}, percorsi positivi {Pct(cv.PositiveShare)}.")); + } + + b.AppendLine(Text($"- Deflated Sharpe Ratio {Num(r.DeflatedSharpe.Value)}, contando {r.TrialsCounted} varianti provate in tutto.")); + b.AppendLine(r.Overfitting is { } pbo + ? Text($"- Probabilità di sovra-adattamento (PBO) {Num(pbo.Probability)}, su {pbo.Combinations} combinazioni di {pbo.Variants} varianti.") + : "- Probabilità di sovra-adattamento: non calcolabile con una sola variante."); + b.AppendLine(Text($"- Sguardo in avanti: {r.LookAhead.Decisions} decisioni rifatte tagliando i dati in {r.LookAhead.Cutoffs.Count} punti, {r.LookAhead.Changed} cambiate.")); + b.AppendLine(); + + b.AppendLine("**Soglie**").AppendLine(); + b.AppendLine("| Controllo | Valore | Soglia | Esito |").AppendLine("|---|---:|---:|---|"); + foreach (var c in r.Checks) + { + b.AppendLine(Text($"| {c.Name} | {CheckValue(c, r.Currency)} | {c.Comparison} {CheckThreshold(c, r.Currency)} | {(c.Passed is null ? "non si applica" : c.Passed.Value ? "superato" : "**non superato**")} |")); + } + + b.AppendLine(); + b.AppendLine("**Varianti della griglia**").AppendLine(); + b.AppendLine("| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo |").AppendLine("|---|---:|---:|---:|---:|"); + foreach (var v in r.Variants) + { + b.AppendLine(Text($"| `{v.Parameters}`{(v.Chosen ? " (scelta)" : "")} | {Num(v.Sharpe * annual)} | {Num(v.PlateauScore * annual)} | {Money(v.NetResult, r.Currency)} | {Pct(-v.MaxDrawdown)} |")); + } + + b.AppendLine(); + BasketsSection(b, r); + } + + private static void BasketsSection(StringBuilder b, BacktestReport r) + { + var baskets = r.Baskets ?? []; + b.AppendLine("**Panieri**").AppendLine(); + b.AppendLine(baskets.Count >= TrialRunner.MaxTrades + ? Text($"Panieri della variante giudicata: gli ultimi {baskets.Count} aperti (il rapporto ne tiene al più {TrialRunner.MaxTrades}).") + : Text($"Panieri della variante giudicata: {baskets.Count}.")); + b.AppendLine(); + if (baskets.Count > 0) + { + b.AppendLine("| Uscita | Panieri |").AppendLine("|---|---:|"); + var counts = baskets.GroupBy(x => x.ExitReason ?? "", StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal); + foreach (var (code, label) in Exits) + { + if (counts.TryGetValue(code, out var n)) + { + b.AppendLine(Text($"| {label} | {n} |")); + } + } + + foreach (var (code, n) in counts.Where(x => x.Key.Length > 0 && !Exits.Any(e => e.Code == x.Key)).OrderBy(x => x.Key, StringComparer.Ordinal)) + { + b.AppendLine(Text($"| `{code}` | {n} |")); + } + + if (counts.TryGetValue("", out var open)) + { + b.AppendLine(Text($"| ancora aperto alla fine | {open} |")); + } + + b.AppendLine(); + var closed = baskets.Count(x => x.ExitReason is not null); + var atTarget = baskets.Count(x => x.ExitReason == "target"); + b.AppendLine(Text($"Chiusi all'obiettivo: {Share(closed == 0 ? double.NaN : (double)atTarget / closed)} dei panieri chiusi. La quota è mostrata e mai giudicata.")) + .AppendLine(); + } + + // The notes count every event of the whole run; the baskets list is capped, so it is only the fallback. + int Events(string code) => r.Notes.TryGetValue(code, out var n) ? n : baskets.Count(x => x.ExitReason == code); + b.AppendLine(Text($"- Gambe rimaste sole: {Events(OrphanLeg)} (una gamba chiusa da uno stop obbligatorio chiude il resto del paniere all'esecuzione successiva).")); + b.AppendLine(Text($"- Chiusure d'ufficio per margine insufficiente: {Events(Liquidation)}.")); + b.AppendLine(Text($"- Stop sul valore del conto: {Events(AccountStop)}.")); + b.AppendLine(); + + var refusals = r.Notes.Where(n => n.Key is not (OrphanLeg or Liquidation or AccountStop)).ToList(); + b.AppendLine("**Ingressi e mediazioni non fatti**").AppendLine(); + if (refusals.Count == 0) + { + b.AppendLine("Nessuno.").AppendLine(); + return; + } + + b.AppendLine("| Motivo | Volte |").AppendLine("|---|---:|"); + foreach (var (code, n) in refusals.OrderByDescending(x => x.Value).ThenBy(x => x.Key, StringComparer.Ordinal)) + { + b.AppendLine(Text($"| {(Refusals.TryGetValue(code, out var label) ? label : "`" + code + "`")} | {n} |")); + } + + b.AppendLine(); + } + + private static void LimitsSection(StringBuilder b, BasketReportInput input) + { + b.AppendLine("## Cosa il backtest non rappresenta").AppendLine(); + foreach (var line in input.Trial?.Report.Limitations ?? []) + { + b.Append("- ").AppendLine(line); + } + + var c = input.Costs; + b.AppendLine("- I prezzi sono i cambi di riferimento della BCE, uno al giorno: non si può negoziare a quei prezzi, e dentro la giornata il prezzo tocca livelli che i cambi non mostrano, stop compresi."); + b.AppendLine(Text($"- I costi sono quelli di {VenueName(c.Venue)} letti il {c.AsOf:dd/MM/yyyy}: differenziali, commissioni e finanziamenti cambiano nel tempo.")); + b.AppendLine("- Il bot non legge il conto reale: margine, leva e chiusure d'ufficio seguono le regole della tabella dei costi, non il conto vero."); + b.AppendLine("- Il finanziamento delle coppie segnate come stimate usa il costo più alto tra quelli noti, non quello vero."); + b.AppendLine("- Mancano ancora i dati a 15 minuti: il giudizio che conta richiede i file a 1 minuto forniti dall'utente."); + } + + private static string ModeName(string mode) => mode switch + { + LikeLive => "«come dal vivo»", + ToTheLetter => "«alla lettera»", + _ => "«" + mode + "»", + }; + + private static string VenueName(string venue) => venue switch + { + "etoro" => "eToro", + "none" => "nessuna piattaforma (configurazione di confronto)", + _ => venue, + }; + + private static string StopWords(string stopLabel) => stopLabel == "nessuno" ? "senza stop" : "con stop di " + stopLabel; + + private static string Describe(ReportCheck check, string currency) => + $"{check.Name.ToLower(It)} {CheckValue(check, currency)}, serve {check.Comparison} {CheckThreshold(check, currency)}"; + + private static string CheckValue(ReportCheck c, string currency) => c.Value is not { } v ? "—" : c.Unit switch + { + "percent" => Pct(v), + "money" => Money((decimal)v, currency), + "count" => v.ToString("0", It), + _ => Num(v), + }; + + private static string CheckThreshold(ReportCheck c, string currency) => + c.Unit == "percent" ? Pct(c.Threshold, 0) : c.Unit == "money" ? Money((decimal)c.Threshold, currency) : c.Threshold.ToString("0.##", It); + + private static double Median(double[] sorted) => + sorted.Length == 0 ? double.NaN : sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[(sorted.Length / 2) - 1] + sorted[sorted.Length / 2]) / 2; + + /// The value at rank ⌊p·(n − 1)⌋ of a sorted array, as takes its percentiles. + private static double Rank(double[] sorted, double p) => sorted[(int)Math.Floor(p * (sorted.Length - 1))]; + + private static void Row(StringBuilder b, string label, string strategy, string zero) => + b.Append("| ").Append(label).Append(" | ").Append(strategy).Append(" | ").Append(zero).AppendLine(" |"); + + private static string Short(string fingerprint) => fingerprint.Length > 12 ? fingerprint[..12] : fingerprint; + + private static string Minus(double value) => value < 0 ? "−" : ""; + + /// A total in targets: 535,5; 1.032; −100,8. + private static string Targets(double value) => Minus(value) + Math.Abs(value).ToString("#,0.#", It); + + private static string SignedTargets(double value) => (value > 0 ? "+" : "") + Targets(value); + + /// A break-even or another ratio with its sign: +0,32, −0,03; a dash when not a number. + private static string Ratio(double value) => double.IsNaN(value) ? "—" : (value > 0 ? "+" : "") + Num(value); + + private static string Share(double fraction) => double.IsNaN(fraction) ? "—" : Pct(fraction); + + private static string Pct(double fraction, int decimals = 1) => + Minus(fraction) + Math.Abs(fraction * 100).ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), It) + "%"; + + private static string Num(double value) => Minus(value) + Math.Abs(value).ToString("0.00", It); + + private static string Amount(decimal value) => (value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.###", It); + + private static string Signed(decimal value) => (value > 0 ? "+" : "") + Amount(value); + + private static string Money(decimal value, string currency) => + (value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.00", It) + " " + (currency == "EUR" ? "€" : currency); + + private static string Text(FormattableString text) => text.ToString(It); +} diff --git a/tests/Anubis.Tests/BasketReportTests.cs b/tests/Anubis.Tests/BasketReportTests.cs new file mode 100644 index 0000000..4c3bc0f --- /dev/null +++ b/tests/Anubis.Tests/BasketReportTests.cs @@ -0,0 +1,328 @@ +using System.Security.Cryptography; +using System.Text; +using Anubis.Backtest; +using Anubis.Baskets; +using Anubis.Core; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// The report of the basket family (Phase 14, issue #131): docs/backtests/basket_reversion.md 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. +/// +[TestClass] +public sealed class BasketReportTests +{ + private const string Command = "anubis backtest baskets --to 2026-11-30"; + + /// SHA-256 of the lower-case name of the product the research document describes: the test never writes it. + 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); + + /// The prototype's totals, positions and baskets of the 15 rows of G.4: what the replica gives on the ECB file. + 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 _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"], null, -3m), + ]; + var notes = new Dictionary(StringComparer.Ordinal) + { + ["orphan_leg"] = 2, + ["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, "| 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 | 1 |"); + StringAssert.Contains(two, "Panieri della variante giudicata: 5."); + StringAssert.Contains(two, "perdita aperta oltre il 2%"); + StringAssert.Contains(two, "| `weird_code` | 1 |"); + StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0%"); + + var none = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = new Dictionary(), 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"); + } + + [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** (commissione, differenziale e finanziamento pagato moltiplicati insieme)"); + 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")), + }; + 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 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 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>(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); + } + + /// A research family with one numeric axis, under the basket family's id. + 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 Parameters => [new("target", "Obiettivo", 2.5m, [2m, 2.5m, 3m], 1m, 5m)]; + } + + /// An engine with a flat benchmark (zero) and a noisy equity that depends on the target. + 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 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(); + 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 Limitations() => ["Motore finto della prova."]; + + public TrialExpectations Expected(BacktestRun run, double[] returns) => new(null, null); + } +}