diff --git a/docs/backtests/basket_reversion.md b/docs/backtests/basket_reversion.md
new file mode 100644
index 0000000..fce8107
--- /dev/null
+++ b/docs/backtests/basket_reversion.md
@@ -0,0 +1,213 @@
+# Backtest di `basket_reversion` (Rientro tra strumenti)
+
+**Esito: non superato.** La prova «come dal vivo» non supera: risultato netto con costi doppi −1.580,16 USD, serve > 0,00 USD; deflated sharpe ratio 0,25, serve ≥ 0,9.
+
+Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).
+
+Calcolato il 2026-12-04 con la versione basket-1 del motore a panieri e la versione 1 della famiglia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.
+
+Per rifarlo: `anubis backtest baskets --to 2026-11-30`.
+
+## Dati
+
+- Cambi di riferimento della BCE: 7 valute contro l'euro (GBP, AUD, NZD, USD, CAD, CHF, JPY), da cui 28 coppie incrociate. Fonte: Banca centrale europea, cambi di riferimento (eurofxref-hist.zip, conservato nella cartella di ricerca).
+- Periodo: dal 04/01/1999 al 04/12/2026, 7.151 giorni con il cambio. Impronta dei dati `1c01c649c7af`.
+- La replica dell'appendice G usa i dati fino al 02/12/2026, la fine del documento.
+- 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.
+- Costi: eToro, letti il 02/12/2026. Fonte: Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026
+- Minimo 1.000 USD per posizione, leva 5 per posizione, mai oltre quella del conto reale.
+- Il finanziamento notturno di 16 coppie su 28 non è nel documento: per prudenza pagano, su entrambi i lati, il costo più alto tra quelli noti. Sono segnate come stimate nella tabella.
+
+**Tabella dei costi** (differenziale in pip; finanziamento in USD per 100.000 USD di esposizione a notte, positivo se si paga)
+
+| Coppia | Differenziale | In pausa | Leva massima | Commissione per lato | Finanziamento acquisto | Finanziamento vendita | Finanziamento |
+|---|---:|---:|---:|---:|---:|---:|---|
+| EURGBP | 0,4 | 2,3 | 30 | 0,005% | +7,92 | −0,36 | dal documento |
+| EURAUD | 1,1 | 8,3 | 20 | 0,005% | +10,37 | −2,745 | dal documento |
+| EURNZD | 4,3 | 16,8 | 20 | 0,005% | +4,65 | +3,7 | dal documento |
+| EURUSD | 0,1 | 2,2 | 30 | 0,005% | +8,096 | −0,46 | dal documento |
+| EURCAD | 0,9 | 8,4 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| EURCHF | 0,2 | 7,5 | 30 | 0,005% | −3,597 | +11,336 | dal documento |
+| EURJPY | 1,6 | 11,2 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| GBPAUD | 1,2 | 14,9 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| GBPNZD | 8,3 | 25 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| GBPUSD | 0,2 | 2,3 | 30 | 0,005% | +3,927 | +3,696 | dal documento |
+| GBPCAD | 2 | 11 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| GBPCHF | 1 | 23,3 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| GBPJPY | 0,9 | 14,8 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| AUDNZD | 0,8 | 6,9 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| AUDUSD | 0,1 | 2,1 | 20 | 0,005% | +1,51 | +6,191 | dal documento |
+| AUDCAD | 1 | 7,1 | 20 | 0,005% | −3,074 | +10,812 | dal documento |
+| AUDCHF | 0,9 | 13,5 | 20 | 0,005% | −10,324 | +17,978 | dal documento |
+| AUDJPY | 0,7 | 7 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| NZDUSD | 0,1 | 2,8 | 20 | 0,005% | +8,14 | +0,37 | dal documento |
+| NZDCAD | 1,6 | 7,3 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| NZDCHF | 1 | 12,2 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| NZDJPY | 1,6 | 9,8 | 20 | 0,005% | +17,978 | +17,978 | stimato |
+| USDCAD | 0,3 | 4,2 | 30 | 0,005% | −0,77 | +8,33 | dal documento |
+| USDCHF | 0,1 | 11,2 | 30 | 0,005% | −7,788 | +15,458 | dal documento |
+| USDJPY | 0,3 | 5,8 | 30 | 0,002% | +17,978 | +17,978 | stimato |
+| CADCHF | 0,8 | 11,6 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| CADJPY | 0,8 | 10,7 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+| CHFJPY | 1,7 | 58,4 | 30 | 0,005% | +17,978 | +17,978 | stimato |
+
+## Replica dell'appendice G
+
+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).
+
+| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |
+|---|---|---:|---:|---:|---:|---|---|
+| 2,5 σ · 10 σ · 3 | nessuno | 534 | 535,5 | +1,5 | ±26,7 | sì | dentro |
+| 2,5 σ · 10 σ · 3 | 90 obiettivi | 542 | 543,7 | +1,7 | ±27,1 | sì | dentro |
+| 2,5 σ · 10 σ · 3 | 30 obiettivi | 255 | 257,2 | +2,2 | ±25 | sì | dentro |
+| 2 σ · 8 σ · 3 | nessuno | 757 | 753,6 | −3,4 | ±37,9 | sì | dentro |
+| 2 σ · 8 σ · 3 | 90 obiettivi | 1.032 | 1.029,1 | −2,9 | ±51,6 | sì | dentro |
+| 2 σ · 8 σ · 3 | 30 obiettivi | −98 | −100,8 | −2,8 | ±25 | no | solo riportata |
+| 3 σ · 12 σ · 3 | nessuno | 338 | 340,1 | +2,1 | ±25 | sì | dentro |
+| 3 σ · 12 σ · 3 | 90 obiettivi | 534 | 536,3 | +2,3 | ±26,7 | sì | dentro |
+| 3 σ · 12 σ · 3 | 30 obiettivi | 137 | 138,4 | +1,4 | ±25 | sì | dentro |
+| 2,5 σ · 4 σ · 3 | nessuno | 649 | 647,1 | −1,9 | ±32,5 | sì | dentro |
+| 2,5 σ · 4 σ · 3 | 90 obiettivi | 442 | 439,5 | −2,5 | ±25 | sì | dentro |
+| 2,5 σ · 4 σ · 3 | 30 obiettivi | −45 | −47,4 | −2,4 | ±25 | no | solo riportata |
+| 2,5 σ · 4 σ crescente · 4 | nessuno | 533 | 531,3 | −1,7 | ±26,7 | sì | dentro |
+| 2,5 σ · 4 σ crescente · 4 | 90 obiettivi | 759 | 757,4 | −1,6 | ±38 | sì | dentro |
+| 2,5 σ · 4 σ crescente · 4 | 30 obiettivi | 172 | 169,9 | −2,1 | ±25 | sì | dentro |
+
+13 righe vincolanti su 13 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.
+
+Solo riportate, perché vicine allo zero: 2 σ · 8 σ · 3 con stop di 30 obiettivi, documento −98, Anubis −100,8 (stesso segno); 2,5 σ · 4 σ · 3 con stop di 30 obiettivi, documento −45, Anubis −47,4 (stesso segno).
+
+| Obiettivo · distanza · mediazioni | Stop | Pareggio del documento | Pareggio di Anubis | Posizioni | Panieri | Chiusi all'obiettivo |
+|---|---|---:|---:|---:|---:|---:|
+| 2,5 σ · 10 σ · 3 | nessuno | +0,32 | +0,32 | 1.675 | 1.259 | 97,9% |
+| 2,5 σ · 10 σ · 3 | 90 obiettivi | +0,26 | +0,27 | 2.047 | 1.543 | 97,1% |
+| 2,5 σ · 10 σ · 3 | 30 obiettivi | +0,11 | +0,11 | 2.390 | 1.788 | 94,6% |
+| 2 σ · 8 σ · 3 | nessuno | +0,39 | +0,39 | 1.953 | 1.467 | 98,4% |
+| 2 σ · 8 σ · 3 | 90 obiettivi | +0,40 | +0,40 | 2.583 | 1.929 | 97,8% |
+| 2 σ · 8 σ · 3 | 30 obiettivi | −0,03 | −0,03 | 2.937 | 2.186 | 94,4% |
+| 3 σ · 12 σ · 3 | nessuno | +0,24 | +0,24 | 1.424 | 1.066 | 97,5% |
+| 3 σ · 12 σ · 3 | 90 obiettivi | +0,33 | +0,33 | 1.641 | 1.223 | 97,0% |
+| 3 σ · 12 σ · 3 | 30 obiettivi | +0,07 | +0,07 | 1.936 | 1.447 | 94,3% |
+| 2,5 σ · 4 σ · 3 | nessuno | +0,33 | +0,33 | 1.977 | 1.167 | 97,8% |
+| 2,5 σ · 4 σ · 3 | 90 obiettivi | +0,16 | +0,16 | 2.702 | 1.590 | 96,9% |
+| 2,5 σ · 4 σ · 3 | 30 obiettivi | −0,01 | −0,01 | 3.650 | 2.166 | 93,2% |
+| 2,5 σ · 4 σ crescente · 4 | nessuno | +0,25 | +0,25 | 2.133 | 1.273 | 97,9% |
+| 2,5 σ · 4 σ crescente · 4 | 90 obiettivi | +0,25 | +0,25 | 3.010 | 1.796 | 97,2% |
+| 2,5 σ · 4 σ crescente · 4 | 30 obiettivi | +0,05 | +0,05 | 3.455 | 2.109 | 93,7% |
+
+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.
+
+## Controllo contro il caso (G.5)
+
+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.
+
+| Obiettivo · distanza · mediazioni | Stop | Ripetizioni | Seme | Pareggio osservato | Mediana rimescolate | 5°–95° percentile | Pari o migliori: Anubis | Pari o migliori: documento |
+|---|---|---:|---:|---:|---:|---:|---:|---:|
+| 2,5 σ · 10 σ · 3 | nessuno | 150 | 20261202 | +0,32 | +0,10 | −1,95; +0,81 | 36,0% | 37% |
+| 2,5 σ · 10 σ · 3 | 90 obiettivi | 150 | 20261202 | +0,27 | +0,03 | −0,89; +0,65 | 26,7% | 33% |
+| 2,5 σ · 4 σ · 3 | nessuno | 150 | 20261202 | +0,33 | −0,03 | −1,81; +0,77 | 34,7% | 33% |
+| 2,5 σ · 4 σ · 3 | 90 obiettivi | 150 | 20261202 | +0,16 | +0,02 | −0,73; +0,56 | 31,3% | 32% |
+
+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.
+
+## Prova del motore a panieri
+
+Le 28 coppie della BCE dal 1999: generazione A (i cinque spread a due gambe) e B (i dieci cambi da soli), segnale sui logaritmi, misure in σ, uscita sulla media degli ingressi. Modo «come dal vivo»: le regole del documento più i limiti del bot (SPEC 9.2) e quelli del margine; solo questo modo dà un giudizio (ADR 0026).
+
+Dal 04/01/1999 al 30/11/2026, 7.147 punti di patrimonio giornalieri, capitale iniziale 20.000,00 USD. Costi di eToro del 02/12/2026. Impronta del piano `cb442c4b2b0a`, dei dati `babb6d7ba38f`. Varianti della griglia: 4; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: 4.
+
+| Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
+|---|---:|---:|---:|---:|---:|---|
+| `averagings=3;distance=10;entry_z=2;exit=2;generation=2;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | 0,1% | −12,0% | −1.580,16 USD | 0,25 | 0,15 | non superata |
+
+Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni né perdite.
+
+| | Strategia | Zero (nessuna operazione) |
+|---|---:|---:|
+| Risultato netto | 506,72 USD | 0,00 USD |
+| Rendimento totale | 2,5% | 0,0% |
+| Rendimento annuo | 0,1% | 0,0% |
+| Volatilità annua | 1,8% | 0,0% |
+| Calo massimo | −12,0% | 0,0% |
+| Sharpe annuo | 0,06 | 0,00 |
+| Costi pagati | 1.706,51 USD | 0,00 USD |
+
+**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)
+
+| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo |
+|---|---:|---:|---:|---:|
+| ×1 | 506,72 USD | 2,5% | 0,06 | −12,0% |
+| ×2 | −1.580,16 USD | −7,9% | −0,20 | −13,5% |
+| ×3 | −3.345,01 USD | −16,7% | −0,41 | −19,5% |
+
+**Convalide**
+
+- Finestre che avanzano (4, con 72 giorni di stacco): rendimento fuori campione −4,4%, Sharpe annuo −0,10.
+- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,06, peggiore 0,06, percorsi positivi 100,0%.
+- Deflated Sharpe Ratio 0,25, contando 4 varianti provate in tutto.
+- Probabilità di sovra-adattamento (PBO) 0,15, su 12870 combinazioni di 4 varianti.
+- Sguardo in avanti: 4817 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
+
+**Soglie**
+
+| Controllo | Valore | Soglia | Esito |
+|---|---:|---:|---|
+| Risultato netto con costi doppi | −1.580,16 USD | > 0,00 USD | **non superato** |
+| Deflated Sharpe Ratio | 0,25 | ≥ 0,9 | **non superato** |
+| Probabilità di sovra-adattamento (PBO) | 0,15 | ≤ 0,4 | superato |
+| Calo massimo | 12,0% | ≤ 25% | superato |
+| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
+
+**Varianti della griglia**
+
+| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo |
+|---|---:|---:|---:|---:|
+| `averagings=3;distance=4;entry_z=2;exit=2;generation=1;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | −0,25 | −0,29 | −2.595,52 USD | −14,9% |
+| `averagings=3;distance=10;entry_z=2;exit=2;generation=1;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | −0,34 | −0,34 | −2.512,22 USD | −13,9% |
+| `averagings=3;distance=4;entry_z=2;exit=2;generation=2;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | −0,08 | −0,08 | −1.213,13 USD | −13,3% |
+| `averagings=3;distance=10;entry_z=2;exit=2;generation=2;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` (scelta) | 0,06 | −0,01 | 506,72 USD | −12,0% |
+
+**Panieri**
+
+Panieri della variante giudicata: 266.
+
+| Uscita | Panieri |
+|---|---:|
+| obiettivo raggiunto | 242 |
+| stop obbligatorio della piattaforma | 22 |
+| fine del periodo | 2 |
+
+Chiusi all'obiettivo: 91,0% dei panieri chiusi. La quota è mostrata e mai giudicata.
+
+- Gambe rimaste sole: 0 (una gamba chiusa da uno stop obbligatorio chiude il resto del paniere all'esecuzione successiva).
+- Chiusure d'ufficio per margine insufficiente: 0.
+- Stop sul valore del conto: 0.
+- Posizioni chiuse dallo stop obbligatorio della piattaforma: 22.
+
+**Ingressi e mediazioni fermati o annotati**
+
+Con il profilo Fedele la regola dei tre costi e il limite di esposizione per valuta sono solo annotati: l'ingresso si fa lo stesso. Una dimensione dimezzata è un ingresso fatto più piccolo.
+
+| Motivo | Volte |
+|---|---:|
+| già aperto il numero massimo di panieri | 1569 |
+| esposizione su una valuta oltre il limite | 114 |
+| perdita aperta oltre il 2%: nessun paniere nuovo | 31 |
+| volatilità recente oltre il doppio del normale | 14 |
+| dimensione dimezzata (perdita della settimana o calo dal massimo) | 11 |
+| livello sotto il minimo della piattaforma | 6 |
+
+## Cosa il backtest non rappresenta
+
+- I prezzi della BCE sono cambi di riferimento, non prezzi a cui si compra o si vende: denaro e lettera sono ricostruiti attorno al cambio con il differenziale della tabella dei costi.
+- Costi di eToro al 2 dicembre 2026: Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026.
+- Il finanziamento notturno delle coppie che il documento non dà è stimato con prudenza: il costo più alto fra quelli noti, sui due lati.
+- Si decide sul cambio di chiusura di un giorno e si esegue su quello del giorno dopo; le finestre orarie (fine settimana, sessione, pausa giornaliera) su barre giornaliere non valgono.
+- Il conto non viene letto: margine, stop obbligatorio della piattaforma, chiusura d'ufficio sotto metà del margine e finanziamento con il mercoledì triplo sono simulati con le regole della sede.
+- Modalità «come dal vivo»: regole del documento più i limiti di rischio (perdita del giorno, della settimana, calo dal massimo) e del margine; se scatta l'interruttore supponiamo che tu riparta dopo sette giorni.
+- Nessuna notizia e nessun calendario economico: il filtro delle notizie è spento.
+- Il confronto è con zero, cioè il capitale fermo, non con comprare e tenere.
+- Sharpe e volatilità sono calcolati senza tasso privo di rischio.
+- 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.
+- I costi sono quelli di eToro letti il 02/12/2026: differenziali, commissioni e finanziamenti cambiano nel tempo.
+- Mancano ancora i dati a 15 minuti: il giudizio che conta richiede i file a 1 minuto forniti dall'utente.
diff --git a/src/Anubis.Server/BacktestCommand.cs b/src/Anubis.Server/BacktestCommand.cs
index 7c8dea1..c590c6d 100644
--- a/src/Anubis.Server/BacktestCommand.cs
+++ b/src/Anubis.Server/BacktestCommand.cs
@@ -15,17 +15,25 @@ namespace Anubis.Server;
/// them to euro, runs the protocol of crypto_trend on both universes and writes reports and outcome files.
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
/// "anubis backtest candidates" does the same for the candidates of SPEC 8.4 and leaves the other files alone.
+/// "anubis backtest baskets" is the basket family's: .
///
internal static class BacktestCommand
{
- private const string Usage =
- "Uso: anubis backtest base|candidates [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
- " --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir , obbligatoria fuori dal container]";
+ internal const string Usage =
+ "Uso: anubis backtest base|candidates|baskets [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
+ " --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir , obbligatoria fuori dal container]\n" +
+ " baskets [--control 150] [--seed 20261202]: replica dell'appendice G, controllo contro il caso e prova del motore a panieri sui cambi BCE,\n" +
+ " registrata nel database (avvia prima il server una volta). Con --offline usa solo lo storico BCE già scaricato e si ferma se manca.";
public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null,
HttpMessageHandler? handler = null)
{
output ??= Console.Out;
+ if (args.Length >= 1 && args[0] == "baskets")
+ {
+ return await BasketCommand.RunAsync(args[1..], output, environment, handler).ConfigureAwait(false);
+ }
+
if (args.Length < 1 || args[0] is not ("base" or "candidates"))
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
diff --git a/src/Anubis.Server/BasketCommand.cs b/src/Anubis.Server/BasketCommand.cs
new file mode 100644
index 0000000..fa86a2b
--- /dev/null
+++ b/src/Anubis.Server/BasketCommand.cs
@@ -0,0 +1,207 @@
+using System.Collections;
+using System.Globalization;
+using Anubis.Backtest;
+using Anubis.Baskets;
+using Anubis.Brokers;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Strategies;
+
+namespace Anubis.Server;
+
+///
+/// "anubis backtest baskets" (Phase 14, issue #131): the replica of appendix G of the research document on the 28 ECB
+/// crosses, the control against chance of G.5 and the trial of the basket engine «come dal vivo» with the eToro costs
+/// (). The trial is planned in the configured database before it runs, read back and run only if
+/// its stored plan is the one just written, judged with every earlier trial of the family counted, and recorded. The report
+/// basket_reversion.md is written whatever the verdict; there is no outcome file for the family.
+///
+internal static class BasketCommand
+{
+ private const string Progress = "costi doppi e tripli, comprare e tenere";
+
+ public static async Task RunAsync(string[] args, TextWriter output, IReadOnlyDictionary? environment = null,
+ HttpMessageHandler? handler = null, IClock? clock = null)
+ {
+ ArgumentNullException.ThrowIfNull(args);
+ ArgumentNullException.ThrowIfNull(output);
+ clock ??= new SystemClock();
+ var rest = args.ToList();
+ var offline = rest.Remove("--offline");
+ var own = new Dictionary(StringComparer.Ordinal);
+ foreach (var name in new[] { "--to", "--out", "--control", "--seed" })
+ {
+ var index = rest.IndexOf(name);
+ if (index < 0)
+ {
+ continue;
+ }
+
+ if (index == rest.Count - 1)
+ {
+ return await UsageAsync(output, $"Manca il valore di {name}.").ConfigureAwait(false);
+ }
+
+ own[name] = rest[index + 1];
+ rest.RemoveRange(index, 2);
+ }
+
+ var now = clock.UtcNow;
+ DateOnly to;
+ if (own.TryGetValue("--to", out var t))
+ {
+ if (!DateOnly.TryParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out to))
+ {
+ return await UsageAsync(output, "--to vuole una data AAAA-MM-GG.").ConfigureAwait(false);
+ }
+ }
+ else
+ {
+ to = new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last day of the previous month.
+ }
+
+ var repetitions = BasketProtocol.ControlRepetitions;
+ if (own.TryGetValue("--control", out var c) && (!int.TryParse(c, NumberStyles.None, CultureInfo.InvariantCulture, out repetitions) || repetitions < 1))
+ {
+ return await UsageAsync(output, "--control vuole un numero intero di ripetizioni, almeno 1.").ConfigureAwait(false);
+ }
+
+ var seed = BasketProtocol.ControlSeed;
+ if (own.TryGetValue("--seed", out var s) && !int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out seed))
+ {
+ return await UsageAsync(output, "--seed vuole un numero intero.").ConfigureAwait(false);
+ }
+
+ environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
+ var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
+ var outDir = Path.GetFullPath(own.GetValueOrDefault("--out") ?? Path.Combine("docs", "backtests"));
+ if (!config.IsComplete)
+ {
+ await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
+ return 1;
+ }
+
+ try
+ {
+ Redactor.Register(config.Db!.Password);
+ await using var db = Database.Open(config.Db!, allowCreate: false);
+ config.Data.Ensure();
+ Directory.CreateDirectory(outDir);
+
+ var rates = await RatesAsync(config.Data.Research, offline, handler, clock, output).ConfigureAwait(false);
+ var crosses = EcbCrosses.Build(rates);
+ var notes = BasketProtocol.Notes(crosses);
+ await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
+ $"Cambi BCE: {EcbCrosses.Rates.Count} valute, {notes.Pairs} coppie, {notes.Days} giorni, dal {notes.First:yyyy-MM-dd} al {notes.Last:yyyy-MM-dd}.")).ConfigureAwait(false);
+
+ var series = StylisedReplica.EcbSeries(crosses, BasketProtocol.ReplicaThrough);
+ var replica = BasketProtocol.Replica(series);
+ var binding = replica.Where(r => r.Case.Binding).ToList();
+ await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
+ $"Replica dell'appendice G fino al {Earlier(notes.Last, BasketProtocol.ReplicaThrough):yyyy-MM-dd}: {binding.Count(r => r.Case.Passes(r.Result.Total))} su {binding.Count} righe vincolanti dentro la tolleranza.")).ConfigureAwait(false);
+
+ var control = BasketProtocol.Control(series, repetitions, seed);
+ var it = CultureInfo.GetCultureInfo("it-IT");
+ await output.WriteLineAsync(string.Create(it,
+ $"Controllo contro il caso: {repetitions} ripetizioni, seme {seed.ToString(CultureInfo.InvariantCulture)}. Pari o migliori: {string.Join("; ", control.Select(r => $"{r.Case.Label} {r.Case.StopLabel} {r.Control.Share * 100:0.0}% (documento {r.DocumentShare * 100:0}%)"))}."))
+ .ConfigureAwait(false);
+
+ var (plan, variants) = BasketProtocol.Plan(to, now);
+ var data = BasketProtocol.Dataset(crosses, to);
+ var trials = new TrialStore(db, clock);
+ var planned = await trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
+ if (!await trials.StartAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))
+ {
+ throw new InvalidOperationException("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.");
+ }
+
+ var trial = (await trials.GetAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))!;
+ var refusal = !trial.PlanIntact
+ ? "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."
+ : trial.PlanHash != TrialPlan.Hash(plan.ToJson())
+ ? "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."
+ : null;
+ if (refusal is not null)
+ {
+ await trials.FailAsync(trial.Id, refusal, CancellationToken.None).ConfigureAwait(false);
+ await output.WriteLineAsync("Non riuscito: " + refusal).ConfigureAwait(false);
+ return 1;
+ }
+
+ BacktestReport report;
+ try
+ {
+ var prior = await trials.PriorAsync(trial.Strategy, trial.Id, CancellationToken.None).ConfigureAwait(false);
+ await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
+ $"Prova {trial.Id} pianificata con il piano {trial.PlanHash[..12]}: {variants} varianti dal {plan.Data.From:yyyy-MM-dd} al {plan.Data.To:yyyy-MM-dd}, prove precedenti contate: {prior.Trials}."))
+ .ConfigureAwait(false);
+ var engine = new BasketTrialEngine(trial.Plan, BasketReversionFamily.Instance, data);
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var (judged, summary) = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, BasketReversionFamily.Instance, engine, prior, now,
+ text => output.WriteLine("Prova: " + (text == Progress ? "costi doppi e tripli, confronto con zero" : text)));
+ await trials.FinishAsync(trial.Id, judged.DataFingerprint, summary, judged.ToJson(), judged.Passed, CancellationToken.None).ConfigureAwait(false);
+ await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Prova calcolata in {watch.Elapsed.TotalSeconds:0} secondi.")).ConfigureAwait(false);
+ report = judged;
+ }
+ catch (Exception ex)
+ {
+ // A trial left running would be picked up by the laboratory at the next start: it is closed as failed.
+ await trials.FailAsync(trial.Id, Redactor.Redact(ex.Message), CancellationToken.None).ConfigureAwait(false);
+ throw;
+ }
+
+ var section = new BasketTrialSection(BasketProtocol.TrialName, trial.Plan, trial.PlanHash, report, trial.Plan.Mode ?? BasketModes.AsLive);
+ var command = "anubis backtest baskets --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
+ + (repetitions == BasketProtocol.ControlRepetitions ? "" : " --control " + repetitions.ToString(CultureInfo.InvariantCulture))
+ + (seed == BasketProtocol.ControlSeed ? "" : " --seed " + seed.ToString(CultureInfo.InvariantCulture));
+ var file = Path.Combine(outDir, BasketReport.Strategy + ".md");
+ await File.WriteAllTextAsync(file, BasketReport.Markdown(new BasketReportInput(command, now, notes, trial.Plan.Costs ?? VenueCosts.Etoro, replica, control, section, null)))
+ .ConfigureAwait(false);
+
+ await output.WriteLineAsync((report.Passed ? "Esito: superato. " : "Esito: non superato. ") + BasketReport.Verdict(section)).ConfigureAwait(false);
+ await output.WriteLineAsync("Rapporto scritto in " + file).ConfigureAwait(false);
+ return 0;
+ }
+ catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
+ or ArgumentException or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException or System.Text.Json.JsonException
+ or SchemaException or System.Data.Common.DbException)
+ {
+ await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
+ return 1;
+ }
+ }
+
+ ///
+ /// The ECB rates of the seven currencies from the zip shared with anubis data ecb: downloaded again on every run;
+ /// with only the copy already in the research folder, and an error when there is none.
+ ///
+ private static async Task> RatesAsync(string research, bool offline, HttpMessageHandler? handler, IClock clock, TextWriter output)
+ {
+ if (offline && !File.Exists(Ecb.HistoryPath(research)))
+ {
+ throw new InvalidOperationException($"Manca lo storico dei cambi BCE già scaricato ({Ecb.HistoryPath(research)}): togli --offline o esegui prima «anubis data ecb».");
+ }
+
+ using var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
+ http.Timeout = TimeSpan.FromMinutes(5);
+ http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
+ var rates = await Ecb.LoadHistoryAsync(new ApiHttp(http, clock, Ecb.Source), research, offline, EcbCrosses.Rates, CancellationToken.None).ConfigureAwait(false);
+ if (rates.Count == 0)
+ {
+ throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
+ }
+
+ await output.WriteLineAsync(offline ? "Storico BCE letto dalla copia già scaricata." : "Storico BCE scaricato di nuovo.").ConfigureAwait(false);
+ return rates;
+ }
+
+ private static DateOnly Earlier(DateOnly a, DateOnly b) => a < b ? a : b;
+
+ private static async Task UsageAsync(TextWriter output, string problem)
+ {
+ await output.WriteLineAsync(problem).ConfigureAwait(false);
+ await output.WriteLineAsync(BacktestCommand.Usage).ConfigureAwait(false);
+ return 2;
+ }
+}
diff --git a/src/Anubis/Backtest/BasketProtocol.cs b/src/Anubis/Backtest/BasketProtocol.cs
new file mode 100644
index 0000000..ffd0f7c
--- /dev/null
+++ b/src/Anubis/Backtest/BasketProtocol.cs
@@ -0,0 +1,119 @@
+using Anubis.Baskets;
+using Anubis.Data;
+using Anubis.Strategies;
+
+namespace Anubis.Backtest;
+
+///
+/// What anubis backtest baskets computes (Phase 14, issue #131), fixed here before any result: the replica of
+/// appendix G of the research document on the 28 ECB crosses up to the document's end, the control against chance of G.5,
+/// and the plan of the trial of the basket engine. The trial runs «come dal vivo» with the eToro costs on a virtual register
+/// of 20,000 USD (plan, section 5) from the first ECB fixing to the chosen day, on a small grid in σ: generation A and B,
+/// averaging distance 4 and 10 σ, everything else as the document's base case of G.4.
+///
+public static class BasketProtocol
+{
+ /// The first ECB fixing: the trial starts here.
+ public static readonly DateOnly From = new(1999, 1, 4);
+
+ /// The end of the research document: the replica never reads past it, whatever the data hold.
+ public static readonly DateOnly ReplicaThrough = new(2026, 12, 2);
+
+ /// The virtual register of the forward test (plan, section 5), in USD.
+ public const decimal Capital = 20_000m;
+
+ /// The repetitions of the document's control (G.5).
+ public const int ControlRepetitions = 150;
+
+ /// The seed of the control when the command gives none: the document's date.
+ public const int ControlSeed = 20_261_202;
+
+ public const string Source = "Banca centrale europea, cambi di riferimento (eurofxref-hist.zip, conservato nella cartella di ricerca)";
+
+ /// What the trial is, in Italian, as the report names it.
+ public const string TrialName =
+ "Le 28 coppie della BCE dal 1999: generazione A (i cinque spread a due gambe) e B (i dieci cambi da soli), segnale sui logaritmi, misure in σ, uscita sulla media degli ingressi";
+
+ ///
+ /// The grid of the trial, written before any result: generation {A, B} × averaging distance {4, 10} σ; target 2.5 σ,
+ /// three averagings without growth, window 100, entry at z 2, profile Fedele, two baskets open, 0.01 lots per 10,000.
+ ///
+ public static IReadOnlyDictionary> Grid { get; } = new SortedDictionary>(StringComparer.Ordinal)
+ {
+ ["generation"] = [1m, 2m],
+ ["signal"] = [2m],
+ ["units"] = [2m],
+ ["target"] = [2.5m],
+ ["distance"] = [4m, 10m],
+ ["growth"] = [1m],
+ ["averagings"] = [3m],
+ ["window"] = [100m],
+ ["entry_z"] = [2m],
+ ["exit"] = [2m],
+ ["profile"] = [1m],
+ ["max_open"] = [2m],
+ ["lot"] = [0.01m],
+ };
+
+ /// The plan of the trial up to , written at , and its variants.
+ public static (TrialPlan Plan, int Variants) Plan(DateOnly to, DateTimeOffset now)
+ {
+ if (to <= From)
+ {
+ throw new ArgumentException($"La prova a panieri parte dal {From:dd/MM/yyyy}: la data di fine deve venire dopo.", nameof(to));
+ }
+
+ var family = BasketReversionFamily.Instance;
+ var plan = new TrialPlan(
+ family.Id,
+ family.Version,
+ Grid,
+ new TrialData(TrialSources.Research, EcbCrosses.Venue, [.. FxPairs.All.Select(p => p.Name)], From, to),
+ Capital,
+ [1m, 2m, 3m],
+ TrialValidation.Default,
+ TrialThresholds.Default,
+ BasketEngine.Version,
+ now)
+ {
+ Mode = BasketModes.AsLive,
+ Costs = VenueCosts.Etoro,
+ };
+ return (plan, ParameterGrid.Of(family, plan.Grid).Count);
+ }
+
+ /// The daily bars of the crosses from their first day to included, on the currency calendar.
+ public static BarDataset Dataset(IReadOnlyDictionary> crosses, DateOnly through)
+ {
+ ArgumentNullException.ThrowIfNull(crosses);
+ var first = crosses.Values.Where(b => b.Count > 0).Select(b => b[0].OpensAt).DefaultIfEmpty().Min();
+ if (first == default)
+ {
+ throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
+ }
+
+ return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, first, QualityChecks.Midnight(through).AddDays(1), crosses);
+ }
+
+ /// Where the data come from: source, fingerprint of every bar, period, days, pairs and the replica's cut.
+ public static BasketDataNotes Notes(IReadOnlyDictionary> crosses)
+ {
+ ArgumentNullException.ThrowIfNull(crosses);
+ var days = crosses.Values.SelectMany(b => b).Select(b => DateOnly.FromDateTime(b.OpensAt.UtcDateTime)).Distinct().Order().ToList();
+ if (days.Count == 0)
+ {
+ throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
+ }
+
+ var fingerprint = Dataset(crosses, days[^1]).Fingerprint();
+ return new BasketDataNotes(Source, fingerprint, days[0], days[^1], days.Count, crosses.Count(c => c.Value.Count > 0), ReplicaThrough);
+ }
+
+ /// The 15 rows of table G.4 on the crosses up to the document's end.
+ public static IReadOnlyList Replica(IReadOnlyList> series) =>
+ [.. ReplicaSettings.DocumentCases.Select(c => new BasketReplicaRow(c, StylisedReplica.Run(series, c.Settings)))];
+
+ /// The four rows of table G.5, each with shuffles from .
+ public static IReadOnlyList Control(IReadOnlyList> series, int repetitions, int seed) =>
+ [.. BasketReport.DocumentControl.Select(d => new BasketControlRow(d.Case, StylisedReplica.Control(series, d.Case.Settings, repetitions, seed), repetitions, seed, d.Share))];
+}
diff --git a/src/Anubis/Backtest/BasketReport.cs b/src/Anubis/Backtest/BasketReport.cs
index 6f360ba..5086a60 100644
--- a/src/Anubis/Backtest/BasketReport.cs
+++ b/src/Anubis/Backtest/BasketReport.cs
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Text;
using Anubis.Baskets;
using Anubis.Data;
+using Anubis.Strategies;
namespace Anubis.Backtest;
@@ -53,56 +54,57 @@ public sealed record BasketReportInput(
public static class BasketReport
{
/// The trial-registry id of the family (ADR 0026 point 10).
- public const string Strategy = "basket_reversion";
+ public const string Strategy = BasketReversionFamily.FamilyId;
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";
+ public const string LikeLive = BasketModes.AsLive;
/// The mode with the document's rules only: replication and experiments, no verdict.
- public const string ToTheLetter = "alla_lettera";
+ public const string ToTheLetter = BasketModes.AsDocument;
/// Note reason of a leg left alone when a mandatory stop closed the other one.
- public const string OrphanLeg = "orphan_leg";
+ public const string OrphanLeg = BasketReasons.OrphanLeg;
/// Note reason of a liquidation for want of margin.
- public const string Liquidation = "liquidation";
+ public const string Liquidation = BasketReasons.Liquidation;
/// Note reason of the 9% stop on the account value.
- public const string AccountStop = "account_stop";
+ public const string AccountStop = BasketReasons.AccountStop;
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"),
+ (BasketReasons.Target, "obiettivo raggiunto"),
+ (BasketReasons.StopBasket, "stop del paniere"),
(AccountStop, "stop sul valore del conto (9%)"),
- ("mandatory_stop", "stop obbligatorio della piattaforma"),
+ (BasketReasons.MandatoryStop, "stop obbligatorio della piattaforma"),
(OrphanLeg, "gamba rimasta sola dopo uno stop obbligatorio"),
(Liquidation, "chiusura d'ufficio per margine insufficiente"),
- ("end", "fine del periodo"),
+ (BasketReasons.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",
+ [BasketReasons.GateOpenLoss] = "perdita aperta oltre il 2%: nessun paniere nuovo",
+ [BasketReasons.PausedUntilNextDay] = "fermo dopo lo stop del 9% fino al cambio di data del server",
+ [BasketReasons.DailyLossBlock] = "perdita del giorno oltre il 2%: niente ingressi né mediazioni per 24 ore",
+ [BasketReasons.HalfSize] = "dimensione dimezzata (perdita della settimana o calo dal massimo)",
+ [BasketReasons.BelowVenueMinimum] = "livello sotto il minimo della piattaforma",
+ [BasketReasons.MarginLimit] = "margine impegnato oltre il 40%",
+ [BasketReasons.PositionLimit] = "troppe posizioni aperte per la piattaforma",
+ [BasketReasons.OppositePosition] = "posizione opposta sullo stesso strumento",
+ [BasketReasons.CurrencyExposure] = "esposizione su una valuta oltre il limite",
+ [BasketReasons.CostRule] = "obiettivo sotto tre volte il costo del paniere",
+ [BasketReasons.RvolFilter] = "volatilità recente oltre il doppio del normale",
+ [BasketReasons.CorrelationLow] = "correlazione sotto 0,6",
+ [BasketReasons.SwitchTripped] = "interruttore scattato (calo del 15%)",
+ [BasketReasons.MaxOpenBaskets] = "già aperto il numero massimo di panieri",
+ [BasketReasons.ClockWindow] = "fuori dalla finestra oraria",
};
///
@@ -156,8 +158,10 @@ public static class BasketReport
return b.ToString();
}
- private static string Verdict(BasketTrialSection trial)
+ /// The verdict of a judged trial in one Italian sentence: what the report and the console say.
+ public static string Verdict(BasketTrialSection trial)
{
+ ArgumentNullException.ThrowIfNull(trial);
var mode = ModeName(trial.Mode);
if (trial.Report.Passed)
{
@@ -378,7 +382,7 @@ public static class BasketReport
b.AppendLine();
var closed = baskets.Count(x => x.ExitReason is not null);
- var atTarget = baskets.Count(x => x.ExitReason == "target");
+ var atTarget = baskets.Count(x => x.ExitReason == BasketReasons.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();
}
@@ -388,16 +392,19 @@ public static class BasketReport
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(Text($"- Posizioni chiuse dallo stop obbligatorio della piattaforma: {(r.Notes.TryGetValue(BasketReasons.MandatoryStop, out var stopped) ? stopped : 0)}."));
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();
+ var refusals = r.Notes.Where(n => n.Key is not (OrphanLeg or Liquidation or AccountStop or BasketReasons.MandatoryStop)).ToList();
+ b.AppendLine("**Ingressi e mediazioni fermati o annotati**").AppendLine();
if (refusals.Count == 0)
{
b.AppendLine("Nessuno.").AppendLine();
return;
}
+ b.AppendLine("Con il profilo Fedele la regola dei tre costi e il limite di esposizione per valuta sono solo annotati: l'ingresso si fa lo stesso. Una dimensione dimezzata è un ingresso fatto più piccolo.")
+ .AppendLine();
b.AppendLine("| Motivo | Volte |").AppendLine("|---|---:|");
foreach (var (code, n) in refusals.OrderByDescending(x => x.Value).ThenBy(x => x.Key, StringComparer.Ordinal))
{
@@ -418,8 +425,14 @@ public static class BasketReport
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.");
+
+ // The engine's own lines already say that the account is not read and how the estimated financing is taken.
+ if (input.Trial is null)
+ {
+ 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.");
}
diff --git a/src/Anubis/Backtest/BasketTrialEngine.cs b/src/Anubis/Backtest/BasketTrialEngine.cs
index f98819a..e35bfdf 100644
--- a/src/Anubis/Backtest/BasketTrialEngine.cs
+++ b/src/Anubis/Backtest/BasketTrialEngine.cs
@@ -135,7 +135,7 @@ public sealed class BasketTrialEngine : ITrialEngine
+ "attorno al cambio con il differenziale della tabella dei costi.");
}
- result.Add(string.Create(italian, $"Costi di {_costs.Venue} al {_costs.AsOf:d MMMM yyyy}: {_costs.Source}."));
+ result.Add(string.Create(italian, $"Costi di {(_costs.Venue == "etoro" ? "eToro" : _costs.Venue)} al {_costs.AsOf:d MMMM yyyy}: {_costs.Source}."));
if (_costs.Pairs.Any(p => p.FinancingEstimated))
{
result.Add("Il finanziamento notturno delle coppie che il documento non dà è stimato con prudenza: il costo più alto fra quelli noti, sui due lati.");
diff --git a/tests/Anubis.Tests/BasketCommandTests.cs b/tests/Anubis.Tests/BasketCommandTests.cs
new file mode 100644
index 0000000..639c1a7
--- /dev/null
+++ b/tests/Anubis.Tests/BasketCommandTests.cs
@@ -0,0 +1,201 @@
+using System.IO.Compression;
+using Anubis.Backtest;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Server;
+
+namespace Anubis.Tests;
+
+///
+/// "anubis backtest baskets" (Phase 14, issue #131): from the command line, on the database of this run (SQLite here,
+/// PostgreSQL in CI), with the ECB history of the research document already in the research folder and no network. The
+/// plan is written before the trial, read back and run only when it is still the one written; every run counts the earlier
+/// ones; the report is written whatever the verdict.
+///
+[TestClass]
+public sealed class BasketCommandTests
+{
+ private const string EcbFile = "free/ecb-hist-1999-2026-12-02.csv";
+
+ private static readonly DateOnly To = new(2001, 12, 31);
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task ABasketTrialRunsFromTheCommandLineWithItsPlanIntact()
+ {
+ var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
+ await using var engine = postgres;
+ var data = TempFolder.Create("baskets");
+ var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
+ try
+ {
+ var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
+ await using var db = Database.Open(config.Db!);
+ await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
+ Directory.CreateDirectory(config.Data.Research);
+ await File.WriteAllBytesAsync(Ecb.HistoryPath(config.Data.Research), EcbZip()).ConfigureAwait(false);
+ var outDir = Path.Combine(data, "out");
+ var report = Path.Combine(outDir, BasketReport.Strategy + ".md");
+ var store = new TrialStore(db, clock);
+ var network = new FakeHttp();
+ string[] args = ["baskets", "--offline", "--to", "2001-12-31", "--control", "5", "--out", outDir, "--platform", "docker", "--data-dir", data];
+
+ async Task<(int Code, string Text)> RunAsync()
+ {
+ using var output = new StringWriter();
+ var code = await BasketCommand.RunAsync([.. args.Skip(1)], output, env, network, clock).ConfigureAwait(false);
+ clock.Advance(TimeSpan.FromMinutes(1));
+ return (code, output.ToString());
+ }
+
+ // The first run: replica, control and trial, the plan written and judged as it was written.
+ var written = BasketProtocol.Plan(To, clock.UtcNow).Plan;
+ var (code, text) = await RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(0, code, text);
+ StringAssert.Contains(text, "13 su 13 righe vincolanti dentro la tolleranza");
+ StringAssert.Contains(text, "Esito: ");
+ StringAssert.Contains(text, "Rapporto scritto in " + report);
+ var markdown = await File.ReadAllTextAsync(report).ConfigureAwait(false);
+ StringAssert.Contains(markdown, "**Esito: ");
+ StringAssert.Contains(markdown, "13 righe vincolanti su 13 dentro la tolleranza.");
+ StringAssert.Contains(markdown, "`anubis backtest baskets --to 2001-12-31 --control 5`");
+ StringAssert.Contains(markdown, "| 5 | 20261202 |");
+ Assert.AreEqual(0, network.Requests.Count, "offline with the cached history: no request");
+ Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".outcome.json")), "no outcome file for the basket family");
+
+ var first = (await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
+ Assert.AreEqual(TrialStatuses.Done, first.Status, first.Error);
+ Assert.IsTrue(first.PlanIntact);
+ Assert.AreEqual(TrialPlan.Hash(written.ToJson()), first.PlanHash);
+ Assert.AreEqual(written.ToJson(), first.Plan.ToJson());
+ Assert.AreEqual(BasketModes.AsLive, first.Plan.Mode);
+ Assert.AreEqual(VenueCosts.Etoro.Fingerprint(), first.Plan.Costs!.Fingerprint());
+ Assert.AreEqual(BasketEngine.Version, first.Plan.Engine);
+ Assert.AreEqual(BasketProtocol.Capital, first.Plan.InitialCapital);
+ Assert.AreEqual(4, first.Variants);
+ var judged = BacktestReport.FromJson((await store.ReportJsonAsync(first.Id, CancellationToken.None).ConfigureAwait(false))!);
+ Assert.AreEqual(first.PlanHash, judged.PlanHash);
+ Assert.AreEqual(4, judged.TrialsCounted);
+ StringAssert.Contains(markdown, "`" + first.PlanHash[..12] + "`");
+
+ // The same plan again: accepted, a trial of its own, and the first one counts in its deflated Sharpe.
+ (code, text) = await RunAsync().ConfigureAwait(false);
+ Assert.AreEqual(0, code, text);
+ StringAssert.Contains(text, "prove precedenti contate: 1");
+ var trials = await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false);
+ Assert.HasCount(2, trials);
+ Assert.IsTrue(trials.All(t => t.Status == TrialStatuses.Done && t.PlanIntact));
+ Assert.AreEqual(8, BacktestReport.FromJson((await store.ReportJsonAsync(trials[0].Id, CancellationToken.None).ConfigureAwait(false))!).TrialsCounted);
+ var kept = await File.ReadAllTextAsync(report).ConfigureAwait(false);
+
+ // A plan changed in the register after it was written: refused, recorded as failed, the report left as it was. First
+ // its hash no longer matches; then the grid is changed and the hash written again to match.
+ string WiderGrid()
+ {
+ var grid = new SortedDictionary>(BasketProtocol.Grid.ToDictionary(), StringComparer.Ordinal) { ["distance"] = [4m, 12m] };
+ var json = (BasketProtocol.Plan(To, clock.UtcNow).Plan with { Grid = grid }).ToJson();
+ return $"SET plan = '{json.Replace("'", "''", StringComparison.Ordinal)}', plan_hash = '{TrialPlan.Hash(json)}'";
+ }
+
+ (Func Sql, string Error)[] tampers =
+ [
+ (() => "SET plan_hash = '0'", "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."),
+ (WiderGrid, "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."),
+ ];
+ foreach (var (sql, error) in tampers)
+ {
+ await TamperAsync(db, sql()).ConfigureAwait(false);
+ (code, text) = await RunAsync().ConfigureAwait(false);
+ await UntamperAsync(db).ConfigureAwait(false);
+ Assert.AreEqual(1, code, text);
+ StringAssert.Contains(text, "Non riuscito: " + error);
+ var refused = (await store.ListAsync(1, CancellationToken.None).ConfigureAwait(false))[0];
+ Assert.AreEqual(TrialStatuses.Failed, refused.Status);
+ Assert.AreEqual(error, refused.Error);
+ Assert.AreEqual(kept, await File.ReadAllTextAsync(report).ConfigureAwait(false), "a refused trial writes no report");
+ }
+
+ Assert.AreEqual(2, (await store.PriorAsync(BasketReport.Strategy, Guid.Empty, CancellationToken.None).ConfigureAwait(false)).Trials, "refused trials are not counted");
+ }
+ finally
+ {
+ Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
+ TempFolder.Delete(data);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task OfflineWithoutTheEcbHistoryTheCommandStopsInItalian()
+ {
+ var data = TempFolder.Create("baskets-offline");
+ try
+ {
+ var env = ServerHarness.DockerSqlite();
+ var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
+ var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
+ await using (var db = Database.Open(config.Db!))
+ {
+ await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
+ }
+
+ var network = new FakeHttp();
+ using var output = new StringWriter();
+ Assert.AreEqual(1, await BasketCommand.RunAsync(["--offline", "--platform", "docker", "--data-dir", data], output, env, network, clock).ConfigureAwait(false));
+ StringAssert.Contains(output.ToString(), "Non riuscito: Manca lo storico dei cambi BCE già scaricato");
+ Assert.AreEqual(0, network.Requests.Count);
+
+ using var usage = new StringWriter();
+ Assert.AreEqual(2, await BacktestCommand.RunAsync(["baskets", "--control", "zero", "--platform", "docker", "--data-dir", data], usage, env).ConfigureAwait(false));
+ StringAssert.Contains(usage.ToString(), "base|candidates|baskets");
+ }
+ finally
+ {
+ Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
+ TempFolder.Delete(data);
+ }
+ }
+
+ /// A trigger that changes every plan as soon as it is written: someone touching the register behind the command.
+ private static async Task TamperAsync(Database db, string set)
+ {
+ if (db.Engine == Anubis.Platform.DbEngine.Postgres)
+ {
+ await db.WriteAsync(s => s.ExecuteAsync(
+ $"CREATE FUNCTION tamper_plan() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; RETURN NULL; END $$",
+ CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
+ await db.WriteAsync(s => s.ExecuteAsync("CREATE TRIGGER tamper AFTER INSERT ON backtest_trials FOR EACH ROW EXECUTE FUNCTION tamper_plan()", CancellationToken.None),
+ CancellationToken.None).ConfigureAwait(false);
+ return;
+ }
+
+ await db.WriteAsync(s => s.ExecuteAsync($"CREATE TRIGGER tamper AFTER INSERT ON backtest_trials BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; END",
+ CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
+ }
+
+ private static async Task UntamperAsync(Database db)
+ {
+ if (db.Engine == Anubis.Platform.DbEngine.Postgres)
+ {
+ await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper ON backtest_trials", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
+ await db.WriteAsync(s => s.ExecuteAsync("DROP FUNCTION tamper_plan()", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
+ return;
+ }
+
+ await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
+ }
+
+ /// The fixture of the research document's ECB history, zipped as the ECB serves it and as the cache keeps it.
+ 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(EcbFile));
+ }
+
+ return zip.ToArray();
+ }
+}
diff --git a/tests/Anubis.Tests/BasketReportTests.cs b/tests/Anubis.Tests/BasketReportTests.cs
index 4c3bc0f..dd0f698 100644
--- a/tests/Anubis.Tests/BasketReportTests.cs
+++ b/tests/Anubis.Tests/BasketReportTests.cs
@@ -152,6 +152,38 @@ public sealed class BasketReportTests
StringAssert.Contains(none, "Stop sul valore del conto: 0");
}
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void EveryCodeOfTheEngineHasAnItalianLabel()
+ {
+ var trial = _trial.Value;
+ var notes = new Dictionary(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,
+ };
+ var text = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes } })), "## Prova del motore a panieri");
+ StringAssert.Contains(text, "| troppe posizioni aperte per la piattaforma | 3 |");
+ StringAssert.Contains(text, "| fuori dalla finestra oraria | 4 |");
+ 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);
+ }
+
[TestMethod]
[TestCategory(Category.Unit)]
public void TheComparisonIsZeroNeverBuyAndHold()
@@ -175,6 +207,9 @@ public sealed class BasketReportTests
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");