Fase 13 — Campionato: unità di lavoro, piano e statistica #188

Merged
Alby96 merged 6 commits from fase-13 into main 2026-12-04 15:53:44 +01:00
31 changed files with 4776 additions and 225 deletions

No files matched your search

+2
View File
@@ -264,6 +264,8 @@ Per ripartire, togli il file e conferma dalla pagina Rischio.
**Parametri delle strategie.** Non si toccano dall'interfaccia: sono quelli con cui ogni strategia è stata provata. Un cambio è una nuova prova in Laboratorio. Si cambiano invece capitale, ripartizione, limiti di rischio, regole sulle notizie e del modello. **Parametri delle strategie.** Non si toccano dall'interfaccia: sono quelli con cui ogni strategia è stata provata. Un cambio è una nuova prova in Laboratorio. Si cambiano invece capitale, ripartizione, limiti di rischio, regole sulle notizie e del modello.
**Operai del Laboratorio.** In Impostazioni → Sistema dici quanti calcoli di una prova del Laboratorio girano insieme (le prove restano una alla volta): uno all'inizio, al massimo uno in meno dei processori. Alzalo solo dopo averne misurato l'effetto, perché il Laboratorio non deve togliere tempo al trading; vale dalla prossima prova. Se il bot si ferma a metà di una prova, alla ripartenza rifà solo i calcoli che non aveva finito; li rifà tutti se nel frattempo sono cambiati i dati della prova o il bot è stato aggiornato, così una prova non mescola mai calcoli fatti su dati o versioni diversi.
**Notizie, calendario e trimestrali: solo misurate o attive.** In Impostazioni → Notizie l'interruttore sopra le cinque regole dice se agiscono. «Solo misurate» è il predefinito: le decisioni guardano solo i prezzi, e ogni regola scrive in ombra che cosa avrebbe fatto. «Attive» è il comportamento delle versioni precedenti: le regole accese possono fermare o rinviare un acquisto. Il bot non le riaccende mai da solo. Prima di farlo guarda nel Laboratorio la tabella delle regole in ombra: una regola merita di agire solo dopo almeno 6 mesi di misura, almeno 30 ingressi cambiati e un effetto tutto sopra lo zero (la riga dice «Criterio raggiunto»). Per riaccenderne una sola, spegni le altre righe e poi scegli «Attive». Passare da «Attive» a «Solo misurate» toglie protezioni: se una strategia usa soldi veri chiede la frase, la password e, se l'hai attivato, il codice a sei cifre, come quando spegni una regola. Ogni cambio lascia una riga nel Diario. Con le regole solo misurate un modello in carica che usa indizi delle notizie, delle trimestrali o di paura e avidità viene messo da parte subito. La domenica ne addestra uno senza, che prende il posto solo dopo aver vinto i confronti con il modello in carica; nel frattempo nessun modello conta. **Notizie, calendario e trimestrali: solo misurate o attive.** In Impostazioni → Notizie l'interruttore sopra le cinque regole dice se agiscono. «Solo misurate» è il predefinito: le decisioni guardano solo i prezzi, e ogni regola scrive in ombra che cosa avrebbe fatto. «Attive» è il comportamento delle versioni precedenti: le regole accese possono fermare o rinviare un acquisto. Il bot non le riaccende mai da solo. Prima di farlo guarda nel Laboratorio la tabella delle regole in ombra: una regola merita di agire solo dopo almeno 6 mesi di misura, almeno 30 ingressi cambiati e un effetto tutto sopra lo zero (la riga dice «Criterio raggiunto»). Per riaccenderne una sola, spegni le altre righe e poi scegli «Attive». Passare da «Attive» a «Solo misurate» toglie protezioni: se una strategia usa soldi veri chiede la frase, la password e, se l'hai attivato, il codice a sei cifre, come quando spegni una regola. Ogni cambio lascia una riga nel Diario. Con le regole solo misurate un modello in carica che usa indizi delle notizie, delle trimestrali o di paura e avidità viene messo da parte subito. La domenica ne addestra uno senza, che prende il posto solo dopo aver vinto i confronti con il modello in carica; nel frattempo nessun modello conta.
Chi aggiorna da una versione precedente trova nel Diario una riga sola: da questa versione le regole sono solo misurate. Le decisioni prese prima restano come erano, con le regole attive. Chi aggiorna da una versione precedente trova nel Diario una riga sola: da questa versione le regole sono solo misurate. Le decisioni prese prima restano come erano, con le regole attive.
+21 -13
View File
@@ -21,8 +21,8 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
| 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Completata (pubblicazione e prova su Unraid in attesa dell'utente) | | 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Completata (pubblicazione e prova su Unraid in attesa dell'utente) |
| 10 | [Nuova rotta: solo Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/37) | Completata (prova di durata dal container in attesa dell'utente) | | 10 | [Nuova rotta: solo Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/37) | Completata (prova di durata dal container in attesa dell'utente) |
| 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Completata (misura sulle azioni in attesa delle chiavi Alpaca e Finnhub) | | 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Completata (misura sulle azioni in attesa delle chiavi Alpaca e Finnhub) |
| 12 | [Dati e matematica dei panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/80) | Completata (unione e tag dopo il sì dell'utente; i formati dei file a un minuto delle valute da verificare sul primo file vero) | | 12 | [Dati e matematica dei panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/80) | Completata (i formati dei file a un minuto delle valute da verificare sul primo file vero) |
| 13 | [Campionato: unità di lavoro, piano e statistica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/81) | Da fare | | 13 | [Campionato: unità di lavoro, piano e statistica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/81) | Completata (unione e tag dopo il sì dell'utente) |
| 14 | [Motore a panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/82) | Da fare | | 14 | [Motore a panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/82) | Da fare |
| 15 | [Campionato: concorrenti e classifica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/83) | Da fare | | 15 | [Campionato: concorrenti e classifica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/83) | Da fare |
| 16 | [Campionato: combinazioni e primo verdetto](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/84) | Da fare | | 16 | [Campionato: combinazioni e primo verdetto](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/84) | Da fare |
@@ -385,20 +385,28 @@ Si costruisce il giudice prima dei concorrenti. Più strategie si provano, più
**Lavori** **Lavori**
- [ ] [#122](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/122) Unità di lavoro e operai - [x] [#122](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/122) Unità di lavoro e operai
- [ ] [#123](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/123) Piano del campionato, immutabile e con impronta come `TrialPlan` - [x] [#123](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/123) Piano del campionato, immutabile e con impronta come `TrialPlan`
- [ ] [#124](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/124) Statistica in `Backtest/TournamentStatistics.cs`, tutta in casa - [x] [#124](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/124) Statistica in `Backtest/TournamentStatistics.cs`, tutta in casa
- [ ] [#125](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/125) Tempi del campionato - [x] [#125](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/125) Tempi del campionato
- [ ] [#126](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/126) Chiusura della fase, revisione indipendente e tag `fase-13` (dopo il sì dell'utente) - [x] [#126](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/126) Chiusura della fase, revisione indipendente e tag `fase-13` (dopo il sì dell'utente)
**Criteri di accettazione** **Criteri di accettazione**
- [ ] `Judge(Variants())` dà lo stesso JSON di `Run`; il test d'oro esistente `TheReferenceRunOfTheAverageCrossDoesNotMove` resta verde; quattro operai danno il rapporto di uno; dopo un'interruzione le unità finite non si rifanno. - [x] `Judge(Variants())` dà lo stesso JSON di `Run`; il test d'oro esistente `TheReferenceRunOfTheAverageCrossDoesNotMove` resta verde; quattro operai danno il rapporto di uno; dopo un'interruzione le unità finite non si rifanno.
- [ ] Il piano è scritto prima di ogni risultato e non cambia; il tratto finale di dati si legge una volta sola. - [x] Il piano è scritto prima di ogni risultato e non cambia; il tratto finale di dati si legge una volta sola.
- [ ] Il surrogato conserva i valori assoluti dei rendimenti di ogni giorno e le correlazioni; una serie con memoria costruita a mano la perde. - [x] Il surrogato conserva i valori assoluti dei rendimenti di ogni giorno e le correlazioni; una serie con memoria costruita a mano la perde.
- [ ] Su una serie che rientra (dimezzamento a 50 barre) una regola di rientro supera il controllo; su un cammino casuale con deriva una regola di tendenza in solo acquisto non lo supera. - [x] Su una serie che rientra (dimezzamento a 50 barre) una regola di rientro supera il controllo; su un cammino casuale con deriva una regola di tendenza in solo acquisto non lo supera.
- [ ] 28 serie identiche valgono una scommessa; una strategia senza vantaggio provata in 100 varianti resta sotto DSR 0,90; il PBO comune sul rumore è circa 0,5. - [x] 28 serie identiche valgono una scommessa; una strategia senza vantaggio provata in 100 varianti resta sotto DSR 0,90; il PBO comune sul rumore è circa 0,5.
- [ ] Campo costruito apposta, con due concorrenti che hanno un vantaggio e quattro di rumore: passano solo i primi due. - [x] Campo costruito apposta, con due concorrenti che hanno un vantaggio e quattro di rumore: passano solo i primi due.
Prove:
- `TrialUnitTests`: `Judge(Variants())` dà il JSON di `Run` sui tre rapporti d'oro; quattro operai danno il rapporto di uno; una corsa ricaricata dalla sua unità dà lo stesso rapporto; con un operaio il motore è chiamato nell'ordine di prima; dopo un'interruzione si rifanno solo le unità rimaste in corso, e quelle calcolate su dati diversi; l'impostazione degli operai. `TheReferenceRunOfTheAverageCrossDoesNotMove` e i tre rapporti d'oro della Fase 12 non sono cambiati.
- `SurrogateTests`: la copia senza regolarità conserva il valore assoluto di ogni rendimento e le correlazioni; una serie con memoria la perde; su una serie che rientra (dimezzamento a 50 barre) la regola di rientro supera il controllo con 200 copie; su un cammino con deriva la regola di tendenza in solo acquisto no; gli strumenti con azioni societarie sono rifiutati.
- `TournamentStatisticsTests`: 28 serie identiche valgono una scommessa; una strategia senza vantaggio provata in 100 varianti resta sotto 0,90 con diversi semi; la probabilità di sovra-adattamento comune sul rumore è circa 0,5; 8 finalisti danno 87 combinazioni; asticella, varianza del campo, calendari allineati, intervallo.
- `TournamentTests`: il piano e le prove dei concorrenti si scrivono insieme prima di ogni risultato e non cambiano; il tratto finale si apre una volta sola e solo per i finalisti; un campo con due concorrenti con un vantaggio e quattro di rumore, 200 copie, fa passare solo i primi due; un giudizio ripreso non rifà le copie già fatte; un piano illeggibile o cambiato, o dati di ricerca cambiati dopo la prova, fanno fallire il campionato senza fermare la coda.
Scelte nell'ADR 0029. Da sapere: lo Sharpe corretto comune alza l'asticella anche con i concorrenti buoni; se molte varianti del campo hanno un vantaggio, quelle buone faticano a passare (ADR 0029, Conseguenze).
## Fase 14 — Motore a panieri (solo ricerca, nessun conto) ## Fase 14 — Motore a panieri (solo ricerca, nessun conto)
+11 -2
View File
@@ -4,7 +4,7 @@ Aggiornato: 2026-12-04
## Fase corrente ## Fase corrente
**Fase 12 — Dati e matematica dei panieri: completata** sul branch `fase-12`, con la pull request aperta: unione in `main` e tag `fase-12` aspettano il sì dell'utente. Il giudice delle prove ha un giunto per un secondo motore, la matematica dei panieri del documento è scritta e provata numero per numero, le 28 coppie di valute escono dai cambi della BCE e i file a un minuto si importano. Nessuna strategia nuova gira: è tutto ricerca. La Fase 11 è unita con il tag `fase-11`. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. **Fase 13 — Campionato: unità di lavoro, piano e statistica: completata** sul branch `fase-13`, con la pull request aperta: unione in `main` e tag `fase-13` aspettano il sì dell'utente. Il giudice del campionato è pronto prima dei concorrenti: ogni prova del Laboratorio è fatta di unità che si riprendono dopo un'interruzione e girano su più operai, un campionato ha un piano immutabile con impronta e un tratto finale di dati che si legge una volta sola, e ogni finalista deve battere almeno 190 copie su 200 dei suoi prezzi senza regolarità. È provato su serie costruite apposta: nessun concorrente vero ha ancora gareggiato (Fase 15). Le Fasi 11 e 12 sono unite con i loro tag. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
**Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023, applicato dalla Fase 11 con l'ADR 0027): notizie, calendario e trimestrali si misurano in ombra. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale. **Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023, applicato dalla Fase 11 con l'ADR 0027): notizie, calendario e trimestrali si misurano in ombra. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale.
@@ -154,13 +154,20 @@ Aggiornato: 2026-12-04
- Barre più corte di un giorno (#120): durate da 15 e 30 minuti, 1, 4 e 8 ore; aggregazione esatta senza riempire buchi; calendari 24×7, 24×5 e di borsa; insieme di barre a colonne con orologio comune. `anubis data ecb` ricava le 28 coppie dai cambi BCE dal 1999 (USDJPY = 176,79 / 1,1193 sul giorno di prova); `anubis data fx` importa i file a un minuto di Dukascopy e HistData e costruisce le barre a 15 minuti. - Barre più corte di un giorno (#120): durate da 15 e 30 minuti, 1, 4 e 8 ore; aggregazione esatta senza riempire buchi; calendari 24×7, 24×5 e di borsa; insieme di barre a colonne con orologio comune. `anubis data ecb` ricava le 28 coppie dai cambi BCE dal 1999 (USDJPY = 176,79 / 1,1193 sul giorno di prova); `anubis data fx` importa i file a un minuto di Dukascopy e HistData e costruisce le barre a 15 minuti.
- Revisione indipendente con verifica a contraddittorio: 5 problemi confermati e corretti (z-score su una finestra piatta, storico BCE rotto che faceva cadere il comando o sostituiva la copia buona, minuti oltre 59 in un fuso fisso, messaggio senza motivo per un file tutto nel fine settimana, una frase dell'ADR), 7 respinti. La correzione importante è stata provata rompendola apposta. - Revisione indipendente con verifica a contraddittorio: 5 problemi confermati e corretti (z-score su una finestra piatta, storico BCE rotto che faceva cadere il comando o sostituiva la copia buona, minuti oltre 59 in un fuso fisso, messaggio senza motivo per un file tutto nel fine settimana, una frase dell'ADR), 7 respinti. La correzione importante è stata provata rompendola apposta.
- **Fase 13 — Campionato: unità di lavoro, piano e statistica** (#122–#125, ADR 0029, nessun pacchetto nuovo; solo ricerca):
- Unità di lavoro e operai (#122): `TrialRunner.Run` = `Judge(Variants())`, in due tempi; ogni esecuzione del motore è un'unità registrata (`tournament_units`) con il suo esito compresso e l'impronta degli ingressi, così dopo un'interruzione si rifanno solo le unità in corso o calcolate su dati diversi. Le unità girano su un gruppo di thread a priorità bassa; l'impostazione `laboratory.workers` (Impostazioni → Sistema, predefinita 1) dice quanti. I tre rapporti d'oro non sono cambiati; quattro operai danno il rapporto di uno.
- Statistica (#124, `Backtest/TournamentStatistics.cs`): conteggio comune delle prove (campo, combinazioni, registro, le 27 da riga di comando), asticella, varianza del campo sugli Sharpe annui, probabilità di sovra-adattamento comune su un calendario solo, numero effettivo di scommesse, intervallo a blocchi. Il generatore a seme fisso è passato nel nucleo senza cambiare un bit.
- Controllo contro il caso: copie dei prezzi in cui ogni giorno tutti gli strumenti cambiano segno insieme, centrate per chi è solo in acquisto (`Backtest/Surrogates.cs`); 200 copie, il finalista passa se al più il 5% fa altrettanto bene.
- Piano e tempi del campionato (#123, #125): piano immutabile con impronta, scritto con le prove dei concorrenti prima di ogni risultato; finalisti uno per gruppo e mercato, al più 8; tratto finale aperto una volta sola, solo per i finalisti; sette controlli tutti necessari. Combinazioni e prove di stress sono già nel piano e si eseguono nella Fase 16.
- Revisione indipendente con verifica a contraddittorio: 4 problemi confermati e corretti (un errore nel giudizio di un campionato fermava la coda del Laboratorio, unità riprese su dati o programma diversi, piano di un concorrente cambiato non controllato, una frase delle Impostazioni), 8 respinti; un quinto, trovato correggendo, è chiuso anch'esso: dati di ricerca cambiati tra la prova di un concorrente e il giudizio. Le correzioni hanno ciascuna una prova che falliva prima.
## In corso ## In corso
Nulla. Nulla.
## Prossimo passo ## Prossimo passo
1. Il sì dell'utente per unire la pull request della Fase 12 e mettere il tag `fase-12`. Poi la **Fase 13 — Campionato: unità di lavoro, piano e statistica**, in una nuova sessione, sul branch `fase-13` da `main`. Letture: la riga della Fase 13 nella tabella dell'ADR 0021 (punto 3) e la Fase 13 del piano. 1. Il sì dell'utente per unire la pull request della Fase 13 e mettere il tag `fase-13`. Poi la **Fase 14 — Motore a panieri**, in una nuova sessione, sul branch `fase-14` da `main`. Letture: la riga della Fase 14 nella tabella dell'ADR 0021 (punto 3), la Fase 14 del piano e gli ADR 0028 e 0029.
2. L'utente decide se pubblicare l'immagine (prossimo tag `v*`) e prova il template su Unraid seguendo `docs/MANUALE.md`. 2. L'utente decide se pubblicare l'immagine (prossimo tag `v*`) e prova il template su Unraid seguendo `docs/MANUALE.md`.
3. Il rapporto della prova di durata (#55): si raccoglie dal container sul server di casa (48 ore a `--memory=2g`), si analizza, si salva in `docs/diagnostica/` e si chiude #55. 3. Il rapporto della prova di durata (#55): si raccoglie dal container sul server di casa (48 ore a `--memory=2g`), si analizza, si salva in `docs/diagnostica/` e si chiude #55.
4. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. 4. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
@@ -172,6 +179,8 @@ Nulla.
- **Gli adapter non hanno mai parlato con un conto di prova vero**: la batteria di conformità passa solo sulle risposte d'esempio della documentazione. Ordini, stop, ricostruzione dopo un ripristino e codici di una chiave rifiutata vanno verificati dal vivo. - **Gli adapter non hanno mai parlato con un conto di prova vero**: la batteria di conformità passa solo sulle risposte d'esempio della documentazione. Ordini, stop, ricostruzione dopo un ripristino e codici di una chiave rifiutata vanno verificati dal vivo.
- **Crypto sempre nel simulatore interno**: manca la scelta per strategia tra simulatore e conto di prova (SPEC 7.1), quindi lo scostamento vero delle crypto non si può misurare. - **Crypto sempre nel simulatore interno**: manca la scelta per strategia tra simulatore e conto di prova (SPEC 7.1), quindi lo scostamento vero delle crypto non si può misurare.
- **Incidenti critici**: il requisito di 12.3 conta solo l'arresto per perdita del 15%, la specifica chiede di più. - **Incidenti critici**: il requisito di 12.3 conta solo l'arresto per perdita del 15%, la specifica chiede di più.
- **Lo Sharpe corretto comune alza l'asticella anche con i concorrenti buoni**: se una buona parte del campo ha un vantaggio, la varianza del campo cresce e quelli buoni faticano a passare (ADR 0029, Conseguenze). È la parte prudente; va guardato al primo campionato vero.
- **Il controllo contro il caso non vale ancora per le azioni** (frazionamenti e dividendi): si rivede nella Fase 23.
- **Prova di durata (#55)** non chiusa: manca il rapporto, che ora si raccoglie dal container. - **Prova di durata (#55)** non chiusa: manca il rapporto, che ora si raccoglie dal container.
- **La logica del documento della nuova rotta**, misurata dal documento stesso, è negativa o non si distingue dal caso. Il piano mette le prove davanti agli ordini, e l'esito più probabile è che resti una prova sul Demo, fuori dai totali. - **La logica del documento della nuova rotta**, misurata dal documento stesso, è negativa o non si distingue dal caso. Il piano mette le prove davanti agli ordini, e l'esito più probabile è che resti una prova sul Demo, fuori dai totali.
- **I file a un minuto delle valute** (Dukascopy, HistData) si leggono secondo formati scritti da conoscenza generale, con campioni costruiti a mano: vanno verificati sul primo file vero. Senza quei file le valute si provano solo sui cambi giornalieri della BCE, che sono prezzi di riferimento e non prezzi a cui si negozia. - **I file a un minuto delle valute** (Dukascopy, HistData) si leggono secondo formati scritti da conoscenza generale, con campioni costruiti a mano: vanno verificati sul primo file vero. Senza quei file le valute si provano solo sui cambi giornalieri della BCE, che sono prezzi di riferimento e non prezzi a cui si negozia.
+88
View File
@@ -0,0 +1,88 @@
# 0029 — Scelte della Fase 13 (campionato: unità di lavoro, piano e statistica)
Data: 2026-12-04 · Stato: accettata · Applica l'ADR 0026 per il giudice del campionato · Precisa SPEC 12.1 e 12.2 e l'ADR 0010 · Nessun pacchetto nuovo
## Contesto
La Fase 13 costruisce il giudice del campionato prima dei concorrenti. Più strategie si provano, più è facile che una vinca per caso: ogni prova fatta, anche vecchia, alza l'asticella per tutte, e ogni finalista deve fare meglio di almeno 190 copie su 200 degli stessi prezzi a cui è stata tolta ogni regolarità. L'ADR 0026 fissa i principi; qui ci sono le scelte che il codice ha dovuto fare, scritte prima che un risultato potesse suggerirle. In questa fase il giudice si prova su serie costruite apposta e sulle famiglie giornaliere che esistono già: nessun concorrente nuovo, nessuna pagina, nessun comando.
## Decisione
### Unità di lavoro e operai (#122)
1. **`TrialRunner.Run` = `Judge(Variants())`.** `Variants` esegue il motore, `Judge` calcola il rapporto senza eseguirlo più. I due `Run` di prima restano con la stessa firma. I tre rapporti d'oro della Fase 12 restano uguali byte per byte, senza toccarne i file.
2. **Due tempi, perché i costi e il controllo dello sguardo in avanti dipendono dalla variante scelta.** Primo tempo: ogni variante della griglia, in ordine, più la variante giudicata quando sta fuori dalla griglia. Poi la scelta sull'altopiano, con una sola funzione usata da entrambi i tempi e dal giudice. Secondo tempo: i costi doppi e tripli, il termine di confronto, lo sguardo in avanti. Con un solo operaio il motore viene chiamato esattamente nell'ordine di prima. I risultati si rimettono insieme per chiave, mai nell'ordine in cui finiscono.
3. **Ogni esecuzione del motore è un'unità registrata** nella tabella `tournament_units`, che serve sia alle prove del Laboratorio sia ai campionati. Le prove semplici hanno `tournament_id` vuoto. Chiave di un'unità: `{tipo}:{indice}:{parametri}:x{moltiplicatore}`, scritta senza dipendere dalla lingua del sistema. Esito di un'unità: il JSON della corsa senza le decisioni, compresso con gzip. Ricaricato, dà un rapporto identico byte per byte; la prova lo controlla sui tre rapporti d'oro.
4. **Ripresa.** Ogni tempo segna «in corso» tutte le sue unità mancanti in una sola scrittura, poi le esegue. Dopo un'interruzione la prova riprende: le unità finite si rileggono, quelle rimaste «in corso» si rifanno. Un'unità finita si riusa solo se è stata calcolata sugli stessi ingressi: ognuna porta l'impronta dei dati, la versione del motore e l'identità della build del programma. Dopo un aggiornamento dell'immagine, o se nel frattempo sono arrivate barre nuove, le unità con un'impronta diversa si rifanno: un rapporto non mescola mai corse fatte su ingressi diversi. Le unità non contano mai come prove nel conteggio di SPEC 12.2. Quando una prova semplice finisce o fallisce, i suoi esiti si cancellano (le righe restano come traccia dei tempi); quelli di un campionato restano fino alla sua fine.
5. **Operai.** Il vecchio thread unico diventa un gruppo di thread a priorità bassa (`anubis-laboratory-1…N`). Le prove restano una alla volta, ma le unità di una prova girano su N operai. Questo sostituisce la frase dell'ADR 0010 «una prova alla volta, su un thread suo». Su Linux, e quindi nel container, la priorità bassa del thread conta poco: il peso sul computer lo decide il numero di operai.
6. **Impostazione `laboratory.workers`**, in Impostazioni → Sistema: predefinita 1, un intero da 1 al numero dei processori meno 1 (almeno 1), calcolato quando la si cambia. Si legge all'inizio di ogni prova: un cambio vale dalla prova dopo, senza riavviare. Si alza solo dopo averne misurato l'effetto nel container, perché il Laboratorio non deve togliere tempo al trading.
7. **Tabelle** (migrazione 0016): `tournaments` e `tournament_units`, uguali sui due motori, più la colonna `tournament_id` su `backtest_trials`. Quella colonna non ha un vincolo verso `tournaments`, perché nell'esportazione `backtest_trials` viene prima. Ogni unità ha la sua chiave unica per prova, lo stato, l'esito compresso, i secondi impiegati e l'impronta degli ingressi.
### Statistica (#124)
8. **Il generatore a seme fisso** delle prove passa nel nucleo (`Core/SeededRandom.cs`) senza cambiare un bit: stesso algoritmo, stessa sequenza, stessi test d'oro. Le prove lo chiamano ancora `Gen`. Restano com'erano il generatore dell'apprendimento (`FixedRandom`, che estrae gli interi in un altro modo) e quello del percorso atteso (`PathBootstrap`), perché da loro dipendono risultati già scritti.
9. **Conteggio comune N** = tutte le varianti previste di tutti i concorrenti, anche di quelli falliti + le combinazioni dei finalisti + ogni variante già nel registro delle prove fuori da questo campionato + le 27 già provate da riga di comando (18 di `crypto_trend`, 9 di `crypto_relative_momentum`). Le combinazioni contano già ora, anche se si eseguono nella Fase 16: (coppie + insieme intero) × 3 schemi di peso, cioè 87 con 8 finalisti. Le varianti del registro si contano fino al momento in cui si apre il tratto finale, così un giudizio ripreso dà lo stesso N.
10. **Varianza del campo** = varianza degli Sharpe annui (Sharpe giornaliero × √periodi per anno) di tutte le varianti di tutti i concorrenti, così un anno crypto di 365 giorni e uno di 252 si confrontano. Per lo Sharpe corretto di un concorrente la varianza torna giornaliera con il suo anno. Le varianti precedenti contano in N ma non nella varianza, perché i loro Sharpe non sono tutti conservati.
11. **Calendari diversi** (crypto tutti i giorni, valute e azioni nei giorni feriali) si mettono su un calendario solo: l'unione dei giorni nella finestra comune, con rendimento zero dove non c'è seduta, perché il patrimonio non si muove. Su questo calendario si calcolano la probabilità di sovra-adattamento comune (16 gruppi) e il numero effettivo di scommesse.
12. **Numero effettivo di scommesse** = n² / Σ ρ² (rapporto di partecipazione della matrice delle correlazioni). Non serve calcolare autovalori. 28 serie identiche valgono 1. Una serie piatta è correlata solo con sé stessa.
13. **Intervallo** dello Sharpe di ogni finalista: ricampionamento a blocchi circolari di 20 giorni, 1.000 giri, 95%, con il seme del piano. È riportato, non decide.
14. **L'asticella** che il piano mostra prima di partire è lo Sharpe che il migliore di N tentativi senza vantaggio mostrerebbe per caso, in deviazioni standard del campo.
### Controllo contro il caso (ADR 0026 punto 4)
15. **Copie senza regolarità.** Ogni giorno del calendario ha un segno, + o −, con la stessa probabilità, e lo stesso segno vale per tutti gli strumenti. Si lavora sui logaritmi dei rapporti di apertura, massimo, minimo e chiusura rispetto alla chiusura del giorno prima: con il segno − cambiano verso e massimo e minimo si scambiano. Restano la grandezza di ogni giorno, le code e le correlazioni tra strumenti; spariscono tendenza e rientro.
16. **Centrato per chi è solo in acquisto**: il segno gira attorno al rendimento medio dello strumento. Altrimenti chiunque stia comprato su un mercato che sale batterebbe il controllo solo perché è comprato. Il motore giornaliero è solo in acquisto, quindi il suo controllo è sempre centrato.
17. La copia copre tutto lo storico caricato, riscaldamento compreso. La prima barra di ogni strumento resta com'è, e il volume non cambia.
18. **Strumenti con azioni societarie** (frazionamenti, dividendi): per ora il controllo li rifiuta con un messaggio. Il finalista che ne avrebbe bisogno non passa. Il primo campionato (crypto e valute) non ne ha; per le azioni si rivede nella Fase 23.
19. **Criterio**: lo Sharpe giornaliero della variante scelta, a costi normali, sulle 200 copie. La quota di copie pari o migliori del risultato vero non deve superare 0,05. Tutti i finalisti usano gli stessi segni nello stesso giorno. Il numero di copie va da 20 a 10.000: con meno di 20 la quota non potrebbe mai scendere a 0,05.
### Piano e tempi del campionato (#123, #125)
20. **Piano immutabile con impronta**, come quello di una prova: il JSON scritto è quello che si legge, e l'impronta è lo SHA-256 di quel testo, ricontrollato a ogni lettura. Contiene:
- i concorrenti, con etichetta, famiglia, versione delle regole, gruppo, mercato, griglia e dati;
- costi 1×, 2× e 3×; soglie di oggi più la quota massima del controllo (0,05);
- regola dei finalisti: al più 8, uno per gruppo e mercato, scelto sullo Sharpe delle finestre che avanzano;
- controllo: 200 copie, seme 20.261.202;
- combinazioni: coppie e insieme intero, pesi uguali, a volatilità inversa e a parità di rischio, 180 giorni, ogni trimestre;
- finestre di stress: «Crollo di marzo 2020», dal 19 febbraio al 23 marzo 2020, e «Inverno delle crypto 2022», dal 5 maggio al 31 dicembre 2022;
- le prove già contate;
- la data da cui comincia il tratto finale.
Combinazioni e finestre di stress si eseguono nella Fase 16, ma sono scritte nel piano fin da ora.
21. **Il piano e le prove dei concorrenti si scrivono insieme**, in una sola transazione, prima di ogni risultato. Ogni concorrente è una prova normale del Laboratorio, che si ferma al giorno prima del tratto finale, e conta nel registro come ogni altra.
22. **Primo tempo**: ogni variante di ogni concorrente una volta, a costi normali, sul tratto di ricerca. **Secondo tempo**: la scelta sull'altopiano è già nella prova di ciascuno. Finalista è, per ogni gruppo e mercato, chi ha lo Sharpe migliore sulle finestre che avanzano; poi si tengono i migliori 8. Senza finestre che avanzano non si è finalisti. **Terzo tempo**, per ogni finalista: costi doppi e tripli, termine di confronto e sguardo in avanti vengono dalla sua prova; poi il controllo e il tratto finale.
23. **Il tratto finale si legge una volta sola.** L'apertura scrive i finalisti e l'ora una volta per tutte. Un giudizio ripreso rilegge i finalisti già scritti: i finalisti non possono cambiare dopo che il tratto è stato aperto, e solo loro lo leggono. Il riscaldamento degli indicatori viene dal tratto di ricerca. Se il programma si ferma mentre il tratto finale è caricato ma prima che i suoi risultati siano scritti, alla ripresa lo si rilegge per gli stessi finalisti. Lo si rilegge anche quando il giudizio riprende su un'altra build del programma. I finalisti restano comunque quelli scritti all'apertura.
24. **Un finalista passa solo se supera tutti e sette i controlli**:
- risultato netto a costi doppi maggiore di zero sul tratto di ricerca;
- Sharpe corretto comune almeno 0,90;
- probabilità di sovra-adattamento comune al più 0,40;
- calo massimo al più 25%;
- nessuno sguardo in avanti;
- controllo contro il caso al più 0,05;
- risultato netto a costi doppi non negativo sul tratto finale.
Un controllo che non si può calcolare conta come non superato. Il campionato è superato se passa almeno un finalista. Una prova di un concorrente fallita resta nel rapporto, non può essere finalista e le sue varianti contano comunque in N. Il campionato fallisce con il motivo se il piano del campionato non corrisponde più alla sua impronta, o non si legge più. Fallisce anche se una prova di un concorrente non corrisponde più alla sua impronta o al piano: griglia, origine dei dati, capitale, tabella dello slittamento, quota di riferimento. E fallisce se i dati di ricerca di un finalista sono cambiati dopo la sua prova, perché il controllo confronterebbe copie fatte su dati nuovi con un risultato fatto sui vecchi. Un errore durante il giudizio non ferma mai la coda del Laboratorio: si scrive nel registro e il giudizio si riprova più tardi.
25. **Il rapporto** del campionato elenca:
- N con le sue parti, l'asticella, la varianza del campo, la probabilità di sovra-adattamento comune e il numero effettivo di scommesse;
- per ogni concorrente: la variante scelta, lo Sharpe delle finestre che avanzano e se è finalista;
- per ogni finalista: i sette controlli, la quota del controllo, l'intervallo e il risultato sul tratto finale;
- i limiti, in italiano.
Alla fine gli esiti delle unità del campionato si cancellano.
## Alternative scartate
- **Rieseguire la variante scelta invece di conservare le corse**: costa un'esecuzione in più e cambia l'ordine delle chiamate al motore.
- **Conservare le corse con le decisioni**: le decisioni sono la parte più grande e il giudice non le legge.
- **Intersecare i calendari invece di riempire con zero**: butterebbe via i fine settimana delle crypto, che sono rendimenti veri.
- **Mettere nella varianza anche le varianti precedenti**: i loro Sharpe esistono solo arrotondati nei documenti. Conterle in N è la parte prudente.
- **Controllo non centrato per tutti**: premierebbe chi sta solo comprato su un mercato che sale.
- **Ricalcolare il registro al momento del giudizio, senza fermarlo**: un giudizio ripreso potrebbe dare un N diverso.
## Conseguenze
- **L'asticella sale anche con i concorrenti buoni.** La varianza del campo comprende tutte le varianti, anche quelle che hanno davvero un vantaggio. Se una buona parte del campo ha un vantaggio, la varianza cresce e con lei l'asticella. Nella prova costruita apposta, due concorrenti con un vantaggio forte provati con tante varianti quanti i concorrenti di rumore non passano (Sharpe corretto 0,66 e 0,87); passano solo se il campo li ha cercati con meno varianti. È la scelta prudente dello Sharpe corretto: sbaglia nel senso di non promuovere. In un campo vero, fatto quasi solo di rumore, conta poco; se un giorno impedisse di riconoscere un vantaggio vero, la correzione andrà decisa con un ADR, prima di guardare i risultati.
- Con alcune centinaia di prove è probabile che pochi concorrenti, o nessuno, superino il campionato (ADR 0026).
- Un campionato si giudica nella stessa coda delle prove: mentre si giudica, le prove dopo aspettano.
- Il controllo contro il caso costa 200 esecuzioni per finalista: per questo le unità si riprendono e gli operai sono regolabili.
- Le Fasi 14 e 15 trovano il giudice pronto: il motore a panieri deve solo dare le sue unità e la sua copia senza regolarità.
+1 -1
View File
@@ -437,7 +437,7 @@ internal sealed partial class AnubisHost(
} }
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none. // The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger); _lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger, ct => LaboratorySettings.WorkersAsync(settings, ct));
if (_lab is { } laboratory && _trading is { } running && _market is { } market) if (_lab is { } laboratory && _trading is { } running && _market is { } market)
{ {
async Task<bool> HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet; async Task<bool> HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet;
@@ -4,6 +4,7 @@
@inject ShellData Shell @inject ShellData Shell
@inject SecondFactorDrafts Drafts @inject SecondFactorDrafts Drafts
@inject Anubis.Core.IClock Clock @inject Anubis.Core.IClock Clock
@using Anubis.Backtest
@using Anubis.Data @using Anubis.Data
@using Anubis.Trading @using Anubis.Trading
@@ -646,6 +647,16 @@
</dl> </dl>
<p class="hint">Motore e connessione del database si cambiano solo nella configurazione del container. Per passare a un altro database c'è l'esportazione e l'importazione: il manuale dice come.</p> <p class="hint">Motore e connessione del database si cambiano solo nella configurazione del container. Per passare a un altro database c'è l'esportazione e l'importazione: il manuale dice come.</p>
<h3>Laboratorio</h3>
<form method="post" action="/azioni/impostazioni/@LaboratorySettings.Workers.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#sistema" />
<label for="lab-workers">@LaboratorySettings.Workers.Label</label>
<input id="lab-workers" name="valore" inputmode="numeric" autocomplete="off" value="@_labWorkers.Value" readonly="@(_labWorkers.ReadOnly || Shell.IsDemo)" />
<button class="btn btn-small" type="submit">Salva</button>
</form>
<p class="hint">Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta. Alzalo solo dopo averne misurato l'effetto: il Laboratorio non deve togliere tempo al trading. Vale dalla prossima prova. Su questo computer va da 1 a @LaboratorySettings.MaxWorkers.</p>
<h3>Salvataggi</h3> <h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p> <p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form> <form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
@@ -722,6 +733,7 @@
private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null); private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null);
private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null); private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null);
private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null); private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null);
private SettingValue _labWorkers = new(LaboratorySettings.Workers.Key, LaboratorySettings.Workers.Default, false, null);
private Anubis.Notifications.NotificationSummary? _queue; private Anubis.Notifications.NotificationSummary? _queue;
private string? _draft; private string? _draft;
private string? _draftUri; private string? _draftUri;
@@ -784,6 +796,7 @@
_telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct); _telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct);
_heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct); _heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct);
_telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct); _telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct);
_labWorkers = await services.Settings.GetAsync(LaboratorySettings.Workers.Key, ct);
_queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null; _queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null;
var ledger = new Ledger(services.Db, Clock); var ledger = new Ledger(services.Db, Clock);
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock)); var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
@@ -818,6 +831,7 @@
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.", "segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.", "salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
"impostazione" => "Questa impostazione non si può cambiare così.", "impostazione" => "Questa impostazione non si può cambiare così.",
"operai" => $"Gli operai del Laboratorio sono un numero intero da 1 a {LaboratorySettings.MaxWorkers}.",
"riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».", "riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».",
"bot" => "Comando non ammesso nello stato attuale del bot.", "bot" => "Comando non ammesso nello stato attuale del bot.",
"motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.", "motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.",
+6 -1
View File
@@ -274,7 +274,7 @@ internal static partial class Forms
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key); var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
var rules = key == Anubis.News.ExternalRules.Setting.Key; var rules = key == Anubis.News.ExternalRules.Setting.Key;
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key && if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key &&
!news && !model && !rules) key != Anubis.Backtest.LaboratorySettings.Workers.Key && !news && !model && !rules)
{ {
return Results.Redirect(With(back, "errore", "impostazione")); return Results.Redirect(With(back, "errore", "impostazione"));
} }
@@ -324,6 +324,11 @@ internal static partial class Forms
return Results.Redirect(With(back, "errore", refusal)); return Results.Redirect(With(back, "errore", refusal));
} }
if (key == Anubis.Backtest.LaboratorySettings.Workers.Key && Anubis.Backtest.LaboratorySettings.Workers.Check!(form["valore"].ToString()) is not null)
{
return Results.Redirect(With(back, "errore", "operai"));
}
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null) if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
{ {
return Results.Redirect(With(back, "errore", "riunioni")); return Results.Redirect(With(back, "errore", "riunioni"));
+108 -63
View File
@@ -1,4 +1,5 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.Threading.Channels; using System.Threading.Channels;
using Anubis.Core; using Anubis.Core;
@@ -41,9 +42,11 @@ public static class TrialRequestErrors
} }
/// <summary> /// <summary>
/// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time on a /// The laboratory (SPEC 12.2, 13.4): it writes the plan of a trial before running it, runs one trial at a time, and writes
/// dedicated thread with low priority, so trading and the interface never wait for a backtest, and writes the report /// the report back. The engine executions of a trial (its units) run on a pool of low-priority threads, one by default
/// back. Only the asynchronous side touches the database. After a restart, trials left halfway start again. /// (<see cref="LaboratorySettings.Workers"/>, read at the start of every trial), so trading and the interface never wait for a
/// backtest. Each unit is recorded in the database when it is done: after a restart a trial left halfway starts again and
/// runs only the units it had not finished. Only the asynchronous side touches the database.
/// </summary> /// </summary>
public sealed partial class Laboratory : IDisposable public sealed partial class Laboratory : IDisposable
{ {
@@ -60,19 +63,43 @@ public sealed partial class Laboratory : IDisposable
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly Channel<Guid> _queue = Channel.CreateUnbounded<Guid>(new UnboundedChannelOptions { SingleReader = true }); private readonly Channel<Guid> _queue = Channel.CreateUnbounded<Guid>(new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary<Guid, string> _progress = new(); private readonly ConcurrentDictionary<Guid, string> _progress = new();
private readonly LowPriorityWorker _worker = new("anubis-laboratory"); private readonly Func<CancellationToken, Task<int>> _workers;
private readonly Lock _poolGate = new();
private LowPriorityPool _pool = new(PoolName, 1);
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null) /// <param name="workers">How many threads the next trial gets (<see cref="LaboratorySettings.WorkersAsync"/>); one when null.</param>
public Laboratory(Database db, IClock clock, string researchRoot, ILogger? logger = null, Func<CancellationToken, Task<int>>? workers = null)
{ {
_db = db; _db = db;
_clock = clock; _clock = clock;
_researchRoot = researchRoot; _researchRoot = researchRoot;
_logger = logger ?? NullLogger.Instance; _logger = logger ?? NullLogger.Instance;
_workers = workers ?? (_ => Task.FromResult(1));
Trials = new TrialStore(db, clock); Trials = new TrialStore(db, clock);
Units = new TrialUnitStore(db, clock);
Tournaments = new TournamentStore(db, clock);
DataFor = (data, cancellationToken) => LoadAsync(_db, _clock, _researchRoot, data, cancellationToken);
} }
private const string PoolName = "anubis-laboratory";
public TrialStore Trials { get; } public TrialStore Trials { get; }
/// <summary>The units of the trials: one row per engine execution.</summary>
public TrialUnitStore Units { get; }
/// <summary>The tournaments of the strategies (ADR 0026).</summary>
public TournamentStore Tournaments { get; }
/// <summary>The engine of a trial: the daily one. Tests put one in between to count or stop the executions.</summary>
internal Func<TrialPlan, IStrategyFamily, BacktestDataset, ITrialEngine> EngineFor { get; set; } = (plan, family, data) => new DailyTrialEngine(plan, family, data);
/// <summary>The families the laboratory knows: the catalogue. Tests add the families that exist only in them.</summary>
internal Func<string, IStrategyFamily?> Families { get; set; } = StrategyCatalog.Find;
/// <summary>The data a trial reads (<see cref="LoadAsync"/>). Tests give synthetic series and count what is read.</summary>
internal Func<TrialData, CancellationToken, Task<BacktestDataset>> DataFor { get; set; }
/// <summary>Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did.</summary> /// <summary>Called when a trial of a quarterly review ends, and once at the start: the review concludes when all of them did.</summary>
public Func<CancellationToken, Task>? ReviewTrialEnded { get; set; } public Func<CancellationToken, Task>? ReviewTrialEnded { get; set; }
@@ -86,8 +113,35 @@ public sealed partial class Laboratory : IDisposable
} }
} }
/// <summary>Heavy work on the thread of the trials.</summary> /// <summary>Heavy work on the threads of the trials.</summary>
public Task<T> ComputeAsync<T>(Func<T> work) => _worker.RunAsync(work); public Task<T> ComputeAsync<T>(Func<T> work)
{
lock (_poolGate)
{
return _pool.RunAsync(work);
}
}
/// <summary>The pool with <paramref name="workers"/> threads: the one in use, or a new one when the number changed.</summary>
private LowPriorityPool PoolOf(int workers)
{
LowPriorityPool? old = null;
LowPriorityPool pool;
lock (_poolGate)
{
if (_pool.Workers != workers)
{
old = _pool;
_pool = new LowPriorityPool(PoolName, workers);
}
pool = _pool;
}
// The old threads finish what they were given (heavy work of a review, at most) and stop.
old?.Dispose();
return pool;
}
/// <summary>What the running trial is doing, in words; null when it is not running here.</summary> /// <summary>What the running trial is doing, in words; null when it is not running here.</summary>
public string? Progress(Guid id) => _progress.GetValueOrDefault(id); public string? Progress(Guid id) => _progress.GetValueOrDefault(id);
@@ -102,10 +156,15 @@ public sealed partial class Laboratory : IDisposable
} }
/// <summary>The plan of a request: the family's own grid where the request gives none, the default costs, checks and thresholds.</summary> /// <summary>The plan of a request: the family's own grid where the request gives none, the default costs, checks and thresholds.</summary>
public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null) public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null) =>
BuildPlan(request, now, slippage, StrategyCatalog.Find);
/// <summary>The same, with the families <paramref name="families"/> knows (the catalogue, or the test families of a tournament).</summary>
internal static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage, Func<string, IStrategyFamily?> families)
{ {
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request);
var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta."); ArgumentNullException.ThrowIfNull(families);
var family = families(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta.");
if (request.Source is not (TrialSources.Database or TrialSources.Research)) if (request.Source is not (TrialSources.Database or TrialSources.Research))
{ {
throw new TrialRequestException(TrialRequestErrors.Source, "Origine dei dati sconosciuta."); throw new TrialRequestException(TrialRequestErrors.Source, "Origine dei dati sconosciuta.");
@@ -205,6 +264,7 @@ public sealed partial class Laboratory : IDisposable
} }
await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); await ReviewEndedAsync(cancellationToken).ConfigureAwait(false);
await ResumeTournamentsAsync(cancellationToken).ConfigureAwait(false);
await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{ {
try try
@@ -236,11 +296,20 @@ public sealed partial class Laboratory : IDisposable
} }
} }
/// <summary>One trial: load its data, compute on the worker thread, write the report. A failure is recorded, not thrown.</summary> /// <summary>
/// One trial: load its data, run its units on the pool (those done before a restart on the same data, engine and build come
/// back from the database), judge on the pool, write the report. A failure is recorded, not thrown. A trial of a tournament
/// already finished that comes back to the queue brings its tournament to the judge, when it is not judged yet.
/// </summary>
public async Task ProcessAsync(Guid id, CancellationToken cancellationToken) public async Task ProcessAsync(Guid id, CancellationToken cancellationToken)
{ {
if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false)) if (!await Trials.StartAsync(id, cancellationToken).ConfigureAwait(false))
{ {
if (await Trials.FinishedTournamentAsync(id, cancellationToken).ConfigureAwait(false) is { } waiting)
{
await JudgeFromQueueAsync(waiting, id, cancellationToken).ConfigureAwait(false);
}
return; return;
} }
@@ -249,22 +318,37 @@ public sealed partial class Laboratory : IDisposable
try try
{ {
trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata."); trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata.");
if (trial.TournamentId is { } tournament)
{
await Tournaments.StartAsync(tournament, cancellationToken).ConfigureAwait(false);
}
if (!trial.PlanIntact) if (!trial.PlanIntact)
{ {
throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte."); throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte.");
} }
var family = StrategyCatalog.Find(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy); var family = Families(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy);
if (family.Version != trial.StrategyVersion) if (family.Version != trial.StrategyVersion)
{ {
throw new InvalidOperationException($"La strategia è cambiata dalla versione {trial.StrategyVersion} alla {family.Version}: pianifica una prova nuova."); throw new InvalidOperationException($"La strategia è cambiata dalla versione {trial.StrategyVersion} alla {family.Version}: pianifica una prova nuova.");
} }
var data = await LoadAsync(_db, _clock, _researchRoot, trial.Plan.Data, cancellationToken).ConfigureAwait(false); var data = await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false);
var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false); var prior = await Trials.PriorOfAsync(trial, cancellationToken).ConfigureAwait(false);
var now = _clock.UtcNow; var now = _clock.UtcNow;
var (report, summary) = await _worker.RunAsync( var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false)));
() => TrialRunner.Run(id, trial.Plan, trial.PlanHash, family, data, prior, now, text => _progress[id] = text, cancellationToken)).ConfigureAwait(false); var engine = EngineFor(trial.Plan, family, data);
var fingerprint = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false);
var done = await Units.ResumeAsync(id, fingerprint, cancellationToken).ConfigureAwait(false);
var watch = Stopwatch.StartNew();
var runs = await TrialRunner.VariantsAsync(trial.Plan, family, engine, new StoredTrialUnits(pool, Units, id, trial.TournamentId, done, fingerprint),
text => _progress[id] = text, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
_progress[id] = "convalide";
var elapsed = watch.Elapsed;
var (report, summary) = await pool.RunAsync(
() => TrialRunner.Judge(id, trial.Plan, trial.PlanHash, family, engine, runs, prior, now, elapsed)).ConfigureAwait(false);
await Trials.FinishAsync(id, report.DataFingerprint, summary, report.ToJson(), report.Passed, cancellationToken).ConfigureAwait(false); await Trials.FinishAsync(id, report.DataFingerprint, summary, report.ToJson(), report.Passed, cancellationToken).ConfigureAwait(false);
LogFinished(_logger, id, trial.Strategy, report.Passed); LogFinished(_logger, id, trial.Strategy, report.Passed);
} }
@@ -286,6 +370,12 @@ public sealed partial class Laboratory : IDisposable
{ {
await ReviewEndedAsync(cancellationToken).ConfigureAwait(false); await ReviewEndedAsync(cancellationToken).ConfigureAwait(false);
} }
// The last trial of a tournament to finish brings it to its judge.
if (trial?.TournamentId is { } judged)
{
await JudgeFromQueueAsync(judged, id, cancellationToken).ConfigureAwait(false);
}
} }
/// <summary> /// <summary>
@@ -379,7 +469,10 @@ public sealed partial class Laboratory : IDisposable
public void Dispose() public void Dispose()
{ {
_queue.Writer.TryComplete(); _queue.Writer.TryComplete();
_worker.Dispose(); lock (_poolGate)
{
_pool.Dispose();
}
} }
[LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")] [LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")]
@@ -391,51 +484,3 @@ public sealed partial class Laboratory : IDisposable
[LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")] [LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")]
private static partial void LogFailed(ILogger logger, Guid id, Exception exception); private static partial void LogFailed(ILogger logger, Guid id, Exception exception);
} }
/// <summary>
/// One thread with low priority that runs heavy work in order. Its callers await the result on their own side: the
/// thread never touches the database.
/// </summary>
internal sealed class LowPriorityWorker : IDisposable
{
private readonly BlockingCollection<Action> _work = [];
private readonly Thread _thread;
public LowPriorityWorker(string name)
{
_thread = new Thread(Loop) { IsBackground = true, Name = name, Priority = ThreadPriority.BelowNormal };
_thread.Start();
}
public Task<T> RunAsync<T>(Func<T> work)
{
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
public void Dispose()
{
_work.CompleteAdding();
_thread.Join(TimeSpan.FromSeconds(10));
_work.Dispose();
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Globalization;
using Anubis.Core;
namespace Anubis.Backtest;
/// <summary>
/// The settings of the laboratory (Phase 13): how many threads run the units of a trial together. One by default; at most
/// one less than the processors, so trading always has one, and never fewer than one (a container with a single processor).
/// </summary>
public static class LaboratorySettings
{
public static readonly SettingDefinition Workers = new("laboratory.workers", "Operai del Laboratorio", "1", Check: Whole);
public static readonly IReadOnlyList<SettingDefinition> All = [Workers];
/// <summary>The most threads this computer allows, read when asked: the processors can change with the container.</summary>
public static int MaxWorkers => Math.Max(1, Environment.ProcessorCount - 1);
/// <summary>The threads for the next trial: the saved value, kept within the bounds of this computer.</summary>
public static async Task<int> WorkersAsync(SettingsStore settings, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(settings);
var value = (await settings.GetAsync(Workers.Key, cancellationToken).ConfigureAwait(false)).Value;
return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var workers) ? Math.Clamp(workers, 1, MaxWorkers) : 1;
}
private static string? Whole(string text)
{
var max = MaxWorkers;
return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= 1 && value <= max
? null
: $"Serve un numero intero tra 1 e {max}.";
}
}
@@ -0,0 +1,314 @@
using System.Diagnostics;
using System.Text.Json;
using Anubis.Core;
using Anubis.Strategies;
using Microsoft.Extensions.Logging;
namespace Anubis.Backtest;
/// <summary>
/// The tournaments of the laboratory (ADR 0026 point 7). The plan and the trials of the contenders are written together; the
/// trials run as any other, on the search window only. When the last one finishes the tournament goes to its judge: the
/// finalists are chosen and written as the final tract is opened, once; the control against chance and the runs on the final
/// tract of every finalist are units on the pool, kept in the database, so a judge stopped halfway runs again only what it
/// had not finished; then the report.
/// </summary>
public sealed partial class Laboratory
{
/// <summary>The costs of the runs on the final tract: plain and doubled.</summary>
private static readonly decimal[] HoldoutCosts = [1m, 2m];
/// <summary>Checks the request, writes the plan of the tournament with the trials of its contenders and queues them. The plan is final from here on.</summary>
public async Task<Tournament> PlanTournamentAsync(TournamentRequest request, CancellationToken cancellationToken)
{
var slippage = await new Anubis.Learning.CostBook(_db, _clock).TableAsync(cancellationToken).ConfigureAwait(false);
var registry = await Tournaments.RegistryVariantsAsync(null, null, cancellationToken).ConfigureAwait(false);
var (plan, trials) = TournamentPlans.BuildPlan(request, _clock.UtcNow, registry, Families, slippage);
var tournament = await Tournaments.PlanAsync(plan, trials, cancellationToken).ConfigureAwait(false);
foreach (var trial in await Trials.OfTournamentAsync(tournament.Id, cancellationToken).ConfigureAwait(false))
{
await _queue.Writer.WriteAsync(trial.Id, cancellationToken).ConfigureAwait(false);
}
return tournament;
}
// After a restart: the tournaments whose trials are all finished but that were not judged to the end.
private async Task ResumeTournamentsAsync(CancellationToken cancellationToken)
{
IReadOnlyList<Guid> ids;
try
{
ids = await Tournaments.ResumableAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
LogQueueFailed(_logger, ex);
return;
}
// An error that escapes the judge (the database out of reach while recording a failure) does not stop the queue: the
// tournament stays to judge, at the next start or when one of its trials comes back to the queue.
foreach (var id in ids)
{
try
{
await JudgeTournamentAsync(id, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
LogJudgeDeferred(_logger, id, ex);
}
}
}
// The judge called from the queue, after trial `trial` of the tournament: an error that escapes it does not stop the queue.
// As an error of the queue itself, the trial comes back after RetryDelay and brings the tournament to its judge again.
private async Task JudgeFromQueueAsync(Guid tournament, Guid trial, CancellationToken cancellationToken)
{
try
{
await JudgeTournamentAsync(tournament, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
LogQueueFailed(_logger, ex);
await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false);
_queue.Writer.TryWrite(trial);
}
}
/// <summary>
/// Judges a tournament whose trials are all finished; nothing when one is still to run or the tournament is finished. A
/// failure is recorded, not thrown, a plan that can no longer be read included; a stop leaves it being judged, and the next
/// start goes on from the units done. Only an error while recording the failure (the database out of reach) comes out.
/// </summary>
public async Task JudgeTournamentAsync(Guid id, CancellationToken cancellationToken)
{
try
{
var tournament = await ReadTournamentAsync(id, cancellationToken).ConfigureAwait(false);
if (tournament is null || tournament.IsFinished)
{
return;
}
var trials = await Trials.OfTournamentAsync(id, cancellationToken).ConfigureAwait(false);
if (trials.Any(t => !t.IsFinished) || !await Tournaments.JudgeAsync(id, cancellationToken).ConfigureAwait(false))
{
return;
}
_progress[id] = "scelta dei finalisti";
var watch = Stopwatch.StartNew();
if (!tournament.PlanIntact)
{
throw new InvalidOperationException("Il piano registrato del campionato non corrisponde più alla sua impronta: il campionato non si giudica.");
}
var plan = tournament.Plan;
if (trials.Count != plan.Contenders.Count)
{
throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano.");
}
var pool = PoolOf(Math.Max(1, await _workers(cancellationToken).ConfigureAwait(false)));
var contenders = new List<ContenderOutcome>();
for (var i = 0; i < trials.Count; i++)
{
contenders.Add(await ContenderAsync(plan, plan.Contenders[i], trials[i], pool, cancellationToken).ConfigureAwait(false));
}
// The final tract opens once: a judge resumed after a restart gets back the finalists written the first time.
var (finalists, openedAt) = await Tournaments.OpenHoldoutAsync(id, TournamentJudge.Finalists(plan, contenders), cancellationToken).ConfigureAwait(false);
var registry = await Tournaments.RegistryVariantsAsync(id, openedAt, cancellationToken).ConfigureAwait(false);
var byLabel = contenders.ToDictionary(c => c.Contender.Label, StringComparer.Ordinal);
var outcomes = new List<FinalistOutcome>();
for (var k = 0; k < finalists.Count; k++)
{
var contender = byLabel.GetValueOrDefault(finalists[k]) ?? throw new InvalidOperationException("Il finalista «" + finalists[k] + "» non è nel piano.");
_progress[id] = $"finalista {k + 1} di {finalists.Count}";
outcomes.Add(await FinalistAsync(id, plan, contender, pool, cancellationToken).ConfigureAwait(false));
}
_progress[id] = "rapporto del campionato";
var now = _clock.UtcNow;
var elapsed = watch.Elapsed;
var report = await pool.RunAsync(() => TournamentJudge.Report(id, plan, tournament.PlanHash, contenders, finalists, outcomes, registry, now, elapsed))
.ConfigureAwait(false);
await Tournaments.FinishAsync(id, report.Passed, report.ToJson(), cancellationToken).ConfigureAwait(false);
LogTournamentFinished(_logger, id, report.PassedCount);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw; // Left being judged: the next start goes on.
}
catch (Exception ex)
{
LogTournamentFailed(_logger, id, ex);
await Tournaments.FailAsync(id, Redactor.Redact(ex.Message), CancellationToken.None).ConfigureAwait(false);
}
finally
{
_progress.TryRemove(id, out _);
}
}
// The tournament with its plan; a plan text that no longer reads (changed by hand, or by a version that cannot read it) fails it.
private async Task<Tournament?> ReadTournamentAsync(Guid id, CancellationToken cancellationToken)
{
try
{
return await Tournaments.GetAsync(id, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
throw new InvalidOperationException("Il piano registrato del campionato non si può più leggere: il campionato non si giudica.", ex);
}
}
// A contender as its trial left it: the report and the run of every variant of the grid, from the units it kept. Its trial
// must be the one the plan of the tournament wrote: plan intact, and the same rule, grid, data, capital and costs.
private async Task<ContenderOutcome> ContenderAsync(TournamentPlan plan, TournamentContender contender, Trial trial, LowPriorityPool pool, CancellationToken cancellationToken)
{
if (!trial.PlanIntact)
{
throw new InvalidOperationException("Il piano registrato della prova di «" + contender.Label + "» non corrisponde più alla sua impronta: il campionato non si giudica.");
}
var data = trial.Plan.Data;
if (trial.Strategy != contender.Strategy || trial.StrategyVersion != contender.StrategyVersion || data.To != plan.SearchTo || data.From != contender.Data.From
|| !data.Symbols.SequenceEqual(contender.Data.Symbols, StringComparer.Ordinal) || data.Venue != contender.Data.Venue || data.Source != contender.Data.Source
|| data.FullHistory != contender.Data.FullHistory || trial.Variants != contender.Variants || !SameGrid(trial.Plan.Grid, contender.Grid)
|| trial.Plan.InitialCapital != plan.InitialCapital || trial.Plan.Slippage != plan.Slippage
|| trial.Plan.ReferenceShare != StrategyPipeline.ResearchShare(contender.Strategy))
{
throw new InvalidOperationException("Le prove del campionato non corrispondono al suo piano.");
}
if (trial.Status != TrialStatuses.Done)
{
return new ContenderOutcome(contender, trial, null, []);
}
var report = BacktestReport.FromJson(await Trials.ReportJsonAsync(trial.Id, cancellationToken).ConfigureAwait(false)
?? throw new InvalidOperationException("La prova di «" + contender.Label + "» non ha un rapporto."));
var family = FamilyOf(contender);
var stored = await Units.OutcomesAsync(trial.Id, cancellationToken).ConfigureAwait(false);
var variants = await pool.RunAsync(() => ParameterGrid.Of(family, trial.Plan.Grid).Select((v, i) =>
{
var key = new TrialUnitKey(TrialUnitKind.Variant, i, v.ToString(), 1m);
var outcome = stored.GetValueOrDefault(key.Text)
?? throw new InvalidOperationException("Mancano i risultati delle varianti di «" + contender.Label + "»: il campionato non si può giudicare.");
return VariantSeries.Of(v.ToString(), TrialUnitOutcomes.Decode(key, outcome).Run!);
}).ToList()).ConfigureAwait(false);
return new ContenderOutcome(contender, trial, report, variants);
}
// The units of a finalist: the repetitions of the control on the surrogates of its search data, then its chosen variant on
// the final tract at plain and doubled costs. The final tract is read only when its runs are not done yet.
private async Task<FinalistOutcome> FinalistAsync(Guid tournamentId, TournamentPlan plan, ContenderOutcome contender, LowPriorityPool pool, CancellationToken cancellationToken)
{
var trial = contender.Trial;
var family = FamilyOf(contender.Contender);
var chosenText = contender.Chosen.Parameters;
var chosen = ParameterGrid.Of(family, trial.Plan.Grid).FirstOrDefault(v => v.ToString() == chosenText)?.Parameters
?? throw new InvalidOperationException("La variante scelta di «" + contender.Contender.Label + "» non è nella sua griglia.");
// Every finalist draws the signs of a day from the same first day, so a day has one sign across the whole field.
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var engine = EngineFor(trial.Plan, family, await DataFor(trial.Plan.Data, cancellationToken).ConfigureAwait(false));
var centred = engine.LongOnly;
// The repetitions of the control done on other search data, by another engine or build run again. The runs on the final
// tract done by another engine or build too; on other data of the tract, only when it is read again for a run not done.
var search = await pool.RunAsync(() => TrialUnitStore.Fingerprint(engine)).ConfigureAwait(false);
// The control compares the replicas with the Sharpe ratio of the contender's own trial: both must come from the same
// search data, or the comparison would mix two inputs.
if (trial.DataFingerprint is null || !search.StartsWith(trial.DataFingerprint + "|", StringComparison.Ordinal))
{
throw new InvalidOperationException("I dati di ricerca di «" + contender.Contender.Label
+ "» sono cambiati dopo la sua prova: il campionato non si giudica.");
}
var controlKind = TrialUnitKey.TextOf(TrialUnitKind.Control);
var holdoutKind = TrialUnitKey.TextOf(TrialUnitKind.Holdout);
var done = await Units.ResumeAsync(trial.Id, (kind, stored) =>
kind == controlKind ? stored == search
: kind != holdoutKind || (stored is not null && stored.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)), cancellationToken).ConfigureAwait(false);
var units = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, done, search);
List<TrialUnitKey> control = [.. Enumerable.Range(0, plan.Control.Repetitions).Select(k => new TrialUnitKey(TrialUnitKind.Control, k, chosenText, 1m))];
string? unavailable = null;
if (control.Any(k => !done.ContainsKey(k.Text)))
{
unavailable = await pool.RunAsync(() =>
{
try
{
engine.Surrogate(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, 0)), centred);
return null;
}
catch (NotSupportedException ex)
{
return ex.Message;
}
}).ConfigureAwait(false);
}
var replicas = new List<double>();
if (unavailable is null)
{
TrialUnitResult Replica(TrialUnitKey key)
{
cancellationToken.ThrowIfCancellationRequested();
var surrogate = engine.Surrogate(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, key.Index)), centred);
return new TrialUnitResult(key, null, null) { Sharpe = Moments.Of(surrogate.Run(chosen).DailyReturns()).Sharpe };
}
replicas.AddRange((await units.RunAsync(control, Replica, cancellationToken).ConfigureAwait(false)).Select(r => r.Sharpe ?? double.NaN));
}
List<TrialUnitKey> holdout = [.. HoldoutCosts.Select(m => new TrialUnitKey(TrialUnitKind.Holdout, 0, chosenText, m))];
ITrialEngine? tract = null;
var finals = units;
if (holdout.Any(k => !done.ContainsKey(k.Text)))
{
var data = trial.Plan.Data with { From = plan.HoldoutFrom, To = contender.Contender.Data.To };
var holdoutPlan = trial.Plan with { Data = data };
var opened = EngineFor(holdoutPlan, family, await DataFor(data, cancellationToken).ConfigureAwait(false));
tract = opened;
var read = await pool.RunAsync(() => TrialUnitStore.Fingerprint(opened)).ConfigureAwait(false);
var again = await Units.ResumeAsync(trial.Id, (kind, stored) => kind != holdoutKind || stored == read, cancellationToken).ConfigureAwait(false);
finals = new StoredTrialUnits(pool, Units, trial.Id, tournamentId, again, read);
}
TrialUnitResult Final(TrialUnitKey key)
{
cancellationToken.ThrowIfCancellationRequested();
return new TrialUnitResult(key, (tract ?? throw new InvalidOperationException("The final tract was not read.")).Run(chosen, key.CostMultiplier), null);
}
var runs = await finals.RunAsync(holdout, Final, cancellationToken).ConfigureAwait(false);
return new FinalistOutcome(contender.Contender.Label, centred, replicas, unavailable, runs.ToDictionary(r => r.Key.CostMultiplier, r => r.Run!));
}
private static bool SameGrid(IReadOnlyDictionary<string, IReadOnlyList<decimal>> a, IReadOnlyDictionary<string, IReadOnlyList<decimal>> b) =>
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var values) && p.Value.SequenceEqual(values));
private IStrategyFamily FamilyOf(TournamentContender contender)
{
var family = Families(contender.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + contender.Strategy);
return family.Version == contender.StrategyVersion ? family
: throw new InvalidOperationException($"La strategia di «{contender.Label}» è cambiata dalla versione {contender.StrategyVersion} alla {family.Version}: pianifica un campionato nuovo.");
}
[LoggerMessage(Level = LogLevel.Information, Message = "Tournament {Id} judged, finalists passed: {Passed}")]
private static partial void LogTournamentFinished(ILogger logger, Guid id, int passed);
[LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} failed")]
private static partial void LogTournamentFailed(ILogger logger, Guid id, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "Tournament {Id} could not be judged now: it is judged at the next start or when one of its trials comes back to the queue")]
private static partial void LogJudgeDeferred(ILogger logger, Guid id, Exception exception);
}
+86
View File
@@ -0,0 +1,86 @@
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Anubis.Backtest;
/// <summary>
/// A few background threads with low priority (<c>name-1</c> … <c>name-N</c>) that take heavy work in the order it arrives:
/// with one thread the work runs in that order. Callers await the result on their own side: the threads never touch the
/// database. On Linux the priority is mostly ignored by the scheduler, so what keeps the laboratory light there is the number
/// of threads.
/// </summary>
internal sealed class LowPriorityPool : IDisposable
{
private static readonly TimeSpan JoinWait = TimeSpan.FromSeconds(10);
private readonly BlockingCollection<Action> _work = [];
private readonly Thread[] _threads;
private int _disposed;
public LowPriorityPool(string name, int workers)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentOutOfRangeException.ThrowIfLessThan(workers, 1);
_threads = new Thread[workers];
for (var i = 0; i < workers; i++)
{
_threads[i] = new Thread(Loop) { IsBackground = true, Name = $"{name}-{i + 1}", Priority = ThreadPriority.BelowNormal };
_threads[i].Start();
}
}
/// <summary>How many threads take work.</summary>
public int Workers => _threads.Length;
public Task<T> RunAsync<T>(Func<T> work)
{
ArgumentNullException.ThrowIfNull(work);
var done = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
_work.Add(() =>
{
try
{
done.SetResult(work());
}
catch (Exception ex)
{
done.SetException(ex);
}
});
return done.Task;
}
private void Loop()
{
foreach (var item in _work.GetConsumingEnumerable())
{
item();
}
}
/// <summary>
/// Takes no more work and lets the threads finish what was handed over, waiting for them a while. The queue is released only
/// when every thread has left it: a thread still busy with a long piece of work must not find it gone.
/// </summary>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_work.CompleteAdding();
var watch = Stopwatch.StartNew();
var stopped = true;
foreach (var thread in _threads)
{
var left = JoinWait - watch.Elapsed;
stopped &= thread.Join(left > TimeSpan.Zero ? left : TimeSpan.Zero);
}
if (stopped)
{
_work.Dispose();
}
}
}
+135 -41
View File
@@ -107,11 +107,14 @@ public sealed record BacktestReport(
} }
/// <summary> /// <summary>
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own /// Runs a trial from its plan, on data already loaded (pure computation, no database), in two steps. <see cref="Variants"/>
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily /// does every engine execution, each one a unit with its own key (<see cref="TrialUnitKey"/>): every variant of the grid on
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan /// the whole period, the variant in use when the grid does not have it, then, once the plateau rule has chosen, the chosen
/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice, /// (or judged) variant with doubled and tripled costs, the benchmark and the look-ahead check. <see cref="Judge"/> then
/// the overfitting and the number of tries. The engine that runs the variants is an <see cref="ITrialEngine"/>: the daily one /// computes the validations, the checks and the report from those runs alone, assembled by key: the same report whether the
/// units ran in order on one thread, on several threads (<see cref="VariantsAsync"/>) or came back from the database after
/// a restart. A plan that names the variant to judge has the figures, the checks and the curve of that one: the grid still
/// gives the choice, the overfitting and the number of tries. The engine is an <see cref="ITrialEngine"/>: the daily one
/// (<see cref="DailyTrialEngine"/>) unless the caller gives another. /// (<see cref="DailyTrialEngine"/>) unless the caller gives another.
/// </summary> /// </summary>
public static class TrialRunner public static class TrialRunner
@@ -132,7 +135,7 @@ public static class TrialRunner
return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken); return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken);
} }
/// <summary>A trial of any family on any engine: the same validations, checks and report whatever the engine.</summary> /// <summary>A trial of any family on any engine: <see cref="Judge"/> of <see cref="Variants"/>, on the caller's thread.</summary>
public static (BacktestReport Report, TrialSummary Summary) Run( public static (BacktestReport Report, TrialSummary Summary) Run(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now, Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now,
Action<string>? progress = null, CancellationToken cancellationToken = default) Action<string>? progress = null, CancellationToken cancellationToken = default)
@@ -142,57 +145,125 @@ public static class TrialRunner
ArgumentNullException.ThrowIfNull(engine); ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(prior); ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
var sessions = engine.Sessions; var runs = Variants(plan, family, engine, progress, cancellationToken);
if (sessions < 30) cancellationToken.ThrowIfCancellationRequested();
{ progress?.Invoke("convalide");
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30."); return Judge(trialId, plan, planHash, family, engine, runs, prior, now, watch.Elapsed);
} }
var variants = ParameterGrid.Of(family, plan.Grid); /// <summary>
if (variants.Count == 0) /// Every engine execution of a trial, one after the other on the caller's thread, in the order the engine has always been
{ /// called: the grid, the variant in use outside it, the costed runs, the benchmark, the look-ahead check.
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri."); /// </summary>
} public static TrialRuns Variants(TrialPlan plan, IResearchFamily family, ITrialEngine engine, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
var runs = new BacktestRun[variants.Count]; var stages = new TrialStages(plan, family, engine);
for (var i = 0; i < variants.Count; i++) var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
foreach (var key in stages.First)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke($"variante {i + 1} di {variants.Count}"); progress?.Invoke(key.Kind == TrialUnitKind.Variant ? $"variante {key.Index + 1} di {stages.Grid.Count}" : "variante in uso");
runs[i] = engine.Run(variants[i].Parameters); results[key.Text] = stages.Execute(key);
} }
var returns = runs.Select(r => r.DailyReturns()).ToArray(); var said = false;
foreach (var key in stages.Second(results))
{
cancellationToken.ThrowIfCancellationRequested();
if (key.Kind == TrialUnitKind.LookAhead)
{
progress?.Invoke("test anti sguardo in avanti");
}
else if (!said)
{
progress?.Invoke("costi doppi e tripli, comprare e tenere");
said = true;
}
results[key.Text] = stages.Execute(key);
}
return stages.Assemble(results);
}
/// <summary>
/// The same executions handed to <paramref name="units"/> one stage at a time (a pool of threads, a store of finished
/// units): the grid and the variant in use first, the rest once the plateau rule has chosen. The results are assembled by
/// key, never in the order they finish, so the runs are those of <see cref="Variants"/>.
/// </summary>
public static async Task<TrialRuns> VariantsAsync(
TrialPlan plan, IResearchFamily family, ITrialEngine engine, ITrialUnits units, Action<string>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(units);
var stages = new TrialStages(plan, family, engine);
var results = new Dictionary<string, TrialUnitResult>(StringComparer.Ordinal);
var total = stages.First.Count + stages.SecondCount;
var finished = 0;
TrialUnitResult Execute(TrialUnitKey key)
{
cancellationToken.ThrowIfCancellationRequested();
var result = stages.Execute(key);
progress?.Invoke($"passo {Interlocked.Increment(ref finished)} di {total}");
return result;
}
foreach (var result in await units.RunAsync(stages.First, Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
Interlocked.Exchange(ref finished, results.Count);
foreach (var result in await units.RunAsync(stages.Second(results), Execute, cancellationToken).ConfigureAwait(false))
{
results[result.Key.Text] = result;
}
return stages.Assemble(results);
}
/// <summary>
/// The judge of a trial on runs already done: the plateau choice, the validations, the checks and the report. Pure: the
/// engine gives only its facts (sessions, currency, year, fingerprint, instruments, limitations) and what it expects of
/// the judged run. <paramref name="elapsed"/> is the time the runs took; the report adds the time of the judge.
/// </summary>
public static (BacktestReport Report, TrialSummary Summary) Judge(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, TrialRuns runs, PriorTrials prior, DateTimeOffset now, TimeSpan elapsed)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(runs);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = engine.Sessions;
var variants = runs.Variants;
if (runs.Grid.Count != variants.Count)
{
throw new InvalidOperationException("Every variant of the grid needs its run.");
}
var returns = runs.Grid.Select(r => r.DailyReturns()).ToArray();
var sharpes = returns.Select(r => Moments.Of(r).Sharpe).ToArray(); var sharpes = returns.Select(r => Moments.Of(r).Sharpe).ToArray();
var scores = Validation.PlateauScores(variants, sharpes); var scores = Validation.PlateauScores(variants, sharpes);
var chosenIndex = Validation.ChoosePlateau(variants, sharpes); var (chosenIndex, judged, judgedIndex) = Choose(plan, family, variants, sharpes);
var chosen = variants[chosenIndex]; var chosen = variants[chosenIndex];
var judged = plan.Judged is null ? chosen.Parameters : StrategyParameters.Of(family, plan.Judged);
var judgedIndex = plan.Judged is null ? chosenIndex : variants.ToList().FindIndex(x => x.ToString() == judged.ToString());
if (judgedIndex < 0)
{
progress?.Invoke("variante in uso");
}
var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex]; var run = judgedIndex < 0 ? runs.OutsideGrid ?? throw new InvalidOperationException("The variant in use outside the grid has no run.") : runs.Grid[judgedIndex];
var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex]; var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var year = engine.PeriodsPerYear; var year = engine.PeriodsPerYear;
var metrics = BacktestMetrics.Of(run, year); var metrics = BacktestMetrics.Of(run, year);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List<ReportCosts>(); var costs = new List<ReportCosts>();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order()) foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{ {
var costed = multiplier == 1m ? run : engine.Run(judged, multiplier); var costed = multiplier == 1m ? run : runs.Costed[multiplier];
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year); var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
} }
var benchmarkRun = engine.Benchmark(); var benchmarkRun = runs.Benchmark;
var benchmark = BacktestMetrics.Of(benchmarkRun, year); var benchmark = BacktestMetrics.Of(benchmarkRun, year);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
var days = run.Equity.Select(p => p.Day).ToArray(); var days = run.Equity.Select(p => p.Day).ToArray();
DateOnly DayOf(int returnIndex) => days[Math.Clamp(returnIndex + 1, 0, days.Length - 1)]; DateOnly DayOf(int returnIndex) => days[Math.Clamp(returnIndex + 1, 0, days.Length - 1)];
var v = plan.Validation; var v = plan.Validation;
@@ -212,8 +283,7 @@ public static class TrialRunner
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation; var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread); var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti"); var look = runs.LookAhead;
var look = engine.LookAhead(judged, v.LookAheadCuts);
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count, var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]); [.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -253,8 +323,8 @@ public static class TrialRunner
metrics, metrics,
benchmark, benchmark,
costs, costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult, [.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs.Grid[i].NetResult,
BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)), BacktestMetrics.Of(runs.Grid[i], year).MaxDrawdown, runs.Grid[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
.. judgedIndex >= 0 ? Array.Empty<ReportVariant>() .. judgedIndex >= 0 ? Array.Empty<ReportVariant>()
: [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]], : [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward, walkForward,
@@ -271,20 +341,44 @@ public static class TrialRunner
[.. run.Trades.TakeLast(MaxTrades)], [.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal), run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now, now,
watch.Elapsed.TotalSeconds) 0)
{ {
Judged = plan.Judged is null ? null : judged.ToString(), Judged = plan.Judged is null ? null : judged.ToString(),
Baskets = run.Baskets.Count == 0 ? null Baskets = run.Baskets.Count == 0 ? null
: [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))], : [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))],
}; };
var expected = engine.Expected(run, judgedReturns); var expected = engine.Expected(run, judgedReturns);
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 }; report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5, Seconds = (elapsed + watch.Elapsed).TotalSeconds };
var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes); dsr.Value, pbo?.Probability, sharpes);
return (report, summary); return (report, summary);
} }
/// <summary>
/// The plateau choice and the variant judged: the chosen one, or the one the plan names, with its place in the grid (-1
/// when the grid does not have it). The same rule for both stages of the runs and for the judge.
/// </summary>
internal static (int ChosenIndex, StrategyParameters Judged, int JudgedIndex) Choose(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants, IReadOnlyList<double> sharpes)
{
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var chosen = variants[chosenIndex];
var (named, namedIndex) = Named(plan, family, variants);
return named is null ? (chosenIndex, chosen.Parameters, chosenIndex) : (chosenIndex, named, namedIndex);
}
/// <summary>The variant the plan names, with its place in the grid (-1 when the grid does not have it); null when it names none.</summary>
internal static (StrategyParameters? Judged, int Index) Named(TrialPlan plan, IResearchFamily family, IReadOnlyList<Variant> variants)
{
if (plan.Judged is null)
{
return (null, -1);
}
var judged = StrategyParameters.Of(family, plan.Judged);
return (judged, variants.ToList().FindIndex(x => x.ToString() == judged.ToString()));
}
/// <summary>What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it).</summary> /// <summary>What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it).</summary>
public static IReadOnlyList<string> Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data) public static IReadOnlyList<string> Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data)
{ {
+196
View File
@@ -0,0 +1,196 @@
using System.Globalization;
using Anubis.Data;
namespace Anubis.Backtest;
/// <summary>
/// One sign a calendar day, +1 or −1, from <see cref="First"/> on: the same sign for every instrument on the same day. Two
/// datasets that must share their signs (the contenders of one tournament) draw them from the same first day and seed.
/// </summary>
public sealed class DaySigns
{
private readonly int[] _signs;
public DaySigns(DateOnly first, IReadOnlyList<int> signs)
{
ArgumentNullException.ThrowIfNull(signs);
if (signs.Any(s => s is not (1 or -1)))
{
throw new ArgumentException("A sign is +1 or −1.", nameof(signs));
}
First = first;
_signs = [.. signs];
}
/// <summary>The day of the first sign.</summary>
public DateOnly First { get; }
/// <summary>How many days have a sign.</summary>
public int Count => _signs.Length;
/// <summary>The day of the last sign (<see cref="First"/> when there is none).</summary>
public DateOnly Last => First.AddDays(Math.Max(_signs.Length - 1, 0));
/// <summary>The sign of <paramref name="day"/>; a day outside the signs is an error, never a default.</summary>
public int this[DateOnly day]
{
get
{
var at = day.DayNumber - First.DayNumber;
if (at < 0 || at >= _signs.Length)
{
throw new ArgumentOutOfRangeException(nameof(day), day, "No sign for this day.");
}
return _signs[at];
}
}
/// <summary>The signs of every calendar day from <paramref name="first"/> to <paramref name="last"/>, drawn with <see cref="TournamentStatistics.Signs"/>.</summary>
public static DaySigns Draw(DateOnly first, DateOnly last, int seed)
{
ArgumentOutOfRangeException.ThrowIfLessThan(last, first);
return new DaySigns(first, TournamentStatistics.Signs(last.DayNumber - first.DayNumber + 1, seed));
}
}
/// <summary>
/// The surrogate series of the control against chance (ADR 0026 point 4; appendix G.5 of the research document of
/// 2 December 2026): every day the returns of all the instruments change sign together, with probability one half. The
/// size of every day, the tails and the correlations between instruments stay; every tendency to revert or to go on is
/// lost. The strategy is then run again on the surrogate prices.
/// </summary>
/// <remarks>
/// <para>The work is on log returns from the previous close: open, high, low and close of day t, each as l = ln(p / close of
/// t − 1). With the sign s of the day, l becomes s·l, or μ + s·(l − μ) when centred, μ being the mean daily log return of
/// the instrument's closes over the loaded bars. Centred is for long-only rules: the drift stays, so a rule that only rides
/// it does as well on the surrogates as on the real data. When s = −1 the high and the low swap.</para>
/// <para>The first bar of each instrument stays as it is, the volume does not change, the value traded follows the close.
/// The surrogate covers the whole loaded history, the warm-up included. It is deterministic: no culture, no clock.
/// Instruments with corporate actions are refused for now.</para>
/// </remarks>
public static class Surrogates
{
/// <summary>The message of the refusal, for the user.</summary>
public const string CorporateActionsRefused = "Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.";
/// <summary>
/// The surrogate of a series of log returns: each one times the sign of its position, or, centred, around the mean of
/// the series. The absolute value of every return (centred: its distance from the mean) is kept exactly.
/// </summary>
public static double[] Flip(IReadOnlyList<double> logReturns, IReadOnlyList<int> signs, bool centred)
{
ArgumentNullException.ThrowIfNull(logReturns);
ArgumentNullException.ThrowIfNull(signs);
if (signs.Count < logReturns.Count)
{
throw new ArgumentException("One sign for every return.", nameof(signs));
}
var mean = centred && logReturns.Count > 0 ? logReturns.Average() : 0;
var result = new double[logReturns.Count];
for (var i = 0; i < result.Length; i++)
{
result[i] = Flip(logReturns[i], signs[i], centred, mean);
}
return result;
}
/// <summary>The surrogate of every instrument of <paramref name="data"/>, with signs drawn from <paramref name="seed"/> over its calendar days.</summary>
public static BacktestDataset Of(BacktestDataset data, int seed, bool centred)
{
ArgumentNullException.ThrowIfNull(data);
var days = data.Instruments.Where(i => i.Bars.Count > 0).ToList();
var signs = days.Count == 0
? new DaySigns(DateOnly.MinValue, [])
: DaySigns.Draw(days.Min(i => i.Bars[0].Day), days.Max(i => i.Bars[^1].Day), seed);
return Of(data, signs, centred);
}
/// <summary>The surrogate of every instrument of <paramref name="data"/>, the ones read only as data included, with the given signs.</summary>
public static BacktestDataset Of(BacktestDataset data, DaySigns signs, bool centred)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(signs);
if (data.Instruments.Any(i => i.Actions.Count > 0))
{
throw new NotSupportedException(CorporateActionsRefused);
}
return new BacktestDataset(
data.Instruments.Select(i => new BacktestInstrument(i.Spec, Bars(i.Bars, signs, centred), [], i.Source)),
data.Currency,
data.Calendar,
data.DataOnly);
}
/// <summary>The surrogate of one instrument's bars, oldest first, one per day.</summary>
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<DailyBar> bars, DaySigns signs, bool centred)
{
ArgumentNullException.ThrowIfNull(bars);
ArgumentNullException.ThrowIfNull(signs);
if (bars.Count == 0)
{
return [];
}
for (var i = 0; i < bars.Count; i++)
{
var b = bars[i];
if (!(b.Open > 0 && b.High > 0 && b.Low > 0 && b.Close > 0) || !double.IsFinite(b.Open + b.High + b.Low + b.Close))
{
throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture,
$"Il controllo contro il caso vuole prezzi positivi: la barra del {b.Day:yyyy-MM-dd} ne ha uno che non lo è."));
}
if (i > 0 && b.Day <= bars[i - 1].Day)
{
throw new ArgumentException("The bars must be in order of day, one a day.", nameof(bars));
}
}
var mean = 0.0;
if (centred && bars.Count > 1)
{
for (var i = 1; i < bars.Count; i++)
{
mean += Math.Log(bars[i].Close / bars[i - 1].Close);
}
mean /= bars.Count - 1;
}
var result = new List<DailyBar>(bars.Count) { bars[0] };
var previous = bars[0].Close;
var made = bars[0].Close;
for (var i = 1; i < bars.Count; i++)
{
var bar = bars[i];
var s = signs[bar.Day];
double Price(double p) => made * Math.Exp(Flip(Math.Log(p / previous), s, centred, mean));
var open = Price(bar.Open);
var close = Price(bar.Close);
var (high, low) = s > 0 ? (Price(bar.High), Price(bar.Low)) : (Price(bar.Low), Price(bar.High));
high = Math.Max(high, Math.Max(open, close));
low = Math.Min(low, Math.Min(open, close));
result.Add(bar with
{
Open = open,
High = high,
Low = low,
Close = close,
QuoteVolume = bar.QuoteVolume is { } value ? value * (close / bar.Close) : null,
Adjusted = null,
});
previous = bar.Close;
made = close;
}
return result;
}
private static double Flip(double l, int sign, bool centred, double mean) =>
centred ? mean + (sign * (l - mean)) : sign * l;
}
+261
View File
@@ -0,0 +1,261 @@
using System.Text.Json;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>The common number of trials N and where it comes from (ADR 0026 point 3): nothing is ever taken away.</summary>
public sealed record TournamentTrialsCount(int Field, int Combinations, int Registry, int Prior, int Total);
/// <summary>A contender of the report: its trial, the variant chosen on its plateau and the Sharpe of its walk-forward windows.</summary>
public sealed record TournamentContenderResult(
string Label,
string Strategy,
string Group,
string Market,
Guid TrialId,
string Status,
int Variants,
string? Chosen,
double? WalkForwardSharpe,
bool Finalist)
{
/// <summary>Why its trial failed; null when it did not.</summary>
public string? Error { get; init; }
}
/// <summary>An interval of a statistic: infinite on both sides when the series is too short to say anything.</summary>
public sealed record ReportInterval(double Low, double High);
/// <summary>
/// The control against chance of a finalist: its daily Sharpe ratio on the real search data, the share of surrogate
/// repetitions that do as well or better, and the median and the 95th percentile of the repetitions. Null figures and
/// <see cref="Unavailable"/> when the control cannot be run on its data.
/// </summary>
public sealed record TournamentControlResult(int Repetitions, int Seed, bool Centred, double Observed, double? Share, double? ReplicaMedian, double? ReplicaHigh)
{
/// <summary>Why the control could not run, in Italian; null when it ran.</summary>
public string? Unavailable { get; init; }
}
/// <summary>The chosen variant of a finalist on the final tract, read once: net result at plain and doubled costs, return, Sharpe and drawdown at plain costs.</summary>
public sealed record TournamentHoldoutResult(DateOnly From, DateOnly To, decimal NetResult, decimal NetAtDoubleCosts, double TotalReturn, double Sharpe, double MaxDrawdown);
/// <summary>A finalist with every figure of its verdict and the checks: it passes only when all of them pass.</summary>
public sealed record TournamentFinalistResult(
string Label,
string Strategy,
string Group,
string Market,
string Chosen,
int PeriodsPerYear,
double Sharpe,
DeflatedSharpe DeflatedSharpe,
ReportInterval SharpeInterval,
decimal NetAtDoubleCosts,
double MaxDrawdown,
bool LookAheadPassed,
TournamentControlResult Control,
TournamentHoldoutResult Holdout,
IReadOnlyList<ReportCheck> Checks,
bool Passed);
/// <summary>
/// The report of a tournament (ADR 0026 point 9): the common number of trials with its parts, the bar it sets, the variance of
/// the field, the common probability of overfitting, the effective number of bets of the finalists, every contender, every
/// finalist with its checks, and what the judge does not do yet. It passes when at least one finalist passes.
/// </summary>
public sealed record TournamentReport(
Guid TournamentId,
string Name,
string PlanHash,
TournamentTrialsCount Trials,
double Bar,
double FieldVariance,
ReportOverfitting? Overfitting,
double? EffectiveBets,
IReadOnlyList<TournamentContenderResult> Contenders,
IReadOnlyList<TournamentFinalistResult> Finalists,
int PassedCount,
bool Passed,
IReadOnlyList<string> Limitations,
DateTimeOffset ComputedAt,
double Seconds)
{
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static TournamentReport FromJson(string text) => JsonSerializer.Deserialize<TournamentReport>(text, TrialPlan.Json) ?? throw new JsonException("Empty tournament report");
}
/// <summary>Keys of the checks of a finalist that a single trial does not have.</summary>
public static class TournamentCheckKeys
{
public const string Control = "control";
public const string Holdout = "holdout";
}
/// <summary>The daily returns of one variant and the days they fall on (the day of the equity point each return ends at).</summary>
public sealed record VariantSeries(string Parameters, IReadOnlyList<DateOnly> Days, double[] Returns)
{
public static VariantSeries Of(string parameters, BacktestRun run)
{
ArgumentNullException.ThrowIfNull(run);
return new VariantSeries(parameters, [.. run.Equity.Skip(1).Select(p => p.Day)], run.DailyReturns());
}
}
/// <summary>What the judge knows of a contender: its trial and, when it is done, its report and the series of every variant of its grid.</summary>
public sealed record ContenderOutcome(TournamentContender Contender, Trial Trial, BacktestReport? Report, IReadOnlyList<VariantSeries> Variants)
{
/// <summary>The Sharpe ratio of the walk-forward windows; null when the trial failed or had too few days for them.</summary>
public double? WalkForwardSharpe => Report?.WalkForward is { } wf && double.IsFinite(wf.Sharpe) ? wf.Sharpe : null;
/// <summary>The series of the chosen variant.</summary>
public VariantSeries Chosen => Variants.FirstOrDefault(v => v.Parameters == (Report?.Judged ?? Report?.Chosen))
?? throw new InvalidOperationException("The chosen variant of " + Contender.Label + " has no run.");
}
/// <summary>What the units of a finalist gave: the repetitions of its control (none when unavailable) and its runs on the final tract by cost multiplier.</summary>
public sealed record FinalistOutcome(string Label, bool Centred, IReadOnlyList<double> Replicas, string? ControlUnavailable, IReadOnlyDictionary<decimal, BacktestRun> Holdout);
/// <summary>
/// The judge of a tournament on what its trials and units gave (ADR 0026 point 7): pure, no clock and no database. It chooses
/// the finalists, counts the trials, computes the common statistics and writes the report.
/// </summary>
public static class TournamentJudge
{
/// <summary>Rounds of the block bootstrap of the Sharpe interval of a finalist.</summary>
public const int IntervalRounds = 1000;
public const double IntervalConfidence = 0.95;
/// <summary>
/// The finalists, best first: among the contenders whose trial is done and has a walk-forward Sharpe, the best of every pair
/// of group and market, then the best <see cref="TournamentFinalists.Max"/> of them. Ties go to the contender written first.
/// </summary>
public static IReadOnlyList<string> Finalists(TournamentPlan plan, IReadOnlyList<ContenderOutcome> contenders)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(contenders);
var order = plan.Contenders.Select((c, i) => (c.Label, i)).ToDictionary(x => x.Label, x => x.i, StringComparer.Ordinal);
return
[
.. contenders
.Where(c => c.Trial.Status == TrialStatuses.Done && c.WalkForwardSharpe is not null)
.GroupBy(c => (c.Contender.Group, c.Contender.Market))
.Select(g => g.OrderByDescending(c => c.WalkForwardSharpe).ThenBy(c => order[c.Contender.Label]).First())
.OrderByDescending(c => c.WalkForwardSharpe).ThenBy(c => order[c.Contender.Label])
.Take(plan.Finalists.Max)
.Select(c => c.Contender.Label),
];
}
/// <summary>The report of the tournament from its contenders, its finalists (as stored when the final tract was opened) and their units.</summary>
public static TournamentReport Report(
Guid tournamentId, TournamentPlan plan, string planHash, IReadOnlyList<ContenderOutcome> contenders, IReadOnlyList<string> finalists,
IReadOnlyList<FinalistOutcome> outcomes, int registryVariants, DateTimeOffset now, TimeSpan elapsed)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(contenders);
ArgumentNullException.ThrowIfNull(finalists);
ArgumentNullException.ThrowIfNull(outcomes);
var watch = System.Diagnostics.Stopwatch.StartNew();
var done = contenders.Where(c => c.Report is not null).ToList();
// N: every planned variant of every contender, failed or not, the combinations of the finalists, the register and what was tried outside it.
var count = new TournamentTrialsCount(
contenders.Sum(c => c.Trial.Variants),
TournamentStatistics.Combinations(finalists.Count, plan.Combinations.WeightSchemes.Count),
registryVariants,
plan.PriorCounted.Sum(p => p.Variants),
0);
count = count with { Total = TournamentStatistics.CommonTrials(count.Field, count.Combinations, count.Registry, count.Prior) };
var field = TournamentStatistics.FieldVariance([.. done.Select(c => new FieldSharpes(c.Report!.PeriodsPerYear, [.. c.Report.Variants.Where(v => !v.OutsideGrid).Select(v => v.Sharpe)]))]);
var all = TournamentStatistics.Align([.. done.SelectMany(c => c.Variants).Select(v => (v.Days, (IReadOnlyList<double>)v.Returns))]);
var pbo = TournamentStatistics.CommonOverfitting(all, plan.Validation.OverfittingGroups);
var overfitting = pbo is null ? null : new ReportOverfitting(pbo.Groups, pbo.Combinations, pbo.Variants, pbo.Probability);
var byLabel = contenders.ToDictionary(c => c.Contender.Label, StringComparer.Ordinal);
var chosen = finalists.Select(f => byLabel[f].Chosen).ToList();
double? bets = chosen.Count == 0 ? null
: TournamentStatistics.EffectiveBets(TournamentStatistics.Align([.. chosen.Select(v => (v.Days, (IReadOnlyList<double>)v.Returns))]).Returns);
var outcomeOf = outcomes.ToDictionary(o => o.Label, StringComparer.Ordinal);
var results = finalists.Select(f => Finalist(plan, byLabel[f], outcomeOf[f], count.Total, field, pbo)).ToList();
var passed = results.Count(r => r.Passed);
List<string> limitations =
[
"La varianza del campo conta solo le varianti dei concorrenti di questo campionato: le prove fatte prima entrano nel numero delle prove, non nella varianza.",
"I mercati con calendari diversi (crypto tutti i giorni, valute e azioni nei giorni feriali) sono messi su un solo calendario: un giorno senza seduta vale un rendimento zero.",
Surrogates.CorporateActionsRefused,
"Le combinazioni dei finalisti e le prove di stress arrivano nella Fase 16: le combinazioni contano già nel numero delle prove.",
];
limitations.AddRange(contenders.Where(c => c.Trial.Status == TrialStatuses.Failed)
.Select(c => $"La prova del concorrente «{c.Contender.Label}» non è arrivata in fondo: non può essere finalista, ma le sue varianti contano lo stesso."));
return new TournamentReport(
tournamentId,
plan.Name,
planHash,
count,
TournamentStatistics.Bar(count.Total),
field,
overfitting,
bets,
[.. contenders.Select(c => new TournamentContenderResult(c.Contender.Label, c.Contender.Strategy, c.Contender.Group, c.Contender.Market, c.Trial.Id, c.Trial.Status,
c.Trial.Variants, c.Report?.Judged ?? c.Report?.Chosen, c.WalkForwardSharpe, finalists.Contains(c.Contender.Label, StringComparer.Ordinal)) { Error = c.Trial.Error })],
results,
passed,
passed > 0,
limitations,
now,
(elapsed + watch.Elapsed).TotalSeconds);
}
private static TournamentFinalistResult Finalist(TournamentPlan plan, ContenderOutcome contender, FinalistOutcome outcome, int trials, double field, OverfittingResult? pbo)
{
var report = contender.Report!;
var series = contender.Chosen;
var year = report.PeriodsPerYear;
var moments = Moments.Of(series.Returns);
var dsr = TournamentStatistics.CommonDeflated(series.Returns, year, trials, field);
var (low, high) = TournamentStatistics.Interval(series.Returns, s => Moments.Of(s).Sharpe, PathBootstrap.Block, IntervalRounds, IntervalConfidence, plan.Control.Seed);
var sorted = outcome.Replicas.Order().ToArray();
var control = outcome.ControlUnavailable is not null || sorted.Length == 0
? new TournamentControlResult(plan.Control.Repetitions, plan.Control.Seed, outcome.Centred, moments.Sharpe, null, null, null) { Unavailable = outcome.ControlUnavailable }
: new TournamentControlResult(plan.Control.Repetitions, plan.Control.Seed, outcome.Centred, moments.Sharpe, TournamentStatistics.ControlShare(moments.Sharpe, sorted),
Percentile(sorted, 0.5), Percentile(sorted, 0.95));
var plain = outcome.Holdout[1m];
var doubledRun = outcome.Holdout[2m];
var metrics = BacktestMetrics.Of(plain, year);
var holdout = new TournamentHoldoutResult(plan.HoldoutFrom, contender.Contender.Data.To, plain.NetResult, doubledRun.NetResult, metrics.TotalReturn, metrics.Sharpe,
metrics.MaxDrawdown);
var t = plan.Thresholds;
var doubled = report.Costs.FirstOrDefault(c => c.Multiplier == 2m);
List<ReportCheck> checks =
[
new(ReportCheckKeys.DoubleCosts, "Risultato netto con costi doppi", doubled is null ? null : (double)doubled.NetResult, ">", (double)t.MinNetAtDoubleCosts, "money",
doubled is not null && doubled.NetResult > t.MinNetAtDoubleCosts),
new(ReportCheckKeys.DeflatedSharpe, "Deflated Sharpe Ratio sul numero comune di prove", dsr.Value, "≥", t.MinDeflatedSharpe, "ratio", dsr.Value >= t.MinDeflatedSharpe),
new(ReportCheckKeys.Overfitting, "Probabilità di sovra-adattamento di tutto il campo (PBO)", pbo?.Probability, "≤", t.MaxOverfitting, "ratio",
pbo is not null && pbo.Probability <= t.MaxOverfitting),
new(ReportCheckKeys.Drawdown, "Calo massimo", report.Metrics.MaxDrawdown, "≤", t.MaxDrawdown, "percent", report.Metrics.MaxDrawdown <= t.MaxDrawdown),
new(ReportCheckKeys.LookAhead, "Decisioni cambiate aggiungendo dati successivi", report.LookAhead.Changed, "=", 0, "count", report.LookAhead.Passed),
new(TournamentCheckKeys.Control, "Controllo contro il caso: quota di copie pari o migliori", control.Share, "≤", t.MaxControlShare, "ratio",
control.Share is { } share && share <= t.MaxControlShare),
new(TournamentCheckKeys.Holdout, "Risultato netto sul tratto finale con costi doppi", (double)holdout.NetAtDoubleCosts, "≥", (double)t.MinNetAtDoubleCosts, "money",
holdout.NetAtDoubleCosts >= t.MinNetAtDoubleCosts),
];
return new TournamentFinalistResult(contender.Contender.Label, contender.Contender.Strategy, contender.Contender.Group, contender.Contender.Market, series.Parameters, year,
moments.Sharpe, dsr, new ReportInterval(low, high), doubled?.NetResult ?? 0m, report.Metrics.MaxDrawdown, report.LookAhead.Passed, control, holdout, checks,
checks.All(c => c.Passed == true));
}
// The value at a share of a sorted list, by the nearest rank below.
private static double Percentile(double[] sorted, double share) => sorted[(int)Math.Floor(share * (sorted.Length - 1))];
}
+294
View File
@@ -0,0 +1,294 @@
using Anubis.Core;
namespace Anubis.Backtest;
/// <summary>The returns of several series on one calendar: <see cref="Returns"/>[k][d] is the return of series k on <see cref="Days"/>[d].</summary>
public sealed record AlignedReturns(IReadOnlyList<DateOnly> Days, IReadOnlyList<double[]> Returns);
/// <summary>The daily Sharpe ratios of every variant of one contender, and the sessions in its year (365 crypto, 252 stocks and currencies).</summary>
public sealed record FieldSharpes(int PeriodsPerYear, IReadOnlyList<double> DailySharpes);
/// <summary>
/// The statistics of the tournament (ADR 0026, Phase 13), pure and written in house: one number of trials for the whole
/// field, the bar it sets, the variance of the field, the probability of overfitting of every variant together, the effective
/// number of bets, the control against chance and a bootstrap interval that keeps neighbouring days together. Each function
/// computes one thing from its arguments; none reads a clock or a database.
/// </summary>
public static class TournamentStatistics
{
/// <summary>
/// The common number of trials N of the deflated Sharpe ratio: every variant of every contender, every combination of
/// finalists, every variant already in the register and every variant tried before outside it (the protocols of
/// <c>docs/backtests</c>). Nothing is taken away: a failed contender still counts.
/// </summary>
public static int CommonTrials(int fieldVariants, int combinations, int registryVariants, int priorCounted)
{
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariants);
ArgumentOutOfRangeException.ThrowIfNegative(combinations);
ArgumentOutOfRangeException.ThrowIfNegative(registryVariants);
ArgumentOutOfRangeException.ThrowIfNegative(priorCounted);
return checked(fieldVariants + combinations + registryVariants + priorCounted);
}
/// <summary>
/// The combinations of finalists the plan counts: every pair and the whole set, each with every weighting scheme. Eight
/// finalists and three schemes give (28 + 1) × 3 = 87; fewer than two finalists give none.
/// </summary>
public static int Combinations(int finalists, int weightSchemes)
{
ArgumentOutOfRangeException.ThrowIfNegative(finalists);
ArgumentOutOfRangeException.ThrowIfNegative(weightSchemes);
return finalists < 2 ? 0 : checked(((finalists * (finalists - 1) / 2) + 1) * weightSchemes);
}
/// <summary>
/// The bar the plan shows before the start: the Sharpe ratio the best of <paramref name="trials"/> tries of nothing would
/// show by chance alone, in standard deviations of the field. Zero for one trial.
/// </summary>
public static double Bar(int trials) => SharpeTests.ExpectedMaximum(trials, 1);
/// <summary>
/// Puts series of different calendars on one: the union of their days inside the common window, from the latest first day
/// to the earliest last day. A day without a session for a series is a return of zero, because its equity does not move
/// (crypto trades every day, stocks and currencies on weekdays). Each series gives its days in increasing order and one
/// return per day.
/// </summary>
public static AlignedReturns Align(IReadOnlyList<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)> series)
{
ArgumentNullException.ThrowIfNull(series);
foreach (var (days, returns) in series)
{
ArgumentNullException.ThrowIfNull(days);
ArgumentNullException.ThrowIfNull(returns);
if (days.Count != returns.Count)
{
throw new ArgumentException("Every series needs one return per day.", nameof(series));
}
for (var i = 1; i < days.Count; i++)
{
if (days[i] <= days[i - 1])
{
throw new ArgumentException("The days of a series must be in increasing order, each once.", nameof(series));
}
}
}
if (series.Count == 0 || series.Any(s => s.Days.Count == 0))
{
return new AlignedReturns([], [.. series.Select(_ => Array.Empty<double>())]);
}
var first = series.Max(s => s.Days[0]);
var last = series.Min(s => s.Days[^1]);
var calendar = series.SelectMany(s => s.Days).Where(d => d >= first && d <= last).Distinct().Order().ToList();
var position = new Dictionary<DateOnly, int>(calendar.Count);
for (var i = 0; i < calendar.Count; i++)
{
position[calendar[i]] = i;
}
var aligned = new List<double[]>(series.Count);
foreach (var (days, returns) in series)
{
var values = new double[calendar.Count];
for (var i = 0; i < days.Count; i++)
{
if (position.TryGetValue(days[i], out var at))
{
values[at] = returns[i];
}
}
aligned.Add(values);
}
return new AlignedReturns(calendar, aligned);
}
/// <summary>
/// The variance of the field: the sample variance of the annual Sharpe ratios (daily × √P) of every variant of every
/// contender, so that a crypto year of 365 days and a stock year of 252 are compared in the same unit. Variants counted
/// before the tournament count in N but not here, because their ratios are not all kept: the field is the variance.
/// Zero with fewer than two variants.
/// </summary>
public static double FieldVariance(IReadOnlyList<FieldSharpes> field)
{
ArgumentNullException.ThrowIfNull(field);
var annual = new List<double>();
foreach (var contender in field)
{
ArgumentNullException.ThrowIfNull(contender);
ArgumentOutOfRangeException.ThrowIfLessThan(contender.PeriodsPerYear, 1);
var root = Math.Sqrt(contender.PeriodsPerYear);
annual.AddRange(contender.DailySharpes.Select(s => s * root));
}
var deviation = Moments.Of([.. annual]).StandardDeviation;
return deviation * deviation;
}
/// <summary>
/// The deflated Sharpe ratio of one contender against the whole field: its daily returns (Sharpe, length, skewness and
/// kurtosis), the common number of trials and the variance of the field brought back to daily with the contender's own
/// year (annual variance / P).
/// </summary>
public static DeflatedSharpe CommonDeflated(ReadOnlySpan<double> returns, int periodsPerYear, int trials, double fieldVariance)
{
ArgumentOutOfRangeException.ThrowIfLessThan(periodsPerYear, 1);
ArgumentOutOfRangeException.ThrowIfNegative(fieldVariance);
return SharpeTests.Deflated(returns, trials, fieldVariance / periodsPerYear);
}
/// <summary>
/// The probability of overfitting of the whole field (CSCV, <see cref="Validation.Overfitting"/>): every variant of every
/// contender, on one calendar. Null when it cannot be computed (fewer than two variants or too few days).
/// </summary>
public static OverfittingResult? CommonOverfitting(AlignedReturns aligned, int groups = 16)
{
ArgumentNullException.ThrowIfNull(aligned);
return Validation.Overfitting(aligned.Returns, groups);
}
/// <summary>
/// The seed of repetition <paramref name="repetition"/> of the control: the plan's seed plus the repetition, wrapping
/// around instead of failing, so repetition k always draws the same signs.
/// </summary>
public static int ReplicaSeed(int seed, int repetition)
{
ArgumentOutOfRangeException.ThrowIfNegative(repetition);
return unchecked(seed + repetition);
}
/// <summary>
/// The signs of a surrogate: one per calendar day, +1 or −1 with the same probability, drawn in order from
/// <see cref="SeededRandom"/> with <paramref name="seed"/>. Every instrument takes the sign of its day.
/// </summary>
public static int[] Signs(int days, int seed)
{
ArgumentOutOfRangeException.ThrowIfNegative(days);
var random = new SeededRandom(seed);
var signs = new int[days];
for (var i = 0; i < days; i++)
{
signs[i] = random.Bool() ? 1 : -1;
}
return signs;
}
/// <summary>
/// The share of replicas on surrogate series that do as well as the real result or better: count(replica ≥ observed) /
/// count. The control passes when it is at most the plan's threshold (0.05: the real result beats at least 190 of 200).
/// What cannot be compared never helps: an observed NaN gives 1 and a NaN replica counts as at least as good.
/// </summary>
public static double ControlShare(double observed, IReadOnlyList<double> replicas)
{
ArgumentNullException.ThrowIfNull(replicas);
ArgumentOutOfRangeException.ThrowIfZero(replicas.Count);
if (double.IsNaN(observed))
{
return 1;
}
return (double)replicas.Count(r => double.IsNaN(r) || r >= observed) / replicas.Count;
}
/// <summary>
/// A bootstrap interval of <paramref name="statistic"/> that keeps neighbouring days together: each of
/// <paramref name="rounds"/> resamples is made of blocks of <paramref name="block"/> days in a row, starting at random
/// and going round the end of the series (circular moving blocks), until it is as long as the series. The bounds are the
/// percentiles of the sorted statistics, with the convention of <c>Learning.Judge.Interval</c>. With fewer than three
/// blocks nothing can be said: the interval is everything.
/// </summary>
public static (double Low, double High) Interval(IReadOnlyList<double> returns, Func<ReadOnlySpan<double>, double> statistic, int block, int rounds, double confidence, int seed)
{
ArgumentNullException.ThrowIfNull(returns);
ArgumentNullException.ThrowIfNull(statistic);
ArgumentOutOfRangeException.ThrowIfLessThan(block, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(rounds, 1);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(confidence);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(confidence, 1);
var n = returns.Count;
if (n < 3 * block)
{
return (double.NegativeInfinity, double.PositiveInfinity);
}
var random = new SeededRandom(seed);
var sample = new double[n];
var values = new double[rounds];
for (var r = 0; r < rounds; r++)
{
for (var filled = 0; filled < n;)
{
var start = random.Int(0, n);
for (var k = 0; k < block && filled < n; k++, filled++)
{
sample[filled] = returns[(start + k) % n];
}
}
values[r] = statistic(sample);
}
Array.Sort(values);
var tail = (1 - confidence) / 2;
return (values[(int)Math.Floor(tail * (rounds - 1))], values[(int)Math.Ceiling((1 - tail) * (rounds - 1))]);
}
/// <summary>
/// The effective number of independent bets among series on one calendar: the participation ratio of their correlation
/// matrix, n² / Σᵢⱼ ρᵢⱼ², which needs no eigenvalues (the trace of R is n, the trace of R² is Σρ²). Identical series are
/// one bet, uncorrelated series are n. A flat series is correlated only with itself.
/// </summary>
public static double EffectiveBets(IReadOnlyList<double[]> aligned)
{
ArgumentNullException.ThrowIfNull(aligned);
var n = aligned.Count;
if (n == 0)
{
return 0;
}
var length = aligned[0].Length;
if (aligned.Any(s => s is null || s.Length != length))
{
throw new ArgumentException("Every series needs the same days.", nameof(aligned));
}
// Centred series and their norms, once.
var centred = new double[n][];
var norms = new double[n];
for (var i = 0; i < n; i++)
{
var mean = length > 0 ? aligned[i].Average() : 0;
centred[i] = [.. aligned[i].Select(x => x - mean)];
norms[i] = Math.Sqrt(centred[i].Sum(x => x * x));
}
var squares = 0.0;
for (var i = 0; i < n; i++)
{
squares += 1; // ρᵢᵢ = 1, flat or not
for (var j = i + 1; j < n; j++)
{
if (norms[i] <= 0 || norms[j] <= 0)
{
continue;
}
var dot = 0.0;
for (var t = 0; t < length; t++)
{
dot += centred[i][t] * centred[j][t];
}
var rho = Math.Clamp(dot / (norms[i] * norms[j]), -1, 1);
squares += 2 * rho * rho;
}
}
return (double)n * n / squares;
}
}
+473
View File
@@ -0,0 +1,473 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Backtest;
/// <summary>
/// The thresholds of a tournament, fixed in its plan: those of a trial (SPEC 12.2) and the control against chance (ADR 0026
/// point 4). Changing them after seeing the results needs an ADR.
/// </summary>
public sealed record TournamentThresholds(decimal MinNetAtDoubleCosts, double MinDeflatedSharpe, double MaxOverfitting, double MaxDrawdown, double MaxControlShare)
{
public static TournamentThresholds Default { get; } = new(
TrialThresholds.Default.MinNetAtDoubleCosts, TrialThresholds.Default.MinDeflatedSharpe, TrialThresholds.Default.MaxOverfitting, TrialThresholds.Default.MaxDrawdown, 0.05);
}
/// <summary>Words of the rules a plan writes down.</summary>
public static class TournamentRules
{
/// <summary>At most one finalist for every pair of group and market.</summary>
public const string GroupAndMarket = "group_and_market";
/// <summary>Finalists are ranked by the Sharpe ratio of their walk-forward windows.</summary>
public const string WalkForwardSharpe = "walk_forward_sharpe";
public const string Pairs = "pairs";
public const string Whole = "whole";
public const string EqualWeights = "equal";
public const string InverseVolatility = "inverse_volatility";
public const string RiskParity = "risk_parity";
public const string Quarterly = "quarterly";
}
/// <summary>Who goes on to the final stage: at most <see cref="Max"/>, one per group and market, the best by walk-forward Sharpe.</summary>
public sealed record TournamentFinalists(int Max, string OnePer, string RankedBy)
{
public static TournamentFinalists Default { get; } = new(8, TournamentRules.GroupAndMarket, TournamentRules.WalkForwardSharpe);
}
/// <summary>The control against chance of every finalist: how many surrogate series and the seed of their signs.</summary>
public sealed record TournamentControl(int Repetitions, int Seed)
{
public static TournamentControl Default { get; } = new(200, 20_261_202);
}
/// <summary>
/// The combinations of finalists (ADR 0026 point 8), written in the plan now and run in Phase 16: every pair and the whole set,
/// with each weighting scheme, reading only the <see cref="LookbackDays"/> before and rebalanced every quarter. They count in
/// the number of trials from now on.
/// </summary>
public sealed record TournamentCombinations(IReadOnlyList<string> Sets, IReadOnlyList<string> WeightSchemes, int LookbackDays, string Rebalance)
{
public static TournamentCombinations Default { get; } = new(
[TournamentRules.Pairs, TournamentRules.Whole],
[TournamentRules.EqualWeights, TournamentRules.InverseVolatility, TournamentRules.RiskParity],
180,
TournamentRules.Quarterly);
}
/// <summary>A named period of stress, recorded in the plan now; the stress tests run in Phase 16.</summary>
public sealed record StressWindow(string Name, DateOnly From, DateOnly To)
{
public static IReadOnlyList<StressWindow> Defaults { get; } =
[
new("Crollo di marzo 2020", new DateOnly(2020, 2, 19), new DateOnly(2020, 3, 23)),
new("Inverno delle crypto 2022", new DateOnly(2022, 5, 5), new DateOnly(2022, 12, 31)),
];
}
/// <summary>Variants tried before, outside the register (the protocols of <c>docs/backtests</c>): they count in N.</summary>
public sealed record PriorCount(string Source, string Strategy, int Variants)
{
public static IReadOnlyList<PriorCount> Defaults { get; } =
[
new("docs/backtests", StrategyNames.CryptoTrend, 18),
new("docs/backtests", StrategyNames.CryptoRelativeMomentum, 9),
];
}
/// <summary>
/// A contender of the plan: a fixed rule (its version) with the numbers of its grid, a group and a market, and its data over
/// the whole period, the final tract included. Its trial reads only up to the day before <see cref="TournamentPlan.HoldoutFrom"/>.
/// </summary>
public sealed record TournamentContender(
string Label,
string Strategy,
string StrategyVersion,
string Group,
string Market,
IReadOnlyDictionary<string, IReadOnlyList<decimal>> Grid,
TrialData Data,
int Variants);
/// <summary>
/// The plan of a tournament (ADR 0026 point 2): contenders, data, costs, thresholds, the rule of the finalists, the control,
/// the combinations, the stress windows and the variants already counted, written before any result and never changed. Its
/// fingerprint is the SHA-256 of the text as stored, as for a trial (<see cref="TrialPlan.Hash"/>). <see cref="PlannedTrials"/>
/// and <see cref="Bar"/> are what the plan shows before the start: the number of trials it expects and the Sharpe ratio, in
/// standard deviations of the field, that chance alone would reach with so many.
/// </summary>
public sealed record TournamentPlan(
string Name,
IReadOnlyList<TournamentContender> Contenders,
DateOnly HoldoutFrom,
decimal InitialCapital,
IReadOnlyList<decimal> CostMultipliers,
TournamentThresholds Thresholds,
TournamentFinalists Finalists,
TournamentControl Control,
TournamentCombinations Combinations,
IReadOnlyList<StressWindow> StressWindows,
IReadOnlyList<PriorCount> PriorCounted,
int RegistryVariantsAtPlanning,
int PlannedTrials,
double Bar,
TrialValidation Validation,
string Engine,
DateTimeOffset WrittenAt)
{
/// <summary>The slippage in force when the plan was written (SPEC 11.6); null for the standard one.</summary>
public SlippageTable? Slippage { get; init; }
/// <summary>The last day of the search: the trials of the contenders end here.</summary>
public DateOnly SearchTo => HoldoutFrom.AddDays(-1);
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static TournamentPlan FromJson(string text) => JsonSerializer.Deserialize<TournamentPlan>(text, TrialPlan.Json) ?? throw new JsonException("Empty tournament plan");
}
/// <summary>A contender as the user asks for it: the plan fills in the version, the grid and the count of variants.</summary>
public sealed record ContenderRequest(
string Label,
string Strategy,
string Group,
string Market,
string Source,
string Venue,
IReadOnlyList<string> Symbols,
DateOnly From,
DateOnly To,
IReadOnlyDictionary<string, IReadOnlyList<decimal>>? Grid = null);
/// <summary>What a new tournament is: its contenders, the first day of the final tract and the capital of every trial.</summary>
public sealed record TournamentRequest(string Name, IReadOnlyList<ContenderRequest> Contenders, DateOnly HoldoutFrom, decimal InitialCapital)
{
/// <summary>The control of the plan; null for 200 repetitions and the default seed.</summary>
public TournamentControl? Control { get; init; }
/// <summary>The variants tried outside the register; null for those of <c>docs/backtests</c>.</summary>
public IReadOnlyList<PriorCount>? PriorCounted { get; init; }
/// <summary>The stress windows; null for the default ones.</summary>
public IReadOnlyList<StressWindow>? StressWindows { get; init; }
}
/// <summary>A tournament plan that cannot be written, with the reason in Italian. Nothing is written.</summary>
public sealed class TournamentPlanException(string message) : Exception(message);
/// <summary>Builds and checks the plan of a tournament: pure, nothing is read or written.</summary>
public static class TournamentPlans
{
public const int MaxContenders = 100;
public const int MaxRepetitions = 10_000;
/// <summary>The shortest final tract, in calendar days.</summary>
public const int MinHoldoutDays = 30;
/// <summary>
/// The plan of <paramref name="request"/> and the plans of the trials of its contenders, which read the search window only
/// (to the day before the final tract). Every check fails with an Italian message before anything is built.
/// </summary>
public static (TournamentPlan Plan, IReadOnlyList<(TrialPlan Plan, int Variants)> Trials) BuildPlan(
TournamentRequest request, DateTimeOffset now, int registryVariants, Func<string, IStrategyFamily?> families, SlippageTable? slippage = null)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(families);
ArgumentOutOfRangeException.ThrowIfNegative(registryVariants);
var it = CultureInfo.GetCultureInfo("it-IT");
if (string.IsNullOrWhiteSpace(request.Name))
{
throw new TournamentPlanException("Dai un nome al campionato.");
}
if (request.Contenders is not { Count: > 0 })
{
throw new TournamentPlanException("Serve almeno un concorrente.");
}
if (request.Contenders.Count > MaxContenders)
{
throw new TournamentPlanException($"Al massimo {MaxContenders} concorrenti per campionato.");
}
var thresholds = TournamentThresholds.Default;
var control = request.Control ?? TournamentControl.Default;
var fewest = (int)Math.Ceiling(Math.Round(1 / thresholds.MaxControlShare, 9)); // 1 / 0.05 is 20, not a hair more
if (control.Repetitions < fewest || control.Repetitions > MaxRepetitions)
{
throw new TournamentPlanException($"Le ripetizioni del controllo contro il caso vanno da {fewest} a {MaxRepetitions}.");
}
var prior = request.PriorCounted ?? PriorCount.Defaults;
if (prior.Any(p => p is null || p.Variants < 0 || string.IsNullOrWhiteSpace(p.Strategy)))
{
throw new TournamentPlanException("Le prove già contate hanno bisogno di una strategia e di un numero non negativo di varianti.");
}
var stress = request.StressWindows ?? StressWindow.Defaults;
if (stress.FirstOrDefault(w => w is null || string.IsNullOrWhiteSpace(w.Name) || w.From > w.To) is { } wrong)
{
throw new TournamentPlanException($"La finestra di stress «{wrong?.Name}» non ha un nome o finisce prima di cominciare.");
}
var contenders = new List<TournamentContender>();
var trials = new List<(TrialPlan Plan, int Variants)>();
var labels = new HashSet<string>(StringComparer.Ordinal);
foreach (var c in request.Contenders)
{
var label = c?.Label?.Trim() ?? "";
if (c is null || label.Length == 0)
{
throw new TournamentPlanException("Ogni concorrente ha bisogno di un'etichetta.");
}
if (!labels.Add(label))
{
throw new TournamentPlanException($"L'etichetta «{label}» è usata due volte.");
}
if (string.IsNullOrWhiteSpace(c.Group) || string.IsNullOrWhiteSpace(c.Market))
{
throw new TournamentPlanException($"Il concorrente «{label}» ha bisogno di un gruppo e di un mercato.");
}
if (request.HoldoutFrom.AddDays(-1) <= c.From)
{
throw new TournamentPlanException(string.Create(it, $"Il tratto finale deve cominciare dopo l'inizio di «{label}», che comincia il {c.From:dd/MM/yyyy}."));
}
if (c.To.DayNumber - request.HoldoutFrom.DayNumber + 1 < MinHoldoutDays)
{
throw new TournamentPlanException(string.Create(it, $"Il tratto finale di «{label}» deve durare almeno {MinHoldoutDays} giorni: i suoi dati finiscono il {c.To:dd/MM/yyyy}."));
}
var family = families(c.Strategy) ?? throw new TournamentPlanException($"Concorrente «{label}»: strategia sconosciuta.");
(TrialPlan Plan, int Variants) trial;
try
{
trial = Laboratory.BuildPlan(new TrialRequest(c.Strategy, c.Source, c.Venue, c.Symbols, c.From, request.HoldoutFrom.AddDays(-1), request.InitialCapital, c.Grid),
now, slippage, families);
}
catch (TrialRequestException ex)
{
throw new TournamentPlanException($"Concorrente «{label}»: {ex.Message}");
}
trials.Add(trial);
contenders.Add(new TournamentContender(label, family.Id, family.Version, c.Group.Trim(), c.Market.Trim(), trial.Plan.Grid,
trial.Plan.Data with { To = c.To }, trial.Variants));
}
var combinations = TournamentCombinations.Default;
var finalists = TournamentFinalists.Default;
var places = Math.Min(finalists.Max, contenders.Select(c => (c.Group, c.Market)).Distinct().Count());
var planned = TournamentStatistics.CommonTrials(contenders.Sum(c => c.Variants), TournamentStatistics.Combinations(places, combinations.WeightSchemes.Count),
registryVariants, prior.Sum(p => p.Variants));
var plan = new TournamentPlan(
request.Name.Trim(),
contenders,
request.HoldoutFrom,
request.InitialCapital,
[1m, 2m, 3m],
thresholds,
finalists,
control,
combinations,
stress,
prior,
registryVariants,
planned,
TournamentStatistics.Bar(planned),
TrialValidation.Default,
BacktestEngine.Version,
now)
{
Slippage = slippage == SlippageTable.Standard ? null : slippage,
};
return (plan, trials);
}
}
public static class TournamentStatuses
{
public const string Planned = "planned";
public const string Running = "running";
public const string Judging = "judging";
public const string Done = "done";
public const string Failed = "failed";
}
/// <summary>A row of the register of the tournaments.</summary>
public sealed record Tournament(
Guid Id,
string Name,
TournamentPlan Plan,
string PlanHash,
string Status,
string? Verdict,
IReadOnlyList<string>? Finalists,
string? Error,
DateTimeOffset? HoldoutOpenedAt,
DateTimeOffset CreatedAt,
DateTimeOffset? StartedAt,
DateTimeOffset? FinishedAt)
{
public bool IsFinished => Status is TournamentStatuses.Done or TournamentStatuses.Failed;
/// <summary>The stored plan text still gives the stored hash: nobody changed it after it was written.</summary>
public bool PlanIntact { get; init; } = true;
}
/// <summary>
/// The register of the tournaments (ADR 0026). The plan and the trials of the contenders are written in one transaction before
/// any result, and the plan is never updated. The final tract is opened once: the finalists are written with the moment it
/// was opened, and a second opening gets back the first finalists.
/// </summary>
public sealed class TournamentStore(Database db, IClock clock)
{
private const string Columns = "id, name, plan, plan_hash, status, verdict, finalists, error, holdout_opened_at, created_at, started_at, finished_at";
/// <summary>The plan and the trials of its contenders, in the order of the plan, all planned.</summary>
public async Task<Tournament> PlanAsync(TournamentPlan plan, IReadOnlyList<(TrialPlan Plan, int Variants)> trials, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(trials);
if (trials.Count != plan.Contenders.Count)
{
throw new ArgumentException("One trial for every contender.", nameof(trials));
}
var id = await db.WriteAsync(async s =>
{
var id = Ids.NewId(clock);
var json = plan.ToJson();
await s.ExecuteAsync(
"INSERT INTO tournaments (id, name, plan, plan_hash, status, created_at) VALUES (@id, @n, @p, @h, @st, @now)",
cancellationToken, ("id", id), ("n", plan.Name), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("st", TournamentStatuses.Planned),
("now", clock.UtcNow)).ConfigureAwait(false);
foreach (var (trial, variants) in trials)
{
await TrialStore.PlanAsync(s, clock, trial, variants, null, id, cancellationToken).ConfigureAwait(false);
}
return id;
}, cancellationToken).ConfigureAwait(false);
return (await GetAsync(id, cancellationToken).ConfigureAwait(false))!;
}
public Task<Tournament?> GetAsync(Guid id, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM tournaments WHERE id = @id", Read, ("id", id)), cancellationToken);
public Task<string?> ReportJsonAsync(Guid id, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT report FROM tournaments WHERE id = @id AND report IS NOT NULL", r => r.Json("report").Text, ("id", id)),
cancellationToken);
/// <summary>The first trial of a contender started.</summary>
public Task StartAsync(Guid id, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @r, started_at = @now WHERE id = @id AND status = @p", cancellationToken,
("r", TournamentStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned)), cancellationToken);
/// <summary>The tournament goes to its judge; true when it is being judged (now, or since before a restart).</summary>
public async Task<bool> JudgeAsync(Guid id, CancellationToken cancellationToken) =>
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE tournaments SET status = @j, started_at = COALESCE(started_at, @now) WHERE id = @id AND status IN (@p, @r)", cancellationToken,
("j", TournamentStatuses.Judging), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running)).ConfigureAwait(false);
return await s.FirstOrDefaultAsync("SELECT status FROM tournaments WHERE id = @id", r => r.Text("status"), ("id", id)).ConfigureAwait(false) == TournamentStatuses.Judging;
}, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Opens the final tract for <paramref name="finalists"/>, once: the first call writes them with the moment, every later
/// one gets back what the first wrote. The finalists never change after the tract is opened.
/// </summary>
public async Task<(IReadOnlyList<string> Finalists, DateTimeOffset OpenedAt)> OpenHoldoutAsync(Guid id, IReadOnlyList<string> finalists, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(finalists);
var stored = await db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE tournaments SET finalists = @f, holdout_opened_at = @now WHERE id = @id AND holdout_opened_at IS NULL", cancellationToken,
("f", new DbJson(JsonSerializer.Serialize(finalists, TrialPlan.Json))), ("now", clock.UtcNow), ("id", id)).ConfigureAwait(false);
return await s.FirstOrDefaultAsync("SELECT finalists, holdout_opened_at FROM tournaments WHERE id = @id",
r => (Finalists: r.Json("finalists").Text, OpenedAt: r.Moment("holdout_opened_at")), ("id", id)).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
return (JsonSerializer.Deserialize<string[]>(stored.Finalists, TrialPlan.Json) ?? [], stored.OpenedAt);
}
/// <summary>The tournament judged, with its report; the outcomes of its units are dropped, the rows stay as a record.</summary>
public Task FinishAsync(Guid id, bool passed, string reportJson, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE tournaments SET status = @d, verdict = @v, report = @rep, finished_at = @now WHERE id = @id AND status = @j", cancellationToken,
("d", TournamentStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow),
("id", id), ("j", TournamentStatuses.Judging)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>The tournament failed, with the reason; the outcomes of its units are dropped as when it is done.</summary>
public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE tournaments SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r, @j)", cancellationToken,
("f", TournamentStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running),
("j", TournamentStatuses.Judging)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>After a restart: the tournaments not finished whose trials are all finished, oldest first, to judge again.</summary>
public async Task<IReadOnlyList<Guid>> ResumableAsync(CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT t.id FROM tournaments t WHERE t.status IN (@p, @r, @j) AND NOT EXISTS " +
"(SELECT 1 FROM backtest_trials b WHERE b.tournament_id = t.id AND b.status IN (@tp, @tr)) ORDER BY t.created_at, t.id",
r => r.Id("id"), ("p", TournamentStatuses.Planned), ("r", TournamentStatuses.Running), ("j", TournamentStatuses.Judging), ("tp", TrialStatuses.Planned),
("tr", TrialStatuses.Running)), cancellationToken).ConfigureAwait(false);
/// <summary>
/// The variants of the register outside tournament <paramref name="except"/>: every finished trial of every strategy, up to
/// <paramref name="until"/> when given (the moment the final tract was opened, so a resumed judge counts the same).
/// </summary>
public async Task<int> RegistryVariantsAsync(Guid? except, DateTimeOffset? until, CancellationToken cancellationToken)
{
var rows = await db.ReadAsync(s => s.QueryAsync(
"SELECT variants, finished_at, tournament_id FROM backtest_trials WHERE status = @d",
r => (Variants: (int)r.Number("variants"), FinishedAt: r.MomentOrNull("finished_at"), Tournament: r.IdOrNull("tournament_id")),
("d", TrialStatuses.Done)), cancellationToken).ConfigureAwait(false);
return rows.Where(r => except is null || r.Tournament != except)
.Where(r => until is null || (r.FinishedAt is { } at && at <= until))
.Sum(r => r.Variants);
}
private static Task<int> ReleaseUnitsAsync(DbSession s, Guid id, CancellationToken cancellationToken) =>
s.ExecuteAsync("UPDATE tournament_units SET outcome = NULL WHERE tournament_id = @id AND outcome IS NOT NULL", cancellationToken, ("id", id));
private static Tournament Read(DbRow r)
{
var plan = r.Json("plan").Text;
return new Tournament(
r.Id("id"),
r.Text("name"),
TournamentPlan.FromJson(plan),
r.Text("plan_hash"),
r.Text("status"),
r.TextOrNull("verdict"),
r.IsNull("finalists") ? null : JsonSerializer.Deserialize<string[]>(r.Json("finalists").Text, TrialPlan.Json),
r.TextOrNull("error"),
r.MomentOrNull("holdout_opened_at"),
r.Moment("created_at"),
r.MomentOrNull("started_at"),
r.MomentOrNull("finished_at"))
{
PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"),
};
}
}
+22 -2
View File
@@ -14,8 +14,10 @@ public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList<double
/// <summary> /// <summary>
/// What the trial judge (<see cref="TrialRunner"/>) asks of an engine, so the same judge, with the same validations and the /// What the trial judge (<see cref="TrialRunner"/>) asks of an engine, so the same judge, with the same validations and the
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in /// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset. Each execution is a unit
/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check. /// (<see cref="TrialUnitKey"/>); on one thread they come in a fixed order: every variant, the judged one outside the grid,
/// the costed runs, the benchmark, the look-ahead check. The laboratory may run several at once on its pool, so an engine
/// must not keep state between runs.
/// </summary> /// </summary>
public interface ITrialEngine public interface ITrialEngine
{ {
@@ -48,6 +50,19 @@ public interface ITrialEngine
/// <summary>What the judged variant should give once it trades, from its run and its returns.</summary> /// <summary>What the judged variant should give once it trades, from its run and its returns.</summary>
TrialExpectations Expected(BacktestRun run, double[] returns); TrialExpectations Expected(BacktestRun run, double[] returns);
/// <summary>
/// True when the engine only buys: its control against chance turns the signs around the mean return, so the drift alone
/// beats nothing (ADR 0026 point 4). An engine that does not say so is taken as one that only buys.
/// </summary>
bool LongOnly => true;
/// <summary>
/// The same engine on the surrogate of its data (<see cref="Surrogates"/>): every day of every instrument takes the sign of
/// <paramref name="signs"/>, around the mean when <paramref name="centred"/>. An engine without surrogates, or data that
/// cannot have them (corporate actions), throws <see cref="NotSupportedException"/> with the reason for the user.
/// </summary>
ITrialEngine Surrogate(DaySigns signs, bool centred) => throw new NotSupportedException("Questo motore non prevede ancora il controllo contro il caso.");
} }
/// <summary> /// <summary>
@@ -99,6 +114,11 @@ public sealed class DailyTrialEngine : ITrialEngine
public IReadOnlyList<string> Limitations() => TrialRunner.Limitations(_plan, _family, _data); public IReadOnlyList<string> Limitations() => TrialRunner.Limitations(_plan, _family, _data);
/// <summary>The daily engine buys and sells what it holds: it never goes short.</summary>
public bool LongOnly => true;
public ITrialEngine Surrogate(DaySigns signs, bool centred) => new DailyTrialEngine(_plan, _family, Surrogates.Of(_data, signs, centred));
public TrialExpectations Expected(BacktestRun run, double[] returns) public TrialExpectations Expected(BacktestRun run, double[] returns)
{ {
ArgumentNullException.ThrowIfNull(run); ArgumentNullException.ThrowIfNull(run);
+476
View File
@@ -0,0 +1,476 @@
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>What one engine execution of a trial is (<see cref="TrialUnitKey"/>).</summary>
public enum TrialUnitKind
{
/// <summary>A variant of the grid at plain costs.</summary>
Variant,
/// <summary>The variant in use when the grid does not have it (<see cref="TrialPlan.Judged"/>).</summary>
OutsideGrid,
/// <summary>The judged variant with costs multiplied.</summary>
Costed,
/// <summary>The term of comparison of the engine.</summary>
Benchmark,
/// <summary>The look-ahead check of the judged variant.</summary>
LookAhead,
/// <summary>
/// A repetition of the control against chance of a finalist of a tournament (its <see cref="TrialUnitKey.Index"/>): the
/// chosen variant on surrogate data. Only its daily Sharpe ratio is kept.
/// </summary>
Control,
/// <summary>The chosen variant of a finalist of a tournament on the final tract, read once, at the cost multiplier of its key.</summary>
Holdout,
}
/// <summary>
/// The identity of one engine execution of a trial: its kind, its place among the units of that kind (the grid index for a
/// variant, 0 otherwise), its parameters and its cost multiplier. <see cref="Text"/> is the invariant key the database keeps
/// (<c>variant:3:a=1;kind=0:x1</c>).
/// </summary>
public sealed record TrialUnitKey(TrialUnitKind Kind, int Index, string Parameters, decimal CostMultiplier)
{
/// <summary>The kind in snake case, as the database keeps it (<c>outside_grid</c>).</summary>
public string KindText => TextOf(Kind);
/// <summary>A kind in snake case, as the database keeps it.</summary>
public static string TextOf(TrialUnitKind kind) => JsonNamingPolicy.SnakeCaseLower.ConvertName(kind.ToString());
public string Text => string.Create(CultureInfo.InvariantCulture,
$"{KindText}:{Index}:{Parameters}:x{CostMultiplier.ToString("0.############################", CultureInfo.InvariantCulture)}");
}
/// <summary>The outcome of one unit: a run, the result of the look-ahead check, or the daily Sharpe ratio of a control.</summary>
public sealed record TrialUnitResult(TrialUnitKey Key, BacktestRun? Run, LookAheadResult? LookAhead)
{
/// <summary>The daily Sharpe ratio of a repetition of the control (<see cref="TrialUnitKind.Control"/>); null for the other units.</summary>
public double? Sharpe { get; init; }
}
/// <summary>
/// Every engine execution a trial needs, done: what <see cref="TrialRunner.Judge"/> reads. <see cref="Grid"/> is in the order
/// of <see cref="Variants"/>; <see cref="Costed"/> holds the multipliers other than 1.
/// </summary>
public sealed record TrialRuns(
IReadOnlyList<Variant> Variants,
IReadOnlyList<BacktestRun> Grid,
BacktestRun? OutsideGrid,
IReadOnlyDictionary<decimal, BacktestRun> Costed,
BacktestRun Benchmark,
LookAheadResult LookAhead);
/// <summary>
/// Where the units of a stage run: on the caller's thread, on a pool of threads, or on a pool that keeps finished units in the
/// database. The results come back in the order of <paramref name="keys"/>, whatever the order they finished in.
/// </summary>
public interface ITrialUnits
{
Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken);
}
/// <summary>Units one after the other on the caller's thread: the task it returns is already finished.</summary>
public sealed class InlineTrialUnits : ITrialUnits
{
public static InlineTrialUnits Instance { get; } = new();
public Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var results = new List<TrialUnitResult>(keys.Count);
foreach (var key in keys)
{
cancellationToken.ThrowIfCancellationRequested();
results.Add(execute(key));
}
return Task.FromResult<IReadOnlyList<TrialUnitResult>>(results);
}
}
/// <summary>
/// Units on a pool of low-priority threads, handed over in order: with one thread they run in the order of the keys. After a
/// unit fails, the ones not yet started are skipped.
/// </summary>
internal sealed class PooledTrialUnits(LowPriorityPool pool) : ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
using var failed = new CancellationTokenSource();
var tasks = keys.Select(key => pool.RunAsync(() => Guarded(key, execute, failed))).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>Runs a unit unless another one has failed; a failure stops the units not yet started.</summary>
internal static TrialUnitResult Guarded(TrialUnitKey key, Func<TrialUnitKey, TrialUnitResult> execute, CancellationTokenSource failed)
{
failed.Token.ThrowIfCancellationRequested();
try
{
return execute(key);
}
catch
{
failed.Cancel();
throw;
}
}
}
/// <summary>
/// Units on a pool that records each one in <c>tournament_units</c>: a claim before it runs, its outcome once done, both with
/// <paramref name="fingerprint"/>, what they are computed on (<see cref="TrialUnitStore.Fingerprint"/>). The units already
/// done (<paramref name="done"/>, from <see cref="TrialUnitStore.ResumeAsync(Guid, string, CancellationToken)"/>, on the same
/// fingerprint) come back from their outcome and do not run again.
/// </summary>
internal sealed class StoredTrialUnits(LowPriorityPool pool, TrialUnitStore store, Guid trialId, Guid? tournamentId, IReadOnlyDictionary<string, byte[]> done, string fingerprint)
: ITrialUnits
{
public async Task<IReadOnlyList<TrialUnitResult>> RunAsync(IReadOnlyList<TrialUnitKey> keys, Func<TrialUnitKey, TrialUnitResult> execute, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
ArgumentNullException.ThrowIfNull(execute);
var missing = keys.Where(k => !done.ContainsKey(k.Text)).ToList();
if (missing.Count > 0)
{
await store.ClaimAsync(trialId, tournamentId, missing, fingerprint, cancellationToken).ConfigureAwait(false);
}
using var failed = new CancellationTokenSource();
async Task<TrialUnitResult> OneAsync(TrialUnitKey key)
{
var (result, outcome, seconds) = await pool.RunAsync(() =>
{
var watch = Stopwatch.StartNew();
var unit = PooledTrialUnits.Guarded(key, execute, failed);
return (unit, TrialUnitOutcomes.Encode(unit), watch.Elapsed.TotalSeconds);
}).ConfigureAwait(false);
await store.DoneAsync(trialId, key, outcome, seconds, fingerprint, cancellationToken).ConfigureAwait(false);
return result;
}
var tasks = keys.Select(key => done.TryGetValue(key.Text, out var outcome) ? Task.FromResult(TrialUnitOutcomes.Decode(key, outcome)) : OneAsync(key)).ToArray();
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
/// <summary>
/// The two stages of the units of a trial. The first: every variant of the grid in grid order, then the variant in use when
/// the grid does not have it. The second, once the plateau rule has chosen on the first: the costed runs of the judged
/// variant (multipliers other than 1, in increasing order), the benchmark, the look-ahead check. Parameters always come
/// from the grid or from the plan, never from the text of a key.
/// </summary>
internal sealed class TrialStages
{
private readonly TrialPlan _plan;
private readonly IResearchFamily _family;
private readonly ITrialEngine _engine;
private readonly StrategyParameters? _named;
private readonly IReadOnlyList<decimal> _multipliers;
private StrategyParameters? _judged;
private IReadOnlyList<TrialUnitKey>? _second;
public TrialStages(TrialPlan plan, IResearchFamily family, ITrialEngine engine)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
_plan = plan;
_family = family;
_engine = engine;
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
}
Grid = ParameterGrid.Of(family, plan.Grid);
if (Grid.Count == 0)
{
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
var (named, namedIndex) = TrialRunner.Named(plan, family, Grid);
_named = namedIndex < 0 ? named : null;
_multipliers = [.. plan.CostMultipliers.Distinct().Order().Where(m => m != 1m)];
First =
[
.. Grid.Select((v, i) => new TrialUnitKey(TrialUnitKind.Variant, i, v.ToString(), 1m)),
.. _named is null ? Array.Empty<TrialUnitKey>() : [new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, _named.ToString(), 1m)],
];
}
public IReadOnlyList<Variant> Grid { get; }
public IReadOnlyList<TrialUnitKey> First { get; }
/// <summary>How many units the second stage has: it does not depend on the choice.</summary>
public int SecondCount => _multipliers.Count + 2;
private StrategyParameters Judged => _judged ?? throw new InvalidOperationException("The second stage needs the choice of the first.");
/// <summary>The plateau choice on the runs of the first stage, and the keys of the second.</summary>
public IReadOnlyList<TrialUnitKey> Second(IReadOnlyDictionary<string, TrialUnitResult> first)
{
ArgumentNullException.ThrowIfNull(first);
var sharpes = First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => Moments.Of(RunOf(first, k).DailyReturns()).Sharpe).ToArray();
_judged = TrialRunner.Choose(_plan, _family, Grid, sharpes).Judged;
var judged = _judged.ToString();
_second =
[
.. _multipliers.Select(m => new TrialUnitKey(TrialUnitKind.Costed, 0, judged, m)),
new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m),
new TrialUnitKey(TrialUnitKind.LookAhead, 0, judged, 1m),
];
return _second;
}
/// <summary>One engine execution.</summary>
public TrialUnitResult Execute(TrialUnitKey key)
{
ArgumentNullException.ThrowIfNull(key);
return key.Kind switch
{
TrialUnitKind.Variant => new TrialUnitResult(key, _engine.Run(VariantOf(key).Parameters), null),
TrialUnitKind.OutsideGrid => new TrialUnitResult(key, _engine.Run(_named ?? throw new InvalidOperationException("The judged variant is in the grid.")), null),
TrialUnitKind.Costed => new TrialUnitResult(key, _engine.Run(Judged, key.CostMultiplier), null),
TrialUnitKind.Benchmark => new TrialUnitResult(key, _engine.Benchmark(), null),
TrialUnitKind.LookAhead => new TrialUnitResult(key, null, _engine.LookAhead(Judged, _plan.Validation.LookAheadCuts)),
_ => throw new ArgumentOutOfRangeException(nameof(key), key.Kind, "Not a unit of a trial."),
};
}
/// <summary>The runs of both stages, by key.</summary>
public TrialRuns Assemble(IReadOnlyDictionary<string, TrialUnitResult> results)
{
ArgumentNullException.ThrowIfNull(results);
var second = _second ?? throw new InvalidOperationException("The second stage was not planned.");
var outside = First.FirstOrDefault(k => k.Kind == TrialUnitKind.OutsideGrid);
return new TrialRuns(
Grid,
[.. First.Where(k => k.Kind == TrialUnitKind.Variant).Select(k => RunOf(results, k))],
outside is null ? null : RunOf(results, outside),
second.Where(k => k.Kind == TrialUnitKind.Costed).ToDictionary(k => k.CostMultiplier, k => RunOf(results, k)),
RunOf(results, second.Single(k => k.Kind == TrialUnitKind.Benchmark)),
ResultOf(results, second.Single(k => k.Kind == TrialUnitKind.LookAhead)).LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."));
}
private Variant VariantOf(TrialUnitKey key)
{
var variant = Grid[key.Index];
return variant.ToString() == key.Parameters ? variant : throw new InvalidOperationException("The key " + key.Text + " is not the variant " + variant + ".");
}
private static TrialUnitResult ResultOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
results.TryGetValue(key.Text, out var result) ? result : throw new InvalidOperationException("The unit " + key.Text + " has no result.");
private static BacktestRun RunOf(IReadOnlyDictionary<string, TrialUnitResult> results, TrialUnitKey key) =>
ResultOf(results, key).Run ?? throw new InvalidOperationException("The unit " + key.Text + " has no run.");
}
/// <summary>
/// The outcome of a unit as the database keeps it: the gzip of its JSON, with the options of the plans (decimals keep their
/// scale, doubles their exact value). A run is kept without its decisions, which only the look-ahead check reads; the order
/// of fills, trades and notes is kept, so a run read back gives the same report byte for byte.
/// </summary>
internal static class TrialUnitOutcomes
{
private sealed record StoredRun(
string Currency,
decimal InitialCapital,
IReadOnlyList<EquityPoint> Equity,
IReadOnlyList<BacktestFill> Fills,
IReadOnlyList<BacktestTrade> Trades,
IReadOnlyList<BacktestNote> Notes,
decimal Dividends,
decimal WrittenOff,
IReadOnlyList<BacktestBasket> Baskets);
private sealed record StoredControl(double Sharpe);
public static byte[] Encode(TrialUnitResult result)
{
ArgumentNullException.ThrowIfNull(result);
var json = result.Key.Kind switch
{
TrialUnitKind.LookAhead => JsonSerializer.SerializeToUtf8Bytes(result.LookAhead ?? throw new InvalidOperationException("The look-ahead unit has no result."), TrialPlan.Json),
TrialUnitKind.Control => JsonSerializer.SerializeToUtf8Bytes(new StoredControl(result.Sharpe ?? throw new InvalidOperationException("The control unit has no Sharpe ratio.")),
TrialPlan.Json),
_ => JsonSerializer.SerializeToUtf8Bytes(Stored(result.Run ?? throw new InvalidOperationException("The unit " + result.Key.Text + " has no run.")), TrialPlan.Json),
};
using var buffer = new MemoryStream();
using (var zip = new GZipStream(buffer, CompressionLevel.Optimal, leaveOpen: true))
{
zip.Write(json);
}
return buffer.ToArray();
}
public static TrialUnitResult Decode(TrialUnitKey key, byte[] outcome)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(outcome);
using var zip = new GZipStream(new MemoryStream(outcome), CompressionMode.Decompress);
if (key.Kind == TrialUnitKind.LookAhead)
{
return new TrialUnitResult(key, null, JsonSerializer.Deserialize<LookAheadResult>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome"));
}
if (key.Kind == TrialUnitKind.Control)
{
var control = JsonSerializer.Deserialize<StoredControl>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome");
return new TrialUnitResult(key, null, null) { Sharpe = control.Sharpe };
}
var run = JsonSerializer.Deserialize<StoredRun>(zip, TrialPlan.Json) ?? throw new JsonException("Empty unit outcome");
return new TrialUnitResult(key, new BacktestRun(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, [], run.Notes)
{
Dividends = run.Dividends,
WrittenOff = run.WrittenOff,
Baskets = run.Baskets,
}, null);
}
private static StoredRun Stored(BacktestRun run) =>
new(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, run.Notes, run.Dividends, run.WrittenOff, run.Baskets);
}
/// <summary>States of a row of <c>tournament_units</c>.</summary>
public static class TrialUnitStatuses
{
public const string Running = "running";
public const string Done = "done";
}
/// <summary>A unit as the database keeps it, without its outcome.</summary>
public sealed record TrialUnitRow(string Key, string Kind, string Status, bool HasOutcome, double? Seconds, Guid? TournamentId)
{
/// <summary>What the unit was computed on (<see cref="TrialUnitStore.Fingerprint"/>).</summary>
public string? Fingerprint { get; init; }
}
/// <summary>
/// The units of the trials in <c>tournament_units</c> (Phase 13): one row per engine execution, claimed before it runs and
/// done with its outcome, so a trial stopped halfway runs again only what it had not finished. Every row keeps what it was
/// computed on (<see cref="Fingerprint"/>): a unit done on other data, by another engine or another build of Anubis is not
/// reused. A plain trial drops its outcomes when it ends (<see cref="TrialStore.FinishAsync"/>, <see cref="TrialStore.FailAsync"/>);
/// a unit never counts as a trial.
/// </summary>
public sealed class TrialUnitStore(Database db, IClock clock)
{
/// <summary>
/// The engine and the code that compute a unit, the second half of <see cref="Fingerprint"/>: the version of the engine and
/// the identity of this build of Anubis, which changes with any change to its code.
/// </summary>
public static string Build { get; } = "|" + BacktestEngine.Version + "|" + typeof(BacktestEngine).Assembly.ManifestModule.ModuleVersionId.ToString("N");
/// <summary>What the units of <paramref name="engine"/> are computed on: the fingerprint of the data it read, then <see cref="Build"/>.</summary>
public static string Fingerprint(ITrialEngine engine)
{
ArgumentNullException.ThrowIfNull(engine);
return engine.Fingerprint() + Build;
}
/// <summary>
/// A trial that starts, or starts again after a restart: the units left running (their work was lost with the process),
/// those without an outcome and those done on another <paramref name="fingerprint"/> are dropped, so they run again; the
/// outcomes of the units done on the same one are returned by key.
/// </summary>
public Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, string fingerprint, CancellationToken cancellationToken) =>
ResumeAsync(trialId, (_, stored) => stored == fingerprint, cancellationToken);
/// <summary>
/// The same, when the units of a trial were computed on different inputs (the judge of a tournament): a unit done is kept
/// when <paramref name="current"/> says so for its kind (as the database keeps it) and its stored fingerprint.
/// </summary>
public async Task<IReadOnlyDictionary<string, byte[]>> ResumeAsync(Guid trialId, Func<string, string?, bool> current, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(current);
var rows = await db.WriteAsync(async s =>
{
await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND (status <> @d OR outcome IS NULL)", cancellationToken,
("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
var done = await s.QueryAsync("SELECT unit_key, kind, fingerprint, outcome FROM tournament_units WHERE trial_id = @t AND status = @d",
r => (Key: r.Text("unit_key"), Kind: r.Text("kind"), Fingerprint: r.TextOrNull("fingerprint"), Outcome: r.Bytes("outcome")),
("t", trialId), ("d", TrialUnitStatuses.Done)).ConfigureAwait(false);
var kept = new List<(string Key, byte[] Outcome)>(done.Count);
foreach (var row in done)
{
if (current(row.Kind, row.Fingerprint))
{
kept.Add((row.Key, row.Outcome));
}
else
{
await s.ExecuteAsync("DELETE FROM tournament_units WHERE trial_id = @t AND unit_key = @k", cancellationToken, ("t", trialId), ("k", row.Key))
.ConfigureAwait(false);
}
}
return kept;
}, cancellationToken).ConfigureAwait(false);
return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal);
}
/// <summary>Claims the units about to run, in one transaction, with what they are computed on. A unit already claimed stays as it is.</summary>
public Task ClaimAsync(Guid trialId, Guid? tournamentId, IReadOnlyList<TrialUnitKey> keys, string fingerprint, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(keys);
return db.WriteAsync(async s =>
{
foreach (var key in keys)
{
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, created_at) VALUES (@id, @t, @tour, @k, @kind, @r, @f, @now) " +
"ON CONFLICT (trial_id, unit_key) DO NOTHING",
cancellationToken, ("id", Ids.NewId(clock)), ("t", trialId), ("tour", tournamentId), ("k", key.Text), ("kind", key.KindText),
("r", TrialUnitStatuses.Running), ("f", fingerprint), ("now", clock.UtcNow)).ConfigureAwait(false);
}
}, cancellationToken);
}
/// <summary>A unit done: its outcome, the seconds it took and what it was computed on.</summary>
public Task DoneAsync(Guid trialId, TrialUnitKey key, byte[] outcome, double seconds, string fingerprint, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(key);
return db.WriteAsync(s => s.ExecuteAsync(
"UPDATE tournament_units SET status = @d, outcome = @o, seconds = @sec, fingerprint = @f, finished_at = @now WHERE trial_id = @t AND unit_key = @k AND status = @r",
cancellationToken, ("d", TrialUnitStatuses.Done), ("o", outcome), ("sec", seconds), ("f", fingerprint), ("now", clock.UtcNow), ("t", trialId), ("k", key.Text),
("r", TrialUnitStatuses.Running)), cancellationToken);
}
/// <summary>The outcomes of the units of a finished trial that still have one (those of a tournament until it ends), by key.</summary>
public async Task<IReadOnlyDictionary<string, byte[]>> OutcomesAsync(Guid trialId, CancellationToken cancellationToken)
{
var rows = await db.ReadAsync(s => s.QueryAsync("SELECT unit_key, outcome FROM tournament_units WHERE trial_id = @t AND status = @d AND outcome IS NOT NULL",
r => (Key: r.Text("unit_key"), Outcome: r.Bytes("outcome")), ("t", trialId), ("d", TrialUnitStatuses.Done)), cancellationToken).ConfigureAwait(false);
return rows.ToDictionary(r => r.Key, r => r.Outcome, StringComparer.Ordinal);
}
/// <summary>The units of a trial, in the order they were claimed.</summary>
public async Task<IReadOnlyList<TrialUnitRow>> ListAsync(Guid trialId, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT unit_key, kind, status, outcome, seconds, tournament_id, fingerprint FROM tournament_units WHERE trial_id = @t ORDER BY id",
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"),
r.IdOrNull("tournament_id"))
{
Fingerprint = r.TextOrNull("fingerprint"),
},
("t", trialId)), cancellationToken).ConfigureAwait(false);
}
+49 -16
View File
@@ -168,6 +168,9 @@ public sealed record Trial(
/// <summary>The quarterly review that registered it; null for the user's.</summary> /// <summary>The quarterly review that registered it; null for the user's.</summary>
public Guid? ReviewId { get; init; } public Guid? ReviewId { get; init; }
/// <summary>The tournament it is the trial of a contender of; null outside a tournament.</summary>
public Guid? TournamentId { get; init; }
} }
/// <summary>The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios.</summary> /// <summary>The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios.</summary>
@@ -182,7 +185,7 @@ public sealed record PriorTrials(int Trials, int Variants, IReadOnlyList<double>
/// </summary> /// </summary>
public sealed class TrialStore(Database db, IClock clock) public sealed class TrialStore(Database db, IClock clock)
{ {
private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at, review_id"; private const string Columns = "id, strategy, strategy_version, plan, plan_hash, variants, status, verdict, data_fingerprint, summary, error, created_at, started_at, finished_at, review_id, tournament_id";
public async Task<Trial> PlanAsync(TrialPlan plan, int variants, CancellationToken cancellationToken) public async Task<Trial> PlanAsync(TrialPlan plan, int variants, CancellationToken cancellationToken)
{ {
@@ -191,7 +194,11 @@ public sealed class TrialStore(Database db, IClock clock)
} }
/// <summary>The same as part of a transaction: the plans of a quarterly review are written together.</summary> /// <summary>The same as part of a transaction: the plans of a quarterly review are written together.</summary>
public static async Task<Guid> PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, CancellationToken cancellationToken) public static Task<Guid> PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, CancellationToken cancellationToken) =>
PlanAsync(s, clock, plan, variants, review, null, cancellationToken);
/// <summary>The same for the trial of a contender, written with the plan of its tournament.</summary>
public static async Task<Guid> PlanAsync(DbSession s, IClock clock, TrialPlan plan, int variants, Guid? review, Guid? tournament, CancellationToken cancellationToken)
{ {
ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(clock);
@@ -199,10 +206,10 @@ public sealed class TrialStore(Database db, IClock clock)
var id = Ids.NewId(clock); var id = Ids.NewId(clock);
var json = plan.ToJson(); var json = plan.ToJson();
await s.ExecuteAsync( await s.ExecuteAsync(
"INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, review_id) " + "INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, review_id, tournament_id) " +
"VALUES (@id, @s, @v, @p, @h, @n, @st, @now, @rev)", "VALUES (@id, @s, @v, @p, @h, @n, @st, @now, @rev, @tour)",
cancellationToken, ("id", id), ("s", plan.Strategy), ("v", plan.StrategyVersion), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), cancellationToken, ("id", id), ("s", plan.Strategy), ("v", plan.StrategyVersion), ("p", new DbJson(json)), ("h", TrialPlan.Hash(json)),
("n", variants), ("st", TrialStatuses.Planned), ("now", clock.UtcNow), ("rev", review)).ConfigureAwait(false); ("n", variants), ("st", TrialStatuses.Planned), ("now", clock.UtcNow), ("rev", review), ("tour", tournament)).ConfigureAwait(false);
return id; return id;
} }
@@ -210,6 +217,11 @@ public sealed class TrialStore(Database db, IClock clock)
public async Task<IReadOnlyList<Trial>> OfReviewAsync(Guid review, CancellationToken cancellationToken) => public async Task<IReadOnlyList<Trial>> OfReviewAsync(Guid review, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE review_id = @r ORDER BY created_at, id", Read, ("r", review)), cancellationToken).ConfigureAwait(false); await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE review_id = @r ORDER BY created_at, id", Read, ("r", review)), cancellationToken).ConfigureAwait(false);
/// <summary>The trials of the contenders of a tournament, in the order of its plan.</summary>
public async Task<IReadOnlyList<Trial>> OfTournamentAsync(Guid tournament, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM backtest_trials WHERE tournament_id = @t ORDER BY created_at, id", Read, ("t", tournament)),
cancellationToken).ConfigureAwait(false);
public Task<Trial?> GetAsync(Guid id, CancellationToken cancellationToken) => public Task<Trial?> GetAsync(Guid id, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM backtest_trials WHERE id = @id", Read, ("id", id)), cancellationToken); db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM backtest_trials WHERE id = @id", Read, ("id", id)), cancellationToken);
@@ -226,21 +238,41 @@ public sealed class TrialStore(Database db, IClock clock)
await db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @r, started_at = @now WHERE id = @id AND status = @p", await db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @r, started_at = @now WHERE id = @id AND status = @p",
cancellationToken, ("r", TrialStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned)), cancellationToken).ConfigureAwait(false) == 1; cancellationToken, ("r", TrialStatuses.Running), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned)), cancellationToken).ConfigureAwait(false) == 1;
public Task FinishAsync(Guid id, string fingerprint, TrialSummary summary, string reportJson, bool passed, CancellationToken cancellationToken) => /// <summary>The tournament of a finished trial; null when the trial is not finished or belongs to none. The plan is not read.</summary>
db.WriteAsync(s => s.ExecuteAsync( public Task<Guid?> FinishedTournamentAsync(Guid id, CancellationToken cancellationToken) =>
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r", db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT tournament_id FROM backtest_trials WHERE id = @id AND status IN (@d, @f)", r => r.IdOrNull("tournament_id"),
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint), ("id", id), ("d", TrialStatuses.Done), ("f", TrialStatuses.Failed)), cancellationToken);
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)), cancellationToken);
/// <summary>A trial done, with its report. A trial outside a tournament drops the outcomes of its units: the rows stay as a record.</summary>
public Task FinishAsync(Guid id, string fingerprint, TrialSummary summary, string reportJson, bool passed, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
await s.ExecuteAsync(
"UPDATE backtest_trials SET status = @d, verdict = @v, data_fingerprint = @f, summary = @s, report = @rep, finished_at = @now WHERE id = @id AND status = @r",
cancellationToken, ("d", TrialStatuses.Done), ("v", passed ? TrialVerdicts.Passed : TrialVerdicts.Rejected), ("f", fingerprint),
("s", new DbJson(JsonSerializer.Serialize(summary, TrialPlan.Json))), ("rep", new DbJson(reportJson)), ("now", clock.UtcNow), ("id", id),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>A trial failed, with the reason. A trial outside a tournament drops the outcomes of its units, as when it is done.</summary>
public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) => public Task FailAsync(Guid id, string error, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)", db.WriteAsync(async s =>
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned), {
("r", TrialStatuses.Running)), cancellationToken); await s.ExecuteAsync("UPDATE backtest_trials SET status = @f, error = @e, finished_at = @now WHERE id = @id AND status IN (@p, @r)",
cancellationToken, ("f", TrialStatuses.Failed), ("e", error), ("now", clock.UtcNow), ("id", id), ("p", TrialStatuses.Planned),
("r", TrialStatuses.Running)).ConfigureAwait(false);
await ReleaseUnitsAsync(s, id, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
// The units of a tournament keep their outcome until the tournament ends: it judges them again.
private static Task<int> ReleaseUnitsAsync(DbSession s, Guid id, CancellationToken cancellationToken) =>
s.ExecuteAsync("UPDATE tournament_units SET outcome = NULL WHERE trial_id = @id AND tournament_id IS NULL AND outcome IS NOT NULL", cancellationToken, ("id", id));
/// <summary> /// <summary>
/// After a restart: trials left running go back to planned (their work was lost with the process), and every planned /// After a restart: trials left running go back to planned, and every planned trial is returned oldest first, to run again
/// trial is returned oldest first, to run again from the start with the same plan. /// with the same plan. The units they had finished are kept (<see cref="TrialUnitStore.ResumeAsync"/>): only the rest runs
/// again.
/// </summary> /// </summary>
public async Task<IReadOnlyList<Guid>> ResumeAsync(CancellationToken cancellationToken) => public async Task<IReadOnlyList<Guid>> ResumeAsync(CancellationToken cancellationToken) =>
await db.WriteAsync(async s => await db.WriteAsync(async s =>
@@ -301,6 +333,7 @@ public sealed class TrialStore(Database db, IClock clock)
{ {
PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"), PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"),
ReviewId = r.IdOrNull("review_id"), ReviewId = r.IdOrNull("review_id"),
TournamentId = r.IdOrNull("tournament_id"),
}; };
} }
} }
+101
View File
@@ -0,0 +1,101 @@
using System.Diagnostics.CodeAnalysis;
namespace Anubis.Core;
/// <summary>
/// A fixed-seed generator based on SplitMix64 (Steele, Lea and Flood, 2014). Unlike a seeded <see cref="Random"/>, its
/// sequence is fixed by this code, so it stays the same on every platform and .NET version: a control, a bootstrap or a
/// synthetic series drawn from a seed repeats exactly. It moved here from the tests (Phase 13) without changing a bit of
/// its algorithm, so every series the tests drew before draws the same today.
/// </summary>
/// <remarks>
/// Two older generators stay as they are, because their outputs are recorded: <c>Learning.FixedRandom</c> (same stream,
/// but its <c>Next</c> multiplies instead of rejecting) and <c>Backtest.PathBootstrap</c> (a seeded <see cref="Random"/>,
/// whose results are in the committed outcome files).
/// </remarks>
[SuppressMessage("Naming", "CA1720", Justification = "Long, Int, Double and Decimal name what they draw; the tests have called them so since Phase 1.")]
public sealed class SeededRandom(int seed)
{
// The seed is sign-extended: seed −1 starts from 0xFFFF_FFFF_FFFF_FFFF, as it always did.
private ulong _state = unchecked((ulong)(long)seed);
/// <summary>The next 64 bits of SplitMix64.</summary>
public ulong NextUInt64()
{
var z = _state += 0x9E3779B97F4A7C15UL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>), without bias (rejection sampling).</summary>
public long Long(long minInclusive, long maxExclusive)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
var range = unchecked((ulong)(maxExclusive - minInclusive));
var limit = ulong.MaxValue - (ulong.MaxValue % range);
ulong x;
do
{
x = NextUInt64();
}
while (x >= limit);
return unchecked(minInclusive + (long)(x % range));
}
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
/// <summary>True or false with the same probability: the lowest bit of the next draw.</summary>
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
/// <summary>Uniform value in [0, 1).</summary>
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
/// <summary>A standard normal value (Box–Muller, cosine branch, two draws per value), for synthetic prices and returns.</summary>
public double Normal()
{
var u = 1.0 - Double();
var v = Double();
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
}
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals, uniform on that grid.</summary>
public decimal Decimal(decimal min, decimal max, int scale)
{
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
ArgumentOutOfRangeException.ThrowIfNegative(scale);
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
var unit = 1m;
for (var i = 0; i < scale; i++)
{
unit /= 10m;
}
var low = decimal.Ceiling(min / unit);
var high = decimal.Floor(max / unit);
if (low > high)
{
throw new ArgumentException("No value with this scale in the interval.", nameof(scale));
}
var steps = high - low;
if (steps >= long.MaxValue)
{
throw new ArgumentException("The interval is too wide for this scale.", nameof(scale));
}
var k = Long(0, (long)steps + 1);
return (low + k) * unit;
}
/// <summary>One of <paramref name="items"/>, each with the same probability.</summary>
public T Pick<T>(IReadOnlyList<T> items)
{
ArgumentNullException.ThrowIfNull(items);
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
return items[Int(0, items.Count)];
}
}
+1 -1
View File
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]); public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All = public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All]; [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All, .. Backtest.LaboratorySettings.All];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>(); private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
@@ -0,0 +1,41 @@
-- The tournament of the strategies (ADR 0026): its plan, written before any result and never changed, its state and its
-- verdict. The final tract of the data is opened once: holdout_opened_at and finalists are written together, only once.
CREATE TABLE tournaments (
id {uuid} PRIMARY KEY,
name TEXT NOT NULL,
plan {json} NOT NULL,
plan_hash TEXT NOT NULL,
status TEXT NOT NULL,
verdict TEXT,
finalists {json},
report {json},
error TEXT,
holdout_opened_at {timestamp},
created_at {timestamp} NOT NULL,
started_at {timestamp},
finished_at {timestamp}
){strict};
CREATE INDEX tournaments_status ON tournaments (status);
-- One engine execution of a trial of the laboratory (a variant, a costed run, the benchmark, the look-ahead check), so a
-- trial stopped halfway runs again only what it had not finished. The outcome is the gzip of its JSON; a plain trial
-- (tournament_id NULL) drops it when it ends, the row stays as a record. The fingerprint is what the unit was computed on
-- (the data, the engine version, the build): a unit done on other inputs is not reused.
CREATE TABLE tournament_units (
id {uuid} PRIMARY KEY,
trial_id {uuid} NOT NULL REFERENCES backtest_trials (id),
tournament_id {uuid} REFERENCES tournaments (id),
unit_key TEXT NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL,
fingerprint TEXT,
outcome {bytes},
seconds {float},
created_at {timestamp} NOT NULL,
finished_at {timestamp},
UNIQUE (trial_id, unit_key)
){strict};
CREATE INDEX tournament_units_trial ON tournament_units (trial_id, status);
-- The tournament a contender trial belongs to. No foreign key: backtest_trials is imported before tournaments.
ALTER TABLE backtest_trials ADD COLUMN tournament_id {uuid};
+15
View File
@@ -35,6 +35,21 @@ public sealed class ArchiveTests
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false); ("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)", await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false); ("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
// A tournament, one of its trials and a unit with its outcome: JSON, bytes and a measure across engines (Phase 13).
var tournament = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(40));
var trial = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(41));
await s.ExecuteAsync(
"INSERT INTO tournaments (id, name, plan, plan_hash, status, finalists, created_at, started_at) VALUES (@id, 'Campionato', @p, 'abc', 'running', @f, @t, @t)",
("id", tournament), ("p", new DbJson("{\"name\": \"Campionato\", \"cost_multipliers\": [1, 2, 3]}")), ("f", new DbJson("[\"a\", \"b\"]")),
("t", _clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, tournament_id) VALUES (@id, 'sma_cross', '1', @p, 'def', 4, 'running', @t, @tour)",
("id", trial), ("p", new DbJson("{\"strategy\": \"sma_cross\"}")), ("t", _clock.UtcNow), ("tour", tournament)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, fingerprint, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', 'abc|2|def', @o, @sec, @t, @t)",
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(42))), ("tr", trial), ("tour", tournament), ("o", new byte[] { 31, 139, 8, 0, 255, 0 }), ("sec", 0.1234567890123),
("t", _clock.UtcNow)).ConfigureAwait(false);
}).ConfigureAwait(false); }).ConfigureAwait(false);
} }
+2
View File
@@ -0,0 +1,2 @@
// The fixed-seed generator lives in Core since Phase 13; the tests keep calling it Gen, as they always did.
global using Gen = Anubis.Core.SeededRandom;
+4 -1
View File
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using Anubis.Server; using Anubis.Server;
@@ -37,10 +38,12 @@ public sealed class HealthEndpointTests
return (await response.Content.ReadFromJsonAsync<HealthResponse>())!; return (await response.Content.ReadFromJsonAsync<HealthResponse>())!;
} }
// Up to 30 seconds of wall time: on a busy test runner the engine can take more than ten to start.
async Task UntilAsync(string status, string loop) async Task UntilAsync(string status, string loop)
{ {
HealthResponse? last = null; HealthResponse? last = null;
for (var i = 0; i < 100; i++) var deadline = Stopwatch.StartNew();
while (last is null || deadline.Elapsed < TimeSpan.FromSeconds(30))
{ {
last = await HealthAsync(); last = await HealthAsync();
if (last.Status == status && last.Checks!.GetValueOrDefault("motore") == loop) if (last.Status == status && last.Checks!.GetValueOrDefault("motore") == loop)
-84
View File
@@ -29,87 +29,3 @@ internal static class Property
} }
} }
} }
/// <summary>
/// Fixed-seed generator based on SplitMix64. Unlike a seeded <see cref="Random"/>, its sequence is
/// fixed by this code, so it stays the same on every platform and .NET version.
/// </summary>
internal sealed class Gen(int seed)
{
private ulong _state = unchecked((ulong)(long)seed);
public ulong NextUInt64()
{
var z = _state += 0x9E3779B97F4A7C15UL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
public long Long(long minInclusive, long maxExclusive)
{
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
var range = unchecked((ulong)(maxExclusive - minInclusive));
var limit = ulong.MaxValue - (ulong.MaxValue % range);
ulong x;
do
{
x = NextUInt64();
}
while (x >= limit);
return unchecked(minInclusive + (long)(x % range));
}
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
/// <summary>Uniform value in [0, 1).</summary>
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
/// <summary>A standard normal value (Box–Muller), for synthetic price series and returns.</summary>
public double Normal()
{
var u = 1.0 - Double();
var v = Double();
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
}
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
public decimal Decimal(decimal min, decimal max, int scale)
{
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
ArgumentOutOfRangeException.ThrowIfNegative(scale);
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
var unit = 1m;
for (var i = 0; i < scale; i++)
{
unit /= 10m;
}
var low = decimal.Ceiling(min / unit);
var high = decimal.Floor(max / unit);
if (low > high)
{
throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale));
}
var steps = high - low;
if (steps >= long.MaxValue)
{
throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale));
}
var k = Long(0, (long)steps + 1);
return (low + k) * unit;
}
public T Pick<T>(IReadOnlyList<T> items)
{
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
return items[Int(0, items.Count)];
}
}
+180
View File
@@ -0,0 +1,180 @@
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The control against chance (issue #124, criteria 3 and 4 of Phase 13): the surrogate series keep each day's size and
/// the correlations and lose every memory; a rule with an edge beats them, a rule without one does not.
/// </summary>
[TestClass]
public sealed class SurrogateTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSurrogateKeepsEveryDaysAbsoluteReturnAndTheCorrelations()
{
// On returns: flipped, every day keeps its size exactly; centred, its distance from the mean.
var returns = Synthetic.WalkReturns(1000, 3, drift: 0.001);
var signs = TournamentStatistics.Signs(returns.Length, 5);
var flipped = Surrogates.Flip(returns, signs, centred: false);
var centred = Surrogates.Flip(returns, signs, centred: true);
var mean = returns.Average();
for (var i = 0; i < returns.Length; i++)
{
Assert.AreEqual(Math.Abs(returns[i]), Math.Abs(flipped[i]));
Assert.AreEqual(signs[i] * returns[i], flipped[i]);
Assert.AreEqual(Math.Abs(returns[i] - mean), Math.Abs(centred[i] - mean), 1e-15);
}
Assert.IsTrue(signs.Count(s => s < 0) is > 400 and < 600, "About half the days change sign.");
// On bars: two correlated coins flip together, so their correlation stays and each day keeps its size.
var (a, b) = Synthetic.CorrelatedReturns(2000, 0.7, 11);
var data = Synthetic.Dataset(("AAA-EUR", Synthetic.Bars(a, 1)), ("BBB-EUR", Synthetic.Bars(b, 2)));
var surrogate = Surrogates.Of(data, seed: 21, centred: false);
var ra = Synthetic.CloseReturns(data["AAA-EUR"]!.Bars);
var rb = Synthetic.CloseReturns(data["BBB-EUR"]!.Bars);
var sa = Synthetic.CloseReturns(surrogate["AAA-EUR"]!.Bars);
var sb = Synthetic.CloseReturns(surrogate["BBB-EUR"]!.Bars);
var changed = 0;
for (var i = 0; i < ra.Length; i++)
{
Assert.AreEqual(Math.Abs(ra[i]), Math.Abs(sa[i]), 1e-12);
Assert.AreEqual(Math.Abs(rb[i]), Math.Abs(sb[i]), 1e-12);
Assert.AreEqual(Math.Sign(sa[i]) * Math.Sign(ra[i]), Math.Sign(sb[i]) * Math.Sign(rb[i]), "One sign a day for every instrument.");
changed += Math.Sign(sa[i]) != Math.Sign(ra[i]) ? 1 : 0;
}
Assert.IsTrue(changed is > 800 and < 1200, $"{changed} days flipped");
Assert.AreEqual(Synthetic.Correlation(ra, rb), Synthetic.Correlation(sa, sb), 0.02);
Assert.AreEqual(0.7, Synthetic.Correlation(sa, sb), 0.05);
// The first bar is the same, the volume never changes, the high stays the highest and the low the lowest.
foreach (var symbol in new[] { "AAA-EUR", "BBB-EUR" })
{
var real = data[symbol]!.Bars;
var made = surrogate[symbol]!.Bars;
Assert.AreEqual(real[0], made[0]);
Assert.HasCount(real.Count, made);
for (var i = 0; i < made.Count; i++)
{
Assert.AreEqual(real[i].Day, made[i].Day);
Assert.AreEqual(real[i].Volume, made[i].Volume);
Assert.IsTrue(made[i].High >= Math.Max(made[i].Open, made[i].Close) && made[i].Low <= Math.Min(made[i].Open, made[i].Close), made[i].ToString());
}
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASeriesWithMemoryLosesItInTheSurrogate()
{
var returns = Synthetic.AutoregressiveReturns(2000, 0.6, 4);
Assert.AreEqual(0.6, Synthetic.LagOne(returns), 0.05, "The hand-built series has memory.");
var lost = Enumerable.Range(0, 20)
.Select(k => Synthetic.LagOne(Surrogates.Flip(returns, TournamentStatistics.Signs(returns.Length, TournamentStatistics.ReplicaSeed(9, k)), centred: false)))
.ToList();
Assert.IsTrue(lost.Average(Math.Abs) < 0.1, string.Join(" ", lost));
Assert.IsTrue(lost.All(x => Math.Abs(x) < 0.15), string.Join(" ", lost));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AFallingDayTurnedUpSwapsHighAndLow()
{
// From a close of 100: open 101, high 103, low 98, close 99. With the sign turned, every price p becomes
// 100 × 100 / p, so the old low makes the new high and the old high the new low.
var day = Synthetic.Start;
IReadOnlyList<DailyBar> bars = [new(day, 100, 100, 100, 100, 10), new(day.AddDays(1), 101, 103, 98, 99, 20)];
var signs = new DaySigns(day, [1, -1]);
var made = Surrogates.Bars(bars, signs, centred: false);
Assert.AreEqual(bars[0], made[0]);
Assert.AreEqual(10_000.0 / 101, made[1].Open, 1e-9);
Assert.AreEqual(10_000.0 / 98, made[1].High, 1e-9);
Assert.AreEqual(10_000.0 / 103, made[1].Low, 1e-9);
Assert.AreEqual(10_000.0 / 99, made[1].Close, 1e-9);
Assert.AreEqual(20, made[1].Volume);
// The same day with its sign kept is the same bar.
var kept = Surrogates.Bars(bars, new DaySigns(day, [1, 1]), centred: false);
Assert.AreEqual(101, kept[1].Open, 1e-9);
Assert.AreEqual(103, kept[1].High, 1e-9);
Assert.AreEqual(98, kept[1].Low, 1e-9);
Assert.AreEqual(99, kept[1].Close, 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSurrogateRepeatsWithItsSeedAndChangesWithAnother()
{
var data = Synthetic.Walk(300, 2);
var one = Surrogates.Of(data, seed: 5, centred: true);
var again = Surrogates.Of(data, seed: 5, centred: true);
var other = Surrogates.Of(data, seed: 6, centred: true);
Assert.AreEqual(one.Fingerprint(), again.Fingerprint());
Assert.AreNotEqual(one.Fingerprint(), other.Fingerprint());
Assert.AreNotEqual(data.Fingerprint(), one.Fingerprint());
Assert.AreEqual(data.Currency, one.Currency);
CollectionAssert.AreEqual(data.Calendar.ToArray(), one.Calendar.ToArray());
// Signs belong to calendar days: the same days get the same signs whatever the instrument.
var signs = DaySigns.Draw(Synthetic.Start, Synthetic.Start.AddDays(9), 5);
Assert.AreEqual(Synthetic.Start, signs.First);
Assert.AreEqual(Synthetic.Start.AddDays(9), signs.Last);
CollectionAssert.AreEqual(TournamentStatistics.Signs(10, 5), Enumerable.Range(0, 10).Select(i => signs[Synthetic.Start.AddDays(i)]).ToArray());
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => signs[Synthetic.Start.AddDays(10)]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASurrogateOfInstrumentsWithCorporateActionsIsRefused()
{
var bars = BacktestData.Walk(60, 3);
var split = new CorporateAction("AAPL", CorporateActionKinds.Split, bars[30].Day, "test", "s1") { Ratio = 2m };
var data = BacktestData.One(BacktestData.Stock(), bars, [split]);
var error = Assert.ThrowsExactly<NotSupportedException>(() => Surrogates.Of(data, seed: 1, centred: true));
Assert.AreEqual("Il controllo contro il caso non è ancora previsto per gli strumenti con azioni societarie.", error.Message);
}
/// <summary>
/// Criterion 4, first half: three coins whose prices halve their distance from the mean in 50 bars, over 3000 days, and
/// a rule that buys them low and sells them back at the mean. Its result is real: at most 1 surrogate in 20 does as well.
/// One coin is not enough: the edge of this rule is a daily Sharpe ratio of about 0.03, the spread of the replicas
/// about 0.017, so on one coin of 3000 days the control passes on one seed out of three; three coins make it about
/// three spreads.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void OnAMeanRevertingSeriesAReversionRulePassesTheControl()
{
var data = Synthetic.MeanReverting(3000, 7, coins: 3, halfLife: 50, volatility: 0.01);
var (observed, replicas, share) = Synthetic.Control(ReversionFamily.Instance, ReversionFamily.With(300, 1m), data, 200, seed: 20_261_204, centred: true);
Assert.IsTrue(observed > 0, $"observed {observed}");
Assert.IsTrue(share <= 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
}
/// <summary>
/// Criterion 4, second half: on a random walk that drifts up, a long-only trend rule earns the drift and nothing
/// else. The centred surrogates keep the drift, so they do as well and the rule fails the control.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void OnARandomWalkWithDriftALongOnlyTrendRuleFailsTheControl()
{
var data = Synthetic.Walk(3000, 8, drift: 0.0008, volatility: 0.02);
var parameters = new StrategyParameters([new("fast", 20m), new("slow", 100m)]);
var (observed, replicas, share) = Synthetic.Control(MovingAverageCrossFamily.Instance, parameters, data, 200, seed: 20_261_204, centred: true);
Assert.IsTrue(share > 0.05, $"share {share}, observed {observed}, replicas median {replicas.Order().ElementAt(100)}");
}
}
+273
View File
@@ -0,0 +1,273 @@
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// Synthetic series with a known nature, built from a fixed seed (Phase 13): a mean-reverting price (Ornstein–Uhlenbeck on
/// the logarithm), a random walk with or without drift, returns with memory, correlated pairs. The statistics of the
/// tournament are proved on them, because only there is the truth known in advance. Shared by the tests of the control,
/// of the common statistics and of the tournament.
/// </summary>
internal static class Synthetic
{
public static readonly DateOnly Start = new(2018, 1, 1);
/// <summary>A coin quoted in euro on OKX, traded every day: the synthetic series live on it.</summary>
public static InstrumentSpec Coin(string symbol = "AAA-EUR") => new(Venues.Okx, symbol, symbol, AssetClasses.Crypto, "EUR")
{
BaseCurrency = symbol.Split('-')[0],
TickSize = 0.0001m,
LotSize = 0.00000001m,
MinSize = 0.00001m,
Status = "live",
};
/// <summary>The autoregressive coefficient of a daily series whose distance from its mean halves in <paramref name="halfLife"/> bars.</summary>
public static double Phi(double halfLife) => Math.Pow(0.5, 1.0 / halfLife);
/// <summary>
/// Log returns of a price whose logarithm reverts to a fixed level: x(t) = φ·x(t−1) + σ·ε, with φ from the
/// <paramref name="halfLife"/> and the series started at its level. The return of day t is x(t) − x(t−1).
/// </summary>
public static double[] MeanRevertingReturns(int days, int seed, double halfLife = 50, double volatility = 0.01)
{
var gen = new Gen(seed);
var phi = Phi(halfLife);
var result = new double[days];
var x = 0.0;
for (var i = 0; i < days; i++)
{
var next = (phi * x) + (volatility * gen.Normal());
result[i] = next - x;
x = next;
}
return result;
}
/// <summary>Log returns of a random walk: <paramref name="drift"/> plus normal noise, no memory.</summary>
public static double[] WalkReturns(int days, int seed, double drift = 0, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
for (var i = 0; i < days; i++)
{
result[i] = drift + (volatility * gen.Normal());
}
return result;
}
/// <summary>Returns with memory: r(t) = φ·r(t−1) + σ·ε, so the autocorrelation at lag one is φ.</summary>
public static double[] AutoregressiveReturns(int days, double phi, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var result = new double[days];
var previous = 0.0;
for (var i = 0; i < days; i++)
{
previous = (phi * previous) + (volatility * gen.Normal());
result[i] = previous;
}
return result;
}
/// <summary>Two series of returns with correlation about <paramref name="correlation"/>: a common part and a part of each.</summary>
public static (double[] A, double[] B) CorrelatedReturns(int days, double correlation, int seed, double volatility = 0.01)
{
var gen = new Gen(seed);
var own = Math.Sqrt(1 - (correlation * correlation));
var a = new double[days];
var b = new double[days];
for (var i = 0; i < days; i++)
{
var common = gen.Normal();
a[i] = volatility * common;
b[i] = volatility * ((correlation * common) + (own * gen.Normal()));
}
return (a, b);
}
/// <summary>
/// Daily bars from log returns of the close: the first bar at <paramref name="start"/>, then each close the one before
/// times e^r. The open is the previous close, high and low a little beyond the body, all unrounded.
/// </summary>
public static IReadOnlyList<DailyBar> Bars(IReadOnlyList<double> logReturns, int seed = 1, double start = 100, DateOnly? from = null)
{
ArgumentNullException.ThrowIfNull(logReturns);
var gen = new Gen(seed);
var day = from ?? Start;
var bars = new List<DailyBar>(logReturns.Count + 1) { new(day, start, start * 1.002, start * 0.998, start, 1000) };
var close = start;
for (var i = 0; i < logReturns.Count; i++)
{
var open = close;
close = open * Math.Exp(logReturns[i]);
var high = Math.Max(open, close) * (1 + (0.003 * gen.Double()));
var low = Math.Min(open, close) * (1 - (0.003 * gen.Double()));
bars.Add(new DailyBar(day.AddDays(i + 1), open, high, low, close, 1000));
}
return bars;
}
/// <summary>A dataset in euro of synthetic coins, one per series of bars.</summary>
public static BacktestDataset Dataset(params (string Symbol, IReadOnlyList<DailyBar> Bars)[] series) =>
new(series.Select(s => new BacktestInstrument(Coin(s.Symbol), s.Bars, source: "sintetico")), "EUR");
/// <summary>A mean-reverting coin: <paramref name="days"/> returns of <see cref="MeanRevertingReturns"/> turned into bars.</summary>
public static BacktestDataset MeanReverting(int days, int seed, double halfLife = 50, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(MeanRevertingReturns(days, seed, halfLife, volatility), seed)));
/// <summary>Several independent mean-reverting coins in one dataset (AAA-EUR, AAB-EUR, …), each from its own seed.</summary>
public static BacktestDataset MeanReverting(int days, int seed, int coins, double halfLife = 50, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(MeanRevertingReturns(days, seed + (1000 * k), halfLife, volatility), seed + k)))]);
/// <summary>Several independent coins walking at random with the same <paramref name="drift"/>, each from its own seed.</summary>
public static BacktestDataset Walk(int days, int seed, int coins, double drift = 0, double volatility = 0.01) =>
Dataset([.. Enumerable.Range(0, coins).Select(k => (Symbol(k), Bars(WalkReturns(days, seed + (1000 * k), drift, volatility), seed + k)))]);
/// <summary>The symbol of the k-th synthetic coin: AAA-EUR, AAB-EUR, AAC-EUR…</summary>
public static string Symbol(int k) => string.Concat("AA", ((char)('A' + k)).ToString(), "-EUR");
/// <summary>A coin that walks at random with a <paramref name="drift"/> a day (zero for pure noise).</summary>
public static BacktestDataset Walk(int days, int seed, double drift = 0, double volatility = 0.01, string symbol = "AAA-EUR") =>
Dataset((symbol, Bars(WalkReturns(days, seed, drift, volatility), seed)));
/// <summary>Log returns of the closes of a series of bars, one per bar after the first.</summary>
public static double[] CloseReturns(IReadOnlyList<DailyBar> bars)
{
ArgumentNullException.ThrowIfNull(bars);
return [.. Enumerable.Range(1, Math.Max(bars.Count - 1, 0)).Select(i => Math.Log(bars[i].Close / bars[i - 1].Close))];
}
/// <summary>Pearson correlation of two series of the same length.</summary>
public static double Correlation(IReadOnlyList<double> x, IReadOnlyList<double> y)
{
var mx = x.Average();
var my = y.Average();
double sxy = 0, sxx = 0, syy = 0;
for (var i = 0; i < x.Count; i++)
{
sxy += (x[i] - mx) * (y[i] - my);
sxx += (x[i] - mx) * (x[i] - mx);
syy += (y[i] - my) * (y[i] - my);
}
return sxy / Math.Sqrt(sxx * syy);
}
/// <summary>Autocorrelation at lag one.</summary>
public static double LagOne(IReadOnlyList<double> x) => Correlation([.. x.Take(x.Count - 1)], [.. x.Skip(1)]);
/// <summary>The daily Sharpe ratio of a run: what the control compares between the real series and its replicas.</summary>
public static double Sharpe(BacktestRun run) => Moments.Of(run.DailyReturns()).Sharpe;
/// <summary>
/// The control of a rule on a dataset: its daily Sharpe on the real data, and on <paramref name="repetitions"/>
/// surrogates whose signs come from <paramref name="seed"/> + k. Returns the observed Sharpe, the replicas and the
/// share of replicas at least as good.
/// </summary>
public static (double Observed, double[] Replicas, double Share) Control(IStrategyFamily family, StrategyParameters parameters, BacktestDataset data, int repetitions, int seed, bool centred)
{
ArgumentNullException.ThrowIfNull(family);
var options = new BacktestOptions();
var observed = Sharpe(BacktestEngine.Run(family.Create(parameters), data, options));
var replicas = new double[repetitions];
for (var k = 0; k < repetitions; k++)
{
var surrogate = Surrogates.Of(data, TournamentStatistics.ReplicaSeed(seed, k), centred);
replicas[k] = Sharpe(BacktestEngine.Run(family.Create(parameters), surrogate, options));
}
return (observed, replicas, TournamentStatistics.ControlShare(observed, replicas));
}
}
/// <summary>
/// A test-only reversion rule, long only: it buys an instrument when its close falls <c>entry</c> standard deviations
/// below the mean of the last <c>lookback</c> closes (on the logarithm), and sells when the close is back at the mean. It
/// has an edge on a mean-reverting series and none on a random walk. It never enters the catalogue and has no order code.
/// </summary>
internal sealed class ReversionRule(int lookback, decimal entry) : IStrategy
{
/// <summary>Bars it waits for before the first decision; until <c>lookback</c> bars, the mean is of those there are.</summary>
public const int MinimumBars = 50;
public string Id => ReversionFamily.FamilyId;
public string Version => "1";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
public IReadOnlyList<Intent> Decide(StrategyContext context)
{
var intents = new List<Intent>();
var weight = 1m / Math.Max(context.Universe.Count, 1);
foreach (var symbol in context.Universe)
{
var bars = context.Bars(symbol);
if (bars.Count < Math.Min(lookback, MinimumBars))
{
continue;
}
var logs = bars.Closes(lookback).Select(c => Math.Log(c)).ToArray();
var m = Moments.Of(logs);
if (m.StandardDeviation <= 0)
{
continue;
}
var z = (logs[^1] - m.Mean) / m.StandardDeviation;
var held = context.Portfolio.Holds(symbol);
if (!held && z < -(double)entry)
{
intents.Add(new Intent(symbol, weight, "reversion_entry"));
}
else if (held && z >= 0)
{
intents.Add(new Intent(symbol, 0m, "reversion_exit"));
}
}
return intents;
}
}
/// <summary>The family of <see cref="ReversionRule"/>: the window of the mean and the distance of the entry.</summary>
internal sealed class ReversionFamily : IStrategyFamily
{
public const string FamilyId = "test_reversion";
public static ReversionFamily Instance { get; } = new();
public string Id => FamilyId;
public string Version => "1";
public string Name => "Rientro di prova";
public string Description => "Regola di prova, solo nei test: compra sotto la media e vende quando il prezzo vi torna.";
public IReadOnlyList<ParameterSpec> Parameters =>
[
new("lookback", "Giorni della media", 100m, [50m, 100m, 150m], 10m, 400m, Whole: true),
new("entry", "Distanza d'ingresso in deviazioni", 1m, [0.5m, 1m, 1.5m], 0.1m, 4m),
];
public IStrategy Create(StrategyParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
return new ReversionRule(parameters.Whole("lookback"), parameters["entry"]);
}
/// <summary>The parameters of a variant, as the laboratory would build them.</summary>
public static StrategyParameters With(int lookback, decimal entry) => new([new("lookback", lookback), new("entry", entry)]);
}
@@ -0,0 +1,218 @@
using Anubis.Backtest;
namespace Anubis.Tests;
/// <summary>
/// The common statistics of the tournament (issue #124, criterion 5 of Phase 13): one number of trials for the whole field,
/// one bar, one variance, one PBO, the effective number of bets, the bootstrap interval and the calendars put side by side.
/// </summary>
[TestClass]
public sealed class TournamentStatisticsTests
{
private static readonly DateOnly Monday = new(2024, 1, 1);
[TestMethod]
[TestCategory(Category.Unit)]
public void TwentyEightIdenticalSeriesAreWorthOneBet()
{
var one = Synthetic.WalkReturns(500, 1);
var copies = Enumerable.Range(0, 28).Select(_ => one.ToArray()).ToList();
Assert.AreEqual(1.0, TournamentStatistics.EffectiveBets(copies), 1e-12);
// Independent series are about as many bets as series; a flat series is a bet of its own.
var independent = Enumerable.Range(0, 28).Select(k => Synthetic.WalkReturns(500, 100 + k)).ToList();
Assert.IsTrue(TournamentStatistics.EffectiveBets(independent) > 20, TournamentStatistics.EffectiveBets(independent).ToString(System.Globalization.CultureInfo.InvariantCulture));
Assert.AreEqual(2.0, TournamentStatistics.EffectiveBets([one, new double[500]]), 1e-12);
Assert.AreEqual(0.0, TournamentStatistics.EffectiveBets([]));
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.EffectiveBets([one, new double[10]]));
}
/// <summary>
/// A rule with no edge, tried in a hundred variants on noise: the best one looks good alone, but against the common
/// number of trials and the variance of the field it never reaches the threshold of 0.90.
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AStrategyWithNoEdgeTriedInOneHundredVariantsStaysBelowTheBar()
{
for (var seed = 1; seed <= 10; seed++)
{
var variants = Enumerable.Range(0, 100).Select(k => Synthetic.WalkReturns(1000, (seed * 1000) + k)).ToList();
var sharpes = variants.Select(v => Moments.Of(v).Sharpe).ToList();
var best = variants[sharpes.IndexOf(sharpes.Max())];
var variance = TournamentStatistics.FieldVariance([new FieldSharpes(365, sharpes)]);
var trials = TournamentStatistics.CommonTrials(100, 0, 0, 0);
var dsr = TournamentStatistics.CommonDeflated(best, 365, trials, variance);
Assert.AreEqual(100, dsr.Trials);
Assert.IsTrue(dsr.Value < 0.90, $"seed {seed}: DSR {dsr.Value}");
Assert.IsTrue(SharpeTests.Deflated(best, 1, 0).Value > dsr.Value, "Alone, the best variant looks better.");
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFieldVarianceIsTakenOnAnnualisedSharpes()
{
// A crypto contender (365 days a year) and a stock one (252): their daily Sharpes become annual before the
// variance, and the variance goes back to daily with the year of the series judged.
var field = new[] { new FieldSharpes(365, [0.05, 0.07]), new FieldSharpes(252, [0.05, 0.07]) };
double[] annual = [0.05 * Math.Sqrt(365), 0.07 * Math.Sqrt(365), 0.05 * Math.Sqrt(252), 0.07 * Math.Sqrt(252)];
var expected = Math.Pow(Moments.Of(annual).StandardDeviation, 2);
Assert.AreEqual(expected, TournamentStatistics.FieldVariance(field), 1e-15);
var returns = Synthetic.WalkReturns(500, 2, drift: 0.001);
var crypto = TournamentStatistics.CommonDeflated(returns, 365, 50, expected);
var stock = TournamentStatistics.CommonDeflated(returns, 252, 50, expected);
Assert.AreEqual(expected / 365, crypto.SharpeVariance, 1e-18);
Assert.AreEqual(expected / 252, stock.SharpeVariance, 1e-18);
Assert.IsTrue(stock.Benchmark > crypto.Benchmark, "Fewer days a year, a higher daily bar.");
Assert.AreEqual(0, TournamentStatistics.FieldVariance([new FieldSharpes(365, [0.05])]));
}
/// <summary>
/// Noise on two calendars, crypto every day and stocks on weekdays, put side by side with zero on the days without a
/// session: the probability of overfitting of the whole field is about one half. On average over forty seeds, because on
/// one seed alone it swings widely (from 0.14 to 0.54 on the first eight).
/// </summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCommonPboOnNoiseIsAboutOneHalf()
{
var values = new List<double>();
for (var seed = 1; seed <= 40; seed++)
{
var gen = new Gen(seed);
var everyDay = Enumerable.Range(0, 1100).Select(i => Monday.AddDays(i)).ToList();
var weekdays = everyDay.Where(d => d.DayOfWeek is not DayOfWeek.Saturday and not DayOfWeek.Sunday).ToList();
var series = new List<(IReadOnlyList<DateOnly> Days, IReadOnlyList<double> Returns)>();
for (var v = 0; v < 10; v++)
{
series.Add((everyDay, [.. everyDay.Select(_ => 0.01 * gen.Normal())]));
series.Add((weekdays, [.. weekdays.Select(_ => 0.01 * gen.Normal())]));
}
var aligned = TournamentStatistics.Align(series);
var pbo = TournamentStatistics.CommonOverfitting(aligned);
Assert.IsNotNull(pbo);
Assert.AreEqual(20, pbo.Variants);
Assert.AreEqual(12870, pbo.Combinations);
values.Add(pbo.Probability);
}
Assert.AreEqual(0.5, values.Average(), 0.1, string.Join(" ", values));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheBarGrowsWithTheTrials()
{
Assert.AreEqual(0, TournamentStatistics.Bar(1));
Assert.IsTrue(TournamentStatistics.Bar(10) < TournamentStatistics.Bar(100));
Assert.IsTrue(TournamentStatistics.Bar(100) < TournamentStatistics.Bar(1000));
Assert.AreEqual(SharpeTests.ExpectedMaximum(100, 1), TournamentStatistics.Bar(100));
// The best of a hundred tries of nothing stands about two and a half standard deviations above zero.
Assert.AreEqual(2.5, TournamentStatistics.Bar(100), 0.1);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void EightFinalistsGiveEightySevenCombinations()
{
// 28 pairs and the whole set, each with three weighting schemes.
Assert.AreEqual(87, TournamentStatistics.Combinations(8, 3));
Assert.AreEqual(6, TournamentStatistics.Combinations(2, 3));
Assert.AreEqual(0, TournamentStatistics.Combinations(1, 3));
Assert.AreEqual(0, TournamentStatistics.Combinations(0, 3));
Assert.AreEqual(500 + 87 + 40 + 27, TournamentStatistics.CommonTrials(500, 87, 40, 27));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.CommonTrials(-1, 0, 0, 0));
Assert.ThrowsExactly<OverflowException>(() => TournamentStatistics.CommonTrials(int.MaxValue, 1, 0, 0));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheIntervalContainsTheTrueMeanOfAKnownSeries()
{
var gen = new Gen(3);
var values = Enumerable.Range(0, 400).Select(_ => 0.05 + gen.Normal()).ToArray();
static double Mean(ReadOnlySpan<double> x)
{
var sum = 0.0;
foreach (var v in x)
{
sum += v;
}
return sum / x.Length;
}
var (low, high) = TournamentStatistics.Interval(values, Mean, block: 10, rounds: 2000, confidence: 0.95, seed: 1);
Assert.IsTrue(low < 0.05 && 0.05 < high, $"{low} – {high}");
Assert.IsTrue(high - low is > 0.1 and < 0.3, $"width {high - low}");
Assert.AreEqual((low, high), TournamentStatistics.Interval(values, Mean, 10, 2000, 0.95, 1), "The same seed gives the same interval.");
// Dependent data: each value ten times in a row. As many numbers as independent ones, ten times fewer facts.
var twins = values.SelectMany(v => Enumerable.Repeat(v, 10)).ToArray();
var independent = Enumerable.Range(0, twins.Length).Select(_ => 0.05 + gen.Normal()).ToArray();
var (tl, th) = TournamentStatistics.Interval(twins, Mean, 10, 2000, 0.95, 1);
var (il, ih) = TournamentStatistics.Interval(independent, Mean, 10, 2000, 0.95, 1);
Assert.IsTrue(th - tl > 1.8 * (ih - il), $"twins {th - tl}, independent {ih - il}");
// Fewer than three blocks: nothing can be said.
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), TournamentStatistics.Interval(values[..29], Mean, 10, 2000, 0.95, 1));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AlignmentPutsTheSeriesOnTheUnionOfTheirDaysWithZeroWhereThereIsNoSession()
{
// Crypto from Monday 1 January for ten days; a stock from Wednesday 3 January on weekdays to Friday 12.
var crypto = Enumerable.Range(0, 10).Select(i => Monday.AddDays(i)).ToList();
var stock = new[] { 2, 3, 4, 7, 8, 9, 10, 11 }.Select(i => Monday.AddDays(i)).ToList();
var aligned = TournamentStatistics.Align(
[
(crypto, [.. crypto.Select((_, i) => (i + 1) / 100.0)]),
(stock, [.. stock.Select((_, i) => -(i + 1) / 100.0)]),
]);
// The common window runs from the latest first day (3 January) to the earliest last day (10 January).
CollectionAssert.AreEqual(Enumerable.Range(2, 8).Select(i => Monday.AddDays(i)).ToArray(), aligned.Days.ToArray());
CollectionAssert.AreEqual(new[] { 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10 }, aligned.Returns[0]);
// Saturday 6 and Sunday 7 January: the stock has no session, its equity does not move.
CollectionAssert.AreEqual(new[] { -0.01, -0.02, -0.03, 0, 0, -0.04, -0.05, -0.06 }, aligned.Returns[1]);
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([(crypto, [0.1])]));
Assert.ThrowsExactly<ArgumentException>(() => TournamentStatistics.Align([([Monday.AddDays(1), Monday], [0.1, 0.2])]));
Assert.IsEmpty(TournamentStatistics.Align([(crypto[..3], [0.1, 0.2, 0.3]), (crypto[5..], [0.1, 0.2, 0.3, 0.4, 0.5])]).Days);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SignsAreOnePerDayAndRepeatWithTheirSeed()
{
var signs = TournamentStatistics.Signs(1000, 7);
Assert.HasCount(1000, signs);
Assert.IsTrue(signs.All(s => s is 1 or -1));
Assert.IsTrue(signs.Count(s => s > 0) is > 450 and < 550);
CollectionAssert.AreEqual(signs, TournamentStatistics.Signs(1000, 7));
CollectionAssert.AreNotEqual(signs, TournamentStatistics.Signs(1000, TournamentStatistics.ReplicaSeed(7, 1)));
Assert.AreEqual(10, TournamentStatistics.ReplicaSeed(7, 3));
Assert.AreEqual(int.MinValue, TournamentStatistics.ReplicaSeed(int.MaxValue, 1), "The seed wraps instead of failing.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheControlShareCountsTheReplicasAtLeastAsGood()
{
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(1.0, [0.0, 1.0, 2.0, 0.5]));
Assert.AreEqual(0.0, TournamentStatistics.ControlShare(3.0, [0.0, 1.0, 2.0, 0.5]));
// Nothing to say is never a pass: an observed NaN fails, a NaN replica counts against.
Assert.AreEqual(1.0, TournamentStatistics.ControlShare(double.NaN, [0.0, 1.0]));
Assert.AreEqual(0.5, TournamentStatistics.ControlShare(3.0, [double.NaN, 1.0]));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TournamentStatistics.ControlShare(1.0, []));
}
}
+873
View File
@@ -0,0 +1,873 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Platform;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The tournament of the strategies (issues #123 and #125, criteria 2 and 6 of Phase 13): a plan written before any result,
/// the trials of the contenders on the search window, the finalists, the final tract opened once, the control against
/// chance and the common statistics, on synthetic series whose nature is known in advance.
/// </summary>
[TestClass]
public sealed class TournamentTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 0, 0, TimeSpan.Zero);
/// <summary>Warm-up of 450 days before the search, as every trial reads.</summary>
private static readonly DateOnly SearchFrom = Synthetic.Start.AddDays(TrialData.WarmupDays);
private static readonly Dictionary<string, IReadOnlyList<decimal>> OneGrid = new() { ["lookback"] = [20m], ["entry"] = [1m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> EdgeGrid = new() { ["lookback"] = [20m], ["entry"] = [1.5m] };
private static readonly Dictionary<string, IReadOnlyList<decimal>> NoiseGrid = new() { ["lookback"] = [20m, 40m, 60m], ["entry"] = [0.5m, 1m, 1.5m] };
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePlanIsWrittenBeforeAnyResultAndNeverChanges()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// A plan that breaks a rule is refused in Italian and leaves nothing behind.
var good = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
(TournamentRequest Request, string Message)[] wrong =
[
(good with { Name = " " }, "Dai un nome al campionato."),
(good with { Contenders = [] }, "Serve almeno un concorrente."),
(good with { Contenders = [good.Contenders[0], good.Contenders[0]] }, "L'etichetta «a» è usata due volte."),
(good with { Contenders = [good.Contenders[0] with { Group = "" }] }, "Il concorrente «a» ha bisogno di un gruppo e di un mercato."),
(good with { Contenders = [good.Contenders[0] with { Strategy = "nessuna" }] }, "Concorrente «a»: strategia sconosciuta."),
(good with { HoldoutFrom = good.Contenders[0].To.AddDays(-10) }, "Il tratto finale di «a» deve durare almeno 30 giorni: i suoi dati finiscono il 04/01/2021."),
(good with { HoldoutFrom = SearchFrom }, "Il tratto finale deve cominciare dopo l'inizio di «a», che comincia il 27/03/2019."),
(good with { Control = new TournamentControl(19, 1) }, "Le ripetizioni del controllo contro il caso vanno da 20 a 10000."),
(good with { Contenders = [good.Contenders[0] with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["lookback"] = [5m] } }] },
"Concorrente «a»: Giorni della media: i valori vanno da 10 a 400."),
(good with { PriorCounted = [new PriorCount("docs/backtests", "crypto_trend", -1)] },
"Le prove già contate hanno bisogno di una strategia e di un numero non negativo di varianti."),
];
foreach (var (request, message) in wrong)
{
var error = await Assert.ThrowsExactlyAsync<TournamentPlanException>(() => lab.PlanTournamentAsync(request, _none)).ConfigureAwait(false);
Assert.AreEqual(message, error.Message);
}
Assert.AreEqual(0, await CountAsync(test, "tournaments").ConfigureAwait(false));
Assert.AreEqual(0, await CountAsync(test, "backtest_trials").ConfigureAwait(false));
// The plan and the trials of its contenders are written together, before anything runs or is read.
var tournament = await lab.PlanTournamentAsync(good, _none).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Planned, tournament.Status);
Assert.IsTrue(tournament.PlanIntact);
var before = await RawPlanAsync(test, tournament.Id).ConfigureAwait(false);
Assert.AreEqual(TrialPlan.Hash(before.Plan), before.Hash);
var plan = tournament.Plan;
Assert.AreEqual(TournamentThresholds.Default, plan.Thresholds);
Assert.AreEqual(0.05, plan.Thresholds.MaxControlShare);
Assert.AreEqual(TrialThresholds.Default.MinDeflatedSharpe, plan.Thresholds.MinDeflatedSharpe);
CollectionAssert.AreEqual(new[] { 1m, 2m, 3m }, plan.CostMultipliers.ToArray());
Assert.AreEqual(new TournamentFinalists(8, "group_and_market", "walk_forward_sharpe"), plan.Finalists);
Assert.AreEqual(180, plan.Combinations.LookbackDays);
CollectionAssert.AreEqual(new[] { "equal", "inverse_volatility", "risk_parity" }, plan.Combinations.WeightSchemes.ToArray());
Assert.AreEqual(27, plan.PriorCounted.Sum(p => p.Variants));
Assert.AreEqual(18, plan.PriorCounted.Single(p => p.Strategy == "crypto_trend").Variants);
Assert.IsNotEmpty(plan.StressWindows);
Assert.AreEqual(TrialValidation.Default, plan.Validation);
Assert.AreEqual(Now, plan.WrittenAt);
Assert.AreEqual(0, plan.RegistryVariantsAtPlanning);
Assert.AreEqual(1 + 1 + TournamentStatistics.Combinations(2, 3) + 27, plan.PlannedTrials, "N planned: the variants, the combinations of two finalists, what was tried before.");
Assert.AreEqual(TournamentStatistics.Bar(plan.PlannedTrials), plan.Bar);
Assert.IsGreaterThan(2.0, plan.Bar, "The plan shows the bar before the start.");
Assert.AreEqual(TournamentPlan.FromJson(before.Plan).ToJson(), before.Plan, "The stored plan is its own text.");
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(2, trials);
var trialPlans = new List<(string Plan, string Hash)>();
foreach (var trial in trials)
{
Assert.AreEqual(tournament.Id, trial.TournamentId);
Assert.AreEqual(TrialStatuses.Planned, trial.Status);
Assert.AreEqual(good.HoldoutFrom.AddDays(-1), trial.Plan.Data.To, "A contender's trial never reads the final tract.");
Assert.IsNull(await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false));
trialPlans.Add(await RawTrialPlanAsync(test, trial.Id).ConfigureAwait(false));
}
CollectionAssert.AreEqual(new[] { "EAA-EUR" }, trials[0].Plan.Data.Symbols.ToArray());
Assert.AreEqual(0, await CountAsync(test, "tournament_units").ConfigureAwait(false), "No result exists yet.");
Assert.IsEmpty(field.Reads, "No data was read yet.");
Assert.IsNull(await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false));
// The contenders run, the tournament is judged; the plans have not changed by a byte.
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
Assert.AreEqual(before, await RawPlanAsync(test, tournament.Id).ConfigureAwait(false), "The plan text and its hash are never updated.");
for (var i = 0; i < trials.Count; i++)
{
Assert.AreEqual(trialPlans[i], await RawTrialPlanAsync(test, trials[i].Id).ConfigureAwait(false));
}
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(before.Hash, report.PlanHash);
Assert.AreEqual(tournament.Id, report.TournamentId);
// The units of the tournament lose their outcomes when it ends: the rows stay as a record.
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
Assert.IsNotEmpty(units);
Assert.IsTrue(units.All(u => u.Status == TrialUnitStatuses.Done && !u.HasOutcome));
CollectionAssert.IsSubsetOf(new[] { "variant", "control", "holdout" }, units.Select(u => u.Kind).Distinct().ToArray());
// A plan changed after it was written no longer gives its hash: the tournament is not judged.
var tampered = await lab.PlanTournamentAsync(good with { Contenders = [good.Contenders[0] with { Symbols = ["XYZ-EUR"] }] }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", tampered.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.IsFalse(refused.PlanIntact);
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
StringAssert.Contains(refused.Error, "impronta");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFinalTractIsReadOnce()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
// a and b share a group and a market: only the better of the two goes on. c has its own.
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g1", "m1", ["NAA-EUR"], OneGrid), ("c", "g2", "m1", ["NAB-EUR"], OneGrid));
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
CollectionAssert.AreEquivalent(new[] { "a", "c" }, done.Finalists!.ToArray());
CollectionAssert.AreEqual(done.Finalists!.ToArray(), report.Finalists.Select(f => f.Label).ToArray());
CollectionAssert.AreEqual(new[] { true, false, true }, report.Contenders.Select(c => c.Finalist).ToArray());
Assert.IsNotNull(done.HoldoutOpenedAt);
// The final tract was read once, only for the finalists; the trials read up to the day before it.
var tract = field.Reads.Where(r => r.To > request.HoldoutFrom.AddDays(-1)).ToList();
Assert.IsTrue(tract.All(r => r.From == request.HoldoutFrom), "Only the runs of the final tract read past the search.");
CollectionAssert.AreEquivalent(new[] { "EAA-EUR", "NAB-EUR" }, tract.SelectMany(r => r.Symbols).ToArray());
Assert.IsTrue(field.Reads.Where(r => r.Symbols.Contains("NAA-EUR")).All(r => r.To == request.HoldoutFrom.AddDays(-1)), "A contender that is not a finalist never sees it.");
// The finalists cannot change once the tract is open: a second opening gets back the first, at the first moment.
clock.Advance(TimeSpan.FromHours(1));
var again = await lab.Tournaments.OpenHoldoutAsync(tournament.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(done.Finalists!.ToArray(), again.Finalists.ToArray());
Assert.AreEqual(done.HoldoutOpenedAt, again.OpenedAt);
// A tournament judged is not judged again.
var reads = field.Reads.Count;
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
Assert.HasCount(reads, field.Reads);
// On a fresh tournament the first opening writes, the second gets it back.
var store = lab.Tournaments;
var other = await lab.PlanTournamentAsync(request with { Name = "Altro" }, _none).ConfigureAwait(false);
var first = await store.OpenHoldoutAsync(other.Id, ["c", "a"], _none).ConfigureAwait(false);
clock.Advance(TimeSpan.FromHours(1));
var second = await store.OpenHoldoutAsync(other.Id, ["b"], _none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { "c", "a" }, first.Finalists.ToArray());
CollectionAssert.AreEqual(new[] { "c", "a" }, second.Finalists.ToArray());
Assert.AreEqual(first.OpenedAt, second.OpenedAt);
CollectionAssert.AreEqual(new[] { "c", "a" }, (await store.GetAsync(other.Id, _none).ConfigureAwait(false))!.Finalists!.ToArray());
}
/// <summary>
/// Criterion 6: a field built on purpose, two contenders with an edge (the reversion rule on prices that revert to their
/// mean) and four of noise (the same rule on random walks without drift), each in its own group and market so all six are
/// finalists, judged with 200 repetitions of the control. Only the two with an edge pass. The variance of the field is
/// mostly the gap between edge and noise when a third of the field has an edge, and the bar of 113 trials rises with
/// it: the edges here are searched less (one variant against nine), as in a real field where noise is most of the search.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFieldWithTwoEdgesAndFourNoisesPassesOnlyTheTwo()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
const int days = 2314;
var field = new SyntheticField();
foreach (var (symbol, seed) in new[] { ("EAA-EUR", 101), ("EAB-EUR", 102), ("EAC-EUR", 103), ("EBA-EUR", 201), ("EBB-EUR", 202), ("EBC-EUR", 203) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.MeanRevertingReturns(days, seed, halfLife: 2, volatility: 0.02), seed));
}
foreach (var (symbol, seed) in new[] { ("NAA-EUR", 301), ("NAB-EUR", 302), ("NAC-EUR", 303), ("NAD-EUR", 304) })
{
field.Add(symbol, Synthetic.Bars(Synthetic.WalkReturns(days, seed, drift: 0, volatility: 0.02), seed));
}
using var lab = Lab(test, clock, field, workers: 4);
var to = Synthetic.Start.AddDays(days);
var holdoutFrom = to.AddDays(-364);
var request = new TournamentRequest("Campo costruito apposta",
[
Contender("bordo-1", "g1", "m1", ["EAA-EUR", "EAB-EUR", "EAC-EUR"], EdgeGrid, to),
Contender("bordo-2", "g2", "m2", ["EBA-EUR", "EBB-EUR", "EBC-EUR"], EdgeGrid, to),
Contender("rumore-1", "g3", "m3", ["NAA-EUR"], NoiseGrid, to),
Contender("rumore-2", "g4", "m4", ["NAB-EUR"], NoiseGrid, to),
Contender("rumore-3", "g5", "m5", ["NAC-EUR"], NoiseGrid, to),
Contender("rumore-4", "g6", "m6", ["NAD-EUR"], NoiseGrid, to),
], holdoutFrom, 10_000m);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
Assert.AreEqual(200, tournament.Plan.Control.Repetitions);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
var said = Describe(report);
Assert.HasCount(6, report.Finalists, said);
Assert.AreEqual(new TournamentTrialsCount(2 + (4 * 9), TournamentStatistics.Combinations(6, 3), 0, 27, 113), report.Trials, said);
Assert.AreEqual(TournamentStatistics.Bar(113), report.Bar);
CollectionAssert.AreEquivalent(new[] { "bordo-1", "bordo-2" }, report.Finalists.Where(f => f.Passed).Select(f => f.Label).ToArray(), said);
Assert.AreEqual(2, report.PassedCount);
Assert.IsTrue(report.Passed);
Assert.AreEqual(TrialVerdicts.Passed, done.Verdict);
foreach (var edge in report.Finalists.Where(f => f.Label.StartsWith("bordo", StringComparison.Ordinal)))
{
Assert.IsTrue(edge.Checks.All(c => c.Passed == true), said);
Assert.AreEqual(200, edge.Control.Repetitions);
Assert.IsTrue(edge.Control.Centred, "The daily engine only buys: its control turns around the mean.");
Assert.IsLessThanOrEqualTo(0.05, edge.Control.Share!.Value, said);
Assert.IsGreaterThan(0.0, edge.SharpeInterval.Low, said);
}
foreach (var noise in report.Finalists.Where(f => f.Label.StartsWith("rumore", StringComparison.Ordinal)))
{
Assert.IsFalse(noise.Passed, said);
Assert.IsLessThan(0.90, noise.DeflatedSharpe.Value, said);
}
Assert.IsLessThanOrEqualTo(0.40, report.Overfitting!.Probability, said);
Assert.AreEqual(38, report.Overfitting.Variants);
Assert.IsNotNull(report.EffectiveBets);
Assert.IsTrue(report.EffectiveBets is > 4 and <= 6, said);
Assert.AreEqual(TournamentReport.FromJson(report.ToJson()).ToJson(), report.ToJson());
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingDoesNotRedoFinishedControlUnits()
{
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
const int total = 2 * 20;
// The same tournament judged without a stop, for comparison.
TournamentReport whole;
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var reference = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
await RunAllAsync(lab, reference.Id).ConfigureAwait(false);
var json = await lab.Tournaments.ReportJsonAsync(reference.Id, _none).ConfigureAwait(false);
Assert.IsNotNull(json, (await lab.Tournaments.GetAsync(reference.Id, _none).ConfigureAwait(false))!.Error);
whole = TournamentReport.FromJson(json);
}
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The process stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
var before = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), before, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Judging, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
var units = await AllUnitsAsync(test, tournament.Id).ConfigureAwait(false);
var symbols = trials.ToDictionary(t => t.Id, t => t.Plan.Data.Symbols[0]);
var finished = (await DoneControlsAsync(test, tournament.Id).ConfigureAwait(false)).Select(u => FormattableString.Invariant($"control {symbols[u.Trial]} {u.Key.Split(':')[1]}")).ToList();
Assert.IsGreaterThanOrEqualTo(5, finished.Count);
Assert.IsTrue(units.Where(u => u.Status == TrialUnitStatuses.Done).All(u => u.HasOutcome), "The tournament keeps its outcomes until it ends.");
Assert.IsFalse(field.Reads.Any(r => r.From == plan.HoldoutFrom), "The stop came before the final tract.");
// The next start judges it again: only the repetitions not finished run, the final tract is read once.
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(total - finished.Count, controls);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(controls, key, "A finished repetition does not run again: " + key);
}
CollectionAssert.AreEquivalent(controls.Concat(finished).ToArray(), controls.Concat(finished).Distinct().ToArray());
Assert.HasCount(total, controls.Concat(finished).Distinct().ToList(), "Every repetition of both finalists is done once.");
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList(), "Two finalists, plain and doubled costs.");
Assert.HasCount(2, field.Reads.Where(r => r.From == plan.HoldoutFrom).ToList(), "The final tract of each finalist is read once.");
var report = TournamentReport.FromJson((await lab.Tournaments.ReportJsonAsync(tournament.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual(Comparable(whole), Comparable(report));
}
}
/// <summary>
/// The repetitions of the control done before a stop by another build (or on other data) are not reused: the judge started
/// again runs every repetition, so the control of a finalist is never a mix of two engines.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AResumedJudgingRunsAgainTheControlUnitsOfAnotherBuild()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var plan = tournament.Plan;
var first = plan.Contenders.Min(c => (c.Data with { To = plan.SearchTo }).HistoryStart());
var replicas = Enumerable.Range(0, plan.Control.Repetitions)
.ToDictionary(k => SignsOf(DaySigns.Draw(first, plan.SearchTo, TournamentStatistics.ReplicaSeed(plan.Control.Seed, k))), k => k, StringComparer.Ordinal);
// The judge stops while the eighth repetition of the control runs, after at least five are recorded.
using var stop = new CancellationTokenSource();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), [], replicas, p.Data.Symbols[0], null, n =>
{
if (n == 8)
{
for (var i = 0; i < 600 && DoneControls(test, tournament.Id) < 5; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await lab.ProcessAsync(trials[0].Id, stop.Token).ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trials[1].Id, stop.Token)).ConfigureAwait(false);
Assert.IsGreaterThanOrEqualTo(5, DoneControls(test, tournament.Id));
// They were computed by another build.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournament_units SET fingerprint = @f WHERE tournament_id = @t AND kind = @k", _none,
("f", "altra|2|build"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
var after = new List<string>();
lab.EngineFor = (p, f, d) => new CountingEngine(new DailyTrialEngine(p, f, d), after, replicas, p.Data.Symbols[0], p.Data.From == plan.HoldoutFrom ? "holdout" : null);
await lab.JudgeTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
var controls = after.Where(c => c.StartsWith("control", StringComparison.Ordinal)).ToList();
Assert.HasCount(2 * plan.Control.Repetitions, controls, "Every repetition runs again.");
Assert.HasCount(2 * plan.Control.Repetitions, controls.Distinct().ToList());
Assert.HasCount(2 * 2, after.Where(c => c.StartsWith("holdout", StringComparison.Ordinal)).ToList());
var fingerprints = await test.Db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT fingerprint FROM tournament_units WHERE tournament_id = @t AND kind = @k",
r => r.Text("fingerprint"), ("t", tournament.Id), ("k", "control")), _none).ConfigureAwait(false);
Assert.HasCount(2, fingerprints, "One fingerprint for the search data of each finalist.");
Assert.IsTrue(fingerprints.All(f => f.EndsWith(TrialUnitStore.Build, StringComparison.Ordinal)));
}
/// <summary>
/// The plan of a tournament that no longer reads (changed by hand, or after an update that cannot read it) fails the
/// tournament with a reason in Italian, when its last contender finishes and when it is found being judged at a start; the
/// laboratory goes on with the rest of the queue.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnUnreadableTournamentPlanFailsTheTournamentAndTheQueueGoesOn()
{
const string Unreadable = "Il piano registrato del campionato non si può più leggere: il campionato non si giudica.";
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var broken = await lab.PlanTournamentAsync(request with { Name = "Illeggibile" }, _none).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET plan = @p WHERE id = @id", _none, ("p", new DbJson("[1]")), ("id", broken.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, broken.Id).ConfigureAwait(false);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
// Found being judged at a start: it fails again, and the trials of the queue run and are judged.
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE tournaments SET status = @j, error = NULL, finished_at = NULL WHERE id = @id", _none,
("j", TournamentStatuses.Judging), ("id", broken.Id)), _none).ConfigureAwait(false);
var good = await lab.PlanTournamentAsync(request, _none).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!.IsFinished && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var judged = (await lab.Tournaments.GetAsync(good.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, judged.Status, judged.Error);
Assert.AreEqual((TournamentStatuses.Failed, Unreadable), await StateAsync(test, broken.Id).ConfigureAwait(false));
}
/// <summary>
/// The database refuses every change of the tournament while its last contender finishes, so neither the judge nor the
/// record of its failure can write: the queue goes on, and the trial that comes back to it after the pause brings the
/// tournament to its judge, though the trial itself is finished.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ARequeuedFinishedContenderStillReachesTheJudge()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false);
await RefuseTournamentChangesAsync(test, true).ConfigureAwait(false);
using var run = new CancellationTokenSource();
var running = lab.RunAsync(run.Token);
for (var i = 0; i < 1200 && clock.Waiting == 0 && !running.IsCompleted; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
Assert.IsFalse(running.IsCompleted, running.Exception?.ToString() ?? "The laboratory stopped.");
Assert.AreEqual(1, clock.Waiting, "The queue waits before trying again.");
Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(trials[1].Id, _none).ConfigureAwait(false))!.Status);
Assert.AreEqual(TournamentStatuses.Running, (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.Status);
// The database is back: after the pause the finished trial comes back to the queue and the tournament is judged.
await RefuseTournamentChangesAsync(test, false).ConfigureAwait(false);
clock.Advance(Laboratory.RetryDelay);
for (var i = 0; i < 1200 && !(await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!.IsFinished; i++)
{
await Task.Delay(50).ConfigureAwait(false);
}
await run.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Done, done.Status, done.Error);
}
/// <summary>
/// The judge checks that every contender trial is the one the plan of the tournament wrote: a trial plan changed by hand
/// (its hash no longer matches) or rewritten with its hash on another capital, grid, slippage, source or reference share
/// fails the tournament.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AContenderTrialWhosePlanChangedFailsTheTournament()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = Lab(test, clock, Small());
var request = SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid));
var tampered = await lab.PlanTournamentAsync(request with { Name = "Impronta" }, _none).ConfigureAwait(false);
var last = (await lab.Trials.OfTournamentAsync(tampered.Id, _none).ConfigureAwait(false))[1];
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", _none, ("h", "0"), ("id", last.Id)), _none)
.ConfigureAwait(false);
await RunAllAsync(lab, tampered.Id).ConfigureAwait(false);
var refused = (await lab.Tournaments.GetAsync(tampered.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, refused.Status);
Assert.AreEqual("Il piano registrato della prova di «b» non corrisponde più alla sua impronta: il campionato non si giudica.", refused.Error);
(string Name, Func<TrialPlan, TrialPlan> Change)[] changes =
[
("Capitale", p => p with { InitialCapital = 20_000m }),
("Griglia", p => p with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["entry"] = [1m], ["lookback"] = [30m] } }),
("Slittamento", p => p with { Slippage = new SlippageTable(9m, 9m, 25m) }),
("Origine", p => p with { Data = p.Data with { Source = TrialSources.Research } }),
("Quota", p => p with { ReferenceShare = 0.5m }),
];
foreach (var (name, change) in changes)
{
var tournament = await lab.PlanTournamentAsync(request with { Name = name }, _none).ConfigureAwait(false);
var trial = (await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false))[1];
var json = change(trial.Plan).ToJson();
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan = @p, plan_hash = @h WHERE id = @id", _none,
("p", new DbJson(json)), ("h", TrialPlan.Hash(json)), ("id", trial.Id)), _none).ConfigureAwait(false);
Assert.IsTrue((await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.PlanIntact, name);
await RunAllAsync(lab, tournament.Id).ConfigureAwait(false);
var failed = (await lab.Tournaments.GetAsync(tournament.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TournamentStatuses.Failed, failed.Status, name);
Assert.AreEqual("Le prove del campionato non corrispondono al suo piano.", failed.Error, name);
}
}
/// <summary>
/// The control compares the replicas with the Sharpe ratio of the contender's own trial: when its search data change
/// between that trial and the judge, the tournament fails instead of mixing the two.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SearchDataThatChangedAfterTheTrialFailTheTournament()
{
var clock = new ManualClock(Now);
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var field = Small();
using var lab = Lab(test, clock, field);
var tournament = await lab.PlanTournamentAsync(SmallRequest(("a", "g1", "m1", ["EAA-EUR"], OneGrid), ("b", "g2", "m1", ["NAA-EUR"], OneGrid)), _none)
.ConfigureAwait(false);
var trials = await lab.Trials.OfTournamentAsync(tournament.Id, _none).ConfigureAwait(false);
await lab.ProcessAsync(trials[0].Id, _none).ConfigureAwait(false);
// One bar of the search tract of «a» is corrected after its trial.
var bars = Synthetic.Bars(Synthetic.MeanRevertingReturns(1099, 11, halfLife: 2, volatility: 0.02), 11).ToList();
bars[500] = bars[500] with { Close = bars[500].Close * 1.01, High = Math.Max(bars[500].High, bars[500].Close * 1.01) };
field.Add("EAA-EUR", bars);
await lab.ProcessAsync(trials[1].Id, _none).ConfigureAwait(false);
var (status, error) = await StateAsync(test, tournament.Id).ConfigureAwait(false);
Assert.AreEqual(TournamentStatuses.Failed, status);
Assert.AreEqual("I dati di ricerca di «a» sono cambiati dopo la sua prova: il campionato non si giudica.", error);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFinalistsAreTheBestOfEachGroupAndMarketAndAtMostEight()
{
var golden = BacktestReport.FromJson(Fixture.Text(Path.Combine("golden", "sma_cross.report.json")));
var trialPlan = Laboratory.BuildPlan(LaboratoryTests.Request(), Now).Plan;
var contenders = new List<TournamentContender>();
var outcomes = new List<ContenderOutcome>();
void Add(string label, string group, string market, double? walkForward, string status = TrialStatuses.Done)
{
var contender = new TournamentContender(label, "sma_cross", "1", group, market, trialPlan.Grid, trialPlan.Data, 4);
contenders.Add(contender);
var trial = new Trial(Guid.NewGuid(), "sma_cross", "1", trialPlan, "h", 4, status, null, null, null, null, Now, Now, Now);
var report = status != TrialStatuses.Done ? null
: golden with { WalkForward = walkForward is { } s ? new ReportWalkForward([], 0, 0, s) : null };
outcomes.Add(new ContenderOutcome(contender, trial, report, []));
}
Add("a", "trend", "crypto", 0.5);
Add("b", "trend", "crypto", 0.9);
Add("c", "trend", "fx", 0.1);
Add("d", "reversion", "crypto", 0.9);
Add("e", "reversion", "crypto", 0.9);
Add("f", "momentum", "crypto", 2.0, TrialStatuses.Failed);
Add("g", "momentum", "crypto", null);
Add("h", "momentum", "fx", double.NaN);
Add("i", "g1", "m", 0.01);
Add("j", "g2", "m", 0.02);
Add("k", "g3", "m", 0.03);
Add("l", "g4", "m", 0.04);
Add("m", "g5", "m", 0.05);
Add("n", "g6", "m", -0.5);
var plan = TournamentPlans.BuildPlan(new TournamentRequest("x", [new ContenderRequest("z", "sma_cross", "g", "m", TrialSources.Database, Venues.Okx, ["BTC-EUR"],
trialPlan.Data.From, trialPlan.Data.To)], trialPlan.Data.To.AddDays(-60), 10_000m), Now, 0, StrategyCatalog.Find).Plan with
{ Contenders = contenders };
// Best of each pair first, ties to the one written first; a failed trial, or one without walk-forward, never goes on.
CollectionAssert.AreEqual(new[] { "b", "d", "c", "m", "l", "k", "j", "i" }, TournamentJudge.Finalists(plan, outcomes).ToArray());
CollectionAssert.AreEqual(new[] { "b", "d", "c" }, TournamentJudge.Finalists(plan with { Finalists = plan.Finalists with { Max = 3 } }, outcomes).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AControlUnitKeepsOnlyItsSharpeAndItsKeyNamesTheRepetition()
{
var parameters = ReversionFamily.With(20, 1.5m).ToString();
var control = new TrialUnitKey(TrialUnitKind.Control, 7, parameters, 1m);
var holdout = new TrialUnitKey(TrialUnitKind.Holdout, 0, parameters, 2m);
Assert.AreEqual("control:7:entry=1.5;lookback=20:x1", control.Text);
Assert.AreEqual("holdout:0:entry=1.5;lookback=20:x2", holdout.Text);
foreach (var sharpe in new[] { -0.0123456789012345, 0.0, 0.1 + 0.2, double.Epsilon })
{
var back = TrialUnitOutcomes.Decode(control, TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null) { Sharpe = sharpe }));
Assert.AreEqual(sharpe, back.Sharpe);
Assert.IsNull(back.Run);
Assert.IsNull(back.LookAhead);
}
Assert.ThrowsExactly<InvalidOperationException>(() => TrialUnitOutcomes.Encode(new TrialUnitResult(control, null, null)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportOfATournamentRoundTrips()
{
var checks = new List<ReportCheck>
{
new(ReportCheckKeys.DeflatedSharpe, "Deflated Sharpe Ratio sul numero comune di prove", 0.93, "≥", 0.9, "ratio", true),
new(TournamentCheckKeys.Control, "Controllo contro il caso: quota di copie pari o migliori", null, "≤", 0.05, "ratio", false),
};
var report = new TournamentReport(
Guid.Parse("01938a6e-0000-7000-8000-000000000001"),
"Campionato",
"abc",
new TournamentTrialsCount(40, 48, 3, 27, 118),
2.6,
0.123456789,
new ReportOverfitting(16, 12870, 40, 0.1),
4.5,
[
new TournamentContenderResult("a", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Done, 2, "entry=1;lookback=20", 0.1, true),
new TournamentContenderResult("b", ReversionFamily.FamilyId, "g", "m", Guid.Empty, TrialStatuses.Failed, 9, null, null, false) { Error = "Strumento sconosciuto" },
],
[
new TournamentFinalistResult("a", ReversionFamily.FamilyId, "g", "m", "entry=1;lookback=20", 365, 0.2,
new DeflatedSharpe(0.2, 0.1, 1500, 0.8, 5.5, 118, 0.0027, 0.93), new ReportInterval(double.NegativeInfinity, double.PositiveInfinity), 1234.5678m, 0.12, true,
new TournamentControlResult(200, 7, true, 0.2, null, null, null) { Unavailable = Surrogates.CorporateActionsRefused },
new TournamentHoldoutResult(new DateOnly(2024, 1, 1), new DateOnly(2024, 12, 31), 100.10m, 90.05m, 0.01, 0.05, 0.02), checks, false),
],
0,
false,
["Una limitazione."],
Now,
1.5);
var json = report.ToJson();
Assert.AreEqual(json, TournamentReport.FromJson(json).ToJson());
foreach (var name in new[] { "\"passed_count\":", "\"field_variance\":", "\"effective_bets\":", "\"sharpe_interval\":", "\"net_at_double_costs\":", "\"unavailable\":", "\"walk_forward_sharpe\":" })
{
StringAssert.Contains(json, name);
}
StringAssert.Contains(json, "\"low\":\"-Infinity\"");
Assert.AreEqual(1234.5678m, TournamentReport.FromJson(json).Finalists[0].NetAtDoubleCosts);
}
/// <summary>The figures a resumed judge must give again: everything but the identities and the seconds.</summary>
private static string Comparable(TournamentReport report) =>
(report with { TournamentId = Guid.Empty, Seconds = 0, Contenders = [.. report.Contenders.Select(c => c with { TrialId = Guid.Empty })] }).ToJson();
private static string Describe(TournamentReport report) => string.Join(" | ", report.Finalists.Select(f => FormattableString.Invariant(
$"{f.Label}: S={f.Sharpe:F4} dsr={f.DeflatedSharpe.Value:F3} sr0={f.DeflatedSharpe.Benchmark:F4} share={f.Control.Share} net2={f.NetAtDoubleCosts:F0} dd={f.MaxDrawdown:F3} hold2={f.Holdout.NetAtDoubleCosts:F0} [{f.SharpeInterval.Low:F3},{f.SharpeInterval.High:F3}] failed:{string.Join(",", f.Checks.Where(c => c.Passed != true).Select(c => c.Key))}")))
+ FormattableString.Invariant($" | pbo={report.Overfitting?.Probability} var={report.FieldVariance:F4} bets={report.EffectiveBets:F2}");
/// <summary>A short field: 1100 days a series, a final tract of 100 days.</summary>
private static SyntheticField Small()
{
var field = new SyntheticField();
field.Add("EAA-EUR", Synthetic.Bars(Synthetic.MeanRevertingReturns(1099, 11, halfLife: 2, volatility: 0.02), 11));
field.Add("NAA-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 12, volatility: 0.02), 12));
field.Add("NAB-EUR", Synthetic.Bars(Synthetic.WalkReturns(1099, 13, volatility: 0.02), 13));
return field;
}
private static TournamentRequest SmallRequest(params (string Label, string Group, string Market, string[] Symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> Grid)[] contenders)
{
var to = Synthetic.Start.AddDays(1099);
return new TournamentRequest("Campionato di prova", [.. contenders.Select(c => Contender(c.Label, c.Group, c.Market, c.Symbols, c.Grid, to))], to.AddDays(-99), 10_000m)
{
Control = new TournamentControl(20, 20_261_204),
};
}
private static ContenderRequest Contender(string label, string group, string market, string[] symbols, IReadOnlyDictionary<string, IReadOnlyList<decimal>> grid, DateOnly to) =>
new(label, ReversionFamily.FamilyId, group, market, TrialSources.Database, Venues.Okx, symbols, SearchFrom, to, grid);
private static Laboratory Lab(TestDb test, IClock clock, SyntheticField field, int workers = 1) =>
new(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers))
{
Families = id => id == ReversionFamily.FamilyId ? ReversionFamily.Instance : StrategyCatalog.Find(id),
DataFor = field.LoadAsync,
};
/// <summary>Runs the trials of a tournament in the order of its plan: the last one brings it to its judge.</summary>
private static async Task RunAllAsync(Laboratory lab, Guid tournament)
{
foreach (var trial in await lab.Trials.OfTournamentAsync(tournament, _none).ConfigureAwait(false))
{
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
}
}
private static async Task<int> CountAsync(TestDb test, string table) =>
(int)await test.Db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT COUNT(*) AS n FROM {table}", r => r.Number("n")), _none).ConfigureAwait(false);
private static int DoneControls(TestDb test, Guid tournament) =>
(int)test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT COUNT(*) AS n FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d", r => r.Number("n"),
("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).GetAwaiter().GetResult();
private static async Task<IReadOnlyList<(Guid Trial, string Key)>> DoneControlsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT trial_id, unit_key FROM tournament_units WHERE tournament_id = @t AND kind = @k AND status = @d",
r => (r.Id("trial_id"), r.Text("unit_key")), ("t", tournament), ("k", "control"), ("d", TrialUnitStatuses.Done)), _none).ConfigureAwait(false);
private static async Task<IReadOnlyList<TrialUnitRow>> AllUnitsAsync(TestDb test, Guid tournament) =>
await test.Db.ReadAsync(s => s.QueryAsync("SELECT unit_key, kind, status, outcome, seconds, tournament_id FROM tournament_units WHERE tournament_id = @t ORDER BY id",
r => new TrialUnitRow(r.Text("unit_key"), r.Text("kind"), r.Text("status"), !r.IsNull("outcome"), r.IsNull("seconds") ? null : r.Measure("seconds"), r.IdOrNull("tournament_id")),
("t", tournament)), _none).ConfigureAwait(false);
/// <summary>State and error of a tournament, read without its plan.</summary>
private static Task<(string Status, string? Error)> StateAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT status, error FROM tournaments WHERE id = @id", r => (r.Text("status"), r.TextOrNull("error")), ("id", id)));
/// <summary>Makes the database refuse, or accept again, every change of a row of the tournaments: a trigger on both engines.</summary>
private static Task RefuseTournamentChangesAsync(TestDb test, bool refuse) => test.Db.WriteAsync(async s =>
{
string[] statements = (test.Db.Engine, refuse) switch
{
(DbEngine.Sqlite, true) => ["CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments BEGIN SELECT RAISE(ABORT, 'database non raggiungibile'); END"],
(DbEngine.Sqlite, false) => ["DROP TRIGGER refuse_tournaments"],
(_, true) =>
[
"CREATE FUNCTION refuse_tournaments() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'database non raggiungibile'; END $$",
"CREATE TRIGGER refuse_tournaments BEFORE UPDATE ON tournaments FOR EACH ROW EXECUTE FUNCTION refuse_tournaments()",
],
(_, false) => ["DROP TRIGGER refuse_tournaments ON tournaments", "DROP FUNCTION refuse_tournaments()"],
};
foreach (var sql in statements)
{
await s.ExecuteAsync(sql, _none).ConfigureAwait(false);
}
}, _none);
private static Task<(string Plan, string Hash)> RawPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM tournaments WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
private static Task<(string Plan, string Hash)> RawTrialPlanAsync(TestDb test, Guid id) =>
test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT plan, plan_hash FROM backtest_trials WHERE id = @id", r => (r.Json("plan").Text, r.Text("plan_hash")), ("id", id)));
/// <summary>The signs of a surrogate as text, to tell which repetition an engine was given.</summary>
private static string SignsOf(DaySigns signs) =>
string.Concat(Enumerable.Range(0, Math.Min(signs.Count, 256)).Select(i => signs[signs.First.AddDays(i)] > 0 ? '+' : '-'));
/// <summary>Synthetic series by symbol, read as the laboratory reads data (from the warm-up to the last day asked), with every read recorded.</summary>
private sealed class SyntheticField
{
private readonly Dictionary<string, IReadOnlyList<DailyBar>> _bars = new(StringComparer.Ordinal);
private readonly List<TrialData> _reads = [];
public IReadOnlyList<TrialData> Reads
{
get
{
lock (_reads)
{
return [.. _reads];
}
}
}
public void Add(string symbol, IReadOnlyList<DailyBar> bars) => _bars[symbol] = bars;
public Task<BacktestDataset> LoadAsync(TrialData data, CancellationToken cancellationToken)
{
lock (_reads)
{
_reads.Add(data);
}
var from = data.HistoryStart();
var instruments = data.Symbols.Select(s => new BacktestInstrument(Synthetic.Coin(s),
[.. (_bars.GetValueOrDefault(s) ?? throw new InvalidOperationException("Strumento sconosciuto: " + s)).Where(b => b.Day >= from && b.Day <= data.To)],
source: "sintetico"));
return Task.FromResult(new BacktestDataset(instruments, "EUR"));
}
}
/// <summary>An engine in between: it records the runs on surrogates (with the repetition their signs belong to) and on the final tract.</summary>
private sealed class CountingEngine(ITrialEngine inner, List<string> calls, IReadOnlyDictionary<string, int> replicas, string name, string? tag, Action<int>? onControl = null) : ITrialEngine
{
private readonly Counter _controls = new();
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public bool LongOnly => inner.LongOnly;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
if (tag is not null)
{
Record(FormattableString.Invariant($"{tag} x{costMultiplier}"));
}
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark() => inner.Benchmark();
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => inner.LookAhead(parameters, cuts);
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
public ITrialEngine Surrogate(DaySigns signs, bool centred)
{
var surrogate = inner.Surrogate(signs, centred);
return replicas.TryGetValue(SignsOf(signs), out var k)
? new CountingEngine(surrogate, calls, replicas, name, FormattableString.Invariant($"control {name} {k}"), onControl) { Parent = this }
: surrogate;
}
private CountingEngine? Parent { get; init; }
private void Record(string call)
{
lock (calls)
{
calls.Add(call.Split(' ')[0] == "control" ? call.Split(" x")[0] : call);
}
if (call.StartsWith("control", StringComparison.Ordinal))
{
onControl?.Invoke((Parent ?? this)._controls.Next());
}
}
}
private sealed class Counter
{
private int _value;
public int Next() => Interlocked.Increment(ref _value);
}
}
+477
View File
@@ -0,0 +1,477 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The units of a trial and the pool of the laboratory (Phase 13, issue #122): the judge works on runs already done, assembled
/// by key, so one thread, four threads and units read back from the database give the same report as the golden ones; a trial
/// stopped halfway runs again only what it had not finished.
/// </summary>
[TestClass]
public sealed class TrialUnitTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12");
private static readonly DateOnly Through = new(2026, 12, 31);
private static readonly TrialUnitKey RunKey = new(TrialUnitKind.Variant, 0, "", 1m);
private static readonly TrialUnitKey LookKey = new(TrialUnitKind.LookAhead, 0, "", 1m);
private sealed record Golden(string Name, TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data, PriorTrials Prior)
{
public string Hash => TrialPlan.Hash(Plan.ToJson());
public DailyTrialEngine Engine() => new(Plan, Family, Data);
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task JudgeOfVariantsGivesTheJsonOfRun()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task FourWorkersGiveTheReportOfOne()
{
using var pool = new LowPriorityPool("anubis-test-four", 4);
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = await TrialRunner.VariantsAsync(golden.Plan, golden.Family, engine, new PooledTrialUnits(pool), null, _none).ConfigureAwait(false);
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, runs, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public async Task ARunReloadedFromItsStoredUnitGivesTheSameReport()
{
foreach (var golden in await GoldensAsync().ConfigureAwait(false))
{
var engine = golden.Engine();
var runs = TrialRunner.Variants(golden.Plan, golden.Family, engine);
var reloaded = new TrialRuns(
runs.Variants,
[.. runs.Grid.Select(Again)],
runs.OutsideGrid is null ? null : Again(runs.OutsideGrid),
runs.Costed.ToDictionary(c => c.Key, c => Again(c.Value)),
Again(runs.Benchmark),
TrialUnitOutcomes.Decode(LookKey, TrialUnitOutcomes.Encode(new TrialUnitResult(LookKey, null, runs.LookAhead))).LookAhead!);
Assert.IsTrue(reloaded.Grid.All(r => r.Decisions.Count == 0), "The decisions are not kept: only the look-ahead check reads them.");
Same(golden.Name, TrialRunner.Judge(Id, golden.Plan, golden.Hash, golden.Family, engine, reloaded, golden.Prior, Now, TimeSpan.Zero).Report);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AStoredUnitIsTheSameBytesWhenWrittenAgain()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: Through.AddDays(-399)));
var run = BacktestEngine.Run(new MovingAverageCross(5, 20), data);
var stored = TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null));
var back = TrialUnitOutcomes.Decode(RunKey, stored).Run!;
CollectionAssert.AreEqual(stored, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, back, null)));
Assert.AreEqual(run.Fees, back.Fees);
Assert.AreEqual(run.FinalEquity, back.FinalEquity);
CollectionAssert.AreEqual(run.Fills.ToList(), back.Fills.ToList());
CollectionAssert.AreEqual(run.Trades.ToList(), back.Trades.ToList());
CollectionAssert.AreEqual(run.Notes.ToList(), back.Notes.ToList());
Assert.IsTrue(stored.Length < 200_000, "The outcome is compressed.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheKeyOfAUnitIsTheSameTextInEveryCulture()
{
var before = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
Assert.AreEqual("variant:3:a=1;kind=0:x1", new TrialUnitKey(TrialUnitKind.Variant, 3, "a=1;kind=0", 1m).Text);
Assert.AreEqual("costed:0:a=1;kind=0:x2", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1;kind=0", 2.00m).Text);
Assert.AreEqual("costed:0:a=1:x1.5", new TrialUnitKey(TrialUnitKind.Costed, 0, "a=1", 1.50m).Text);
Assert.AreEqual("outside_grid:0:a=4;kind=1:x1", new TrialUnitKey(TrialUnitKind.OutsideGrid, 0, "a=4;kind=1", 1m).Text);
Assert.AreEqual("benchmark:0::x1", new TrialUnitKey(TrialUnitKind.Benchmark, 0, "", 1m).Text);
Assert.AreEqual("look_ahead", new TrialUnitKey(TrialUnitKind.LookAhead, 0, "a=1", 1m).KindText);
}
finally
{
CultureInfo.CurrentCulture = before;
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OnOneWorkerThePoolCallsTheEngineInTheOrderOfToday()
{
var (plan, family, data) = SmallCross();
var inline = new List<string>();
var sequential = TrialRunner.Variants(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), inline));
using var pool = new LowPriorityPool("anubis-test-one", 1);
var pooled = new List<string>();
var parallel = await TrialRunner.VariantsAsync(plan, family, new RecordingEngine(new DailyTrialEngine(plan, family, data), pooled), new PooledTrialUnits(pool),
null, _none).ConfigureAwait(false);
Assert.HasCount(4 + 2 + 2, inline);
CollectionAssert.AreEqual(inline, pooled);
StringAssert.StartsWith(inline[^1], "look_ahead ");
Assert.AreEqual("benchmark", inline[^2]);
var inlineUnits = await TrialRunner.VariantsAsync(plan, family, new DailyTrialEngine(plan, family, data), InlineTrialUnits.Instance, null, _none).ConfigureAwait(false);
var hash = TrialPlan.Hash(plan.ToJson());
var one = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), sequential, PriorTrials.None, Now, TimeSpan.Zero).Report;
foreach (var other in new[] { parallel, inlineUnits })
{
var report = TrialRunner.Judge(Id, plan, hash, family, new DailyTrialEngine(plan, family, data), other, PriorTrials.None, Now, TimeSpan.Zero).Report;
Assert.AreEqual((one with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AUnitThatFailsStopsTheOnesNotYetStartedAndItsErrorComesBack()
{
var (plan, family, data) = SmallCross();
using var pool = new LowPriorityPool("anubis-test-fail", 1);
var calls = new List<string>();
var engine = new RecordingEngine(new DailyTrialEngine(plan, family, data), calls, _ => throw new InvalidOperationException("rotto"));
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => TrialRunner.VariantsAsync(plan, family, engine, new PooledTrialUnits(pool), null, _none))
.ConfigureAwait(false);
Assert.AreEqual("rotto", error.Message, "The error of the unit comes back, not the skip of the others.");
Assert.HasCount(1, calls, "After a failure the units still queued do not run.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ThePoolRunsOnNamedLowPriorityBackgroundThreadsAndFinishesWhatItWasGiven()
{
using var pool = new LowPriorityPool("anubis-test-pool", 2);
using var both = new Barrier(2);
(bool Together, string? Name, ThreadPriority Priority, bool Background) Probe() =>
(both.SignalAndWait(TimeSpan.FromSeconds(30)), Thread.CurrentThread.Name, Thread.CurrentThread.Priority, Thread.CurrentThread.IsBackground);
var seen = await Task.WhenAll(pool.RunAsync(Probe), pool.RunAsync(Probe)).ConfigureAwait(false);
Assert.AreEqual(2, pool.Workers);
Assert.IsTrue(seen.All(s => s.Together), "Two threads run two pieces of work at once.");
CollectionAssert.AreEquivalent(new[] { "anubis-test-pool-1", "anubis-test-pool-2" }, seen.Select(s => s.Name).ToArray());
Assert.IsTrue(seen.All(s => s.Priority == ThreadPriority.BelowNormal && s.Background));
await Assert.ThrowsAsync<ArithmeticException>(() => pool.RunAsync<int>(() => throw new ArithmeticException())).ConfigureAwait(false);
// Work handed over before the pool stops still runs; nothing more is taken; stopping twice is harmless.
using var release = new ManualResetEventSlim();
var slow = pool.RunAsync(() => release.Wait(TimeSpan.FromSeconds(30)));
var queued = pool.RunAsync(() => 7);
var stopping = Task.Run(pool.Dispose);
release.Set();
await stopping.ConfigureAwait(false);
Assert.IsTrue(await slow.ConfigureAwait(false));
Assert.AreEqual(7, await queued.ConfigureAwait(false));
Assert.Throws<InvalidOperationException>(() => pool.RunAsync(() => 1));
pool.Dispose();
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AfterAnInterruptionTheFinishedUnitsAreNotRunAgain()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
var workers = 1;
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath(), workers: _ => Task.FromResult(workers));
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
Assert.AreEqual(TrialStatuses.Running, (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!.Status);
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
var finished = rows.Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
var left = rows.Where(r => r.Status == TrialUnitStatuses.Running).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
Assert.IsNotEmpty(left, "The units claimed and not finished stay running.");
Assert.IsTrue(rows.All(r => r.Status != TrialUnitStatuses.Done || (r.HasOutcome && r.Seconds is >= 0)));
Assert.IsTrue(rows.All(r => r.TournamentId is null));
// The next start plans it again and runs only what was not finished, now on two threads.
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
workers = 2;
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total - finished.Count, second);
foreach (var key in finished)
{
CollectionAssert.DoesNotContain(second, CallOf(key), "A finished unit does not run again: " + key);
}
foreach (var key in left)
{
CollectionAssert.Contains(second, CallOf(key), "A unit left running runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
Assert.AreEqual(clock.UtcNow, report.ComputedAt);
// A trial outside a tournament keeps its units as a record, without their outcomes.
var after = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, after);
Assert.IsTrue(after.All(r => r.Status == TrialUnitStatuses.Done && !r.HasOutcome));
CollectionAssert.AreEquivalent(new[] { "variant", "costed", "benchmark", "look_ahead" }, after.Select(r => r.Kind).Distinct().ToArray());
Assert.AreEqual(4, report.TrialsCounted, "Units never count as trials.");
}
/// <summary>
/// A trial stopped halfway whose bars change before the next start (a bar collected again, a corporate action): the units
/// done on the old bars are not reused, every unit runs again on the new ones and the report is that of a run without a stop.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task UnitsComputedOnOtherDataAreRunAgainOnResume()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var btc = await LaboratoryTests.SeedBitcoinAsync(test, clock).ConfigureAwait(false);
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
var trial = await lab.PlanAsync(LaboratoryTests.Request(), _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(trial.Strategy)!;
var before = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
// The process stops while the third variant runs, after the first two are recorded.
using var stop = new CancellationTokenSource();
var first = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), first, n =>
{
if (n == 3)
{
for (var i = 0; i < 600 && lab.Units.ListAsync(trial.Id, _none).GetAwaiter().GetResult().Count(r => r.Status == TrialUnitStatuses.Done) < 2; i++)
{
Thread.Sleep(20);
}
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => lab.ProcessAsync(trial.Id, stop.Token)).ConfigureAwait(false);
var finished = (await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false)).Where(r => r.Status == TrialUnitStatuses.Done).Select(r => r.Key).ToList();
Assert.IsGreaterThanOrEqualTo(2, finished.Count);
// The bars are collected again with other prices before the next start.
await new BarStore(test.Db, clock).UpsertDailyAsync(btc.Id, BacktestData.Walk(400, 4, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)),
"test", _none).ConfigureAwait(false);
var data = await Laboratory.LoadAsync(test.Db, clock, Path.GetTempPath(), trial.Plan.Data, _none).ConfigureAwait(false);
Assert.AreNotEqual(before.Fingerprint(), data.Fingerprint());
var whole = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, family, data, PriorTrials.None, clock.UtcNow).Report;
CollectionAssert.Contains((await lab.Trials.ResumeAsync(_none).ConfigureAwait(false)).ToList(), trial.Id);
var second = new List<string>();
lab.EngineFor = (p, f, d) => new RecordingEngine(new DailyTrialEngine(p, f, d), second);
await lab.ProcessAsync(trial.Id, _none).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, _none).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
var total = 4 + 2 + 1 + 1;
Assert.HasCount(total, second, "Every unit runs again on the new bars.");
foreach (var key in finished)
{
CollectionAssert.Contains(second, CallOf(key), "A unit done on the old bars runs again: " + key);
}
var report = BacktestReport.FromJson((await lab.Trials.ReportJsonAsync(trial.Id, _none).ConfigureAwait(false))!);
Assert.AreEqual((whole with { Seconds = 0 }).ToJson(), (report with { Seconds = 0 }).ToJson());
// Every unit keeps what it was computed on: the new bars, the engine and this build.
var rows = await lab.Units.ListAsync(trial.Id, _none).ConfigureAwait(false);
Assert.HasCount(total, rows);
Assert.IsTrue(rows.All(r => r.Fingerprint == data.Fingerprint() + TrialUnitStore.Build), string.Join(", ", rows.Select(r => r.Fingerprint)));
StringAssert.StartsWith(TrialUnitStore.Build, "|" + BacktestEngine.Version + "|");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheWorkersOfTheLaboratoryAreAWholeNumberFromOneToOneLessThanTheProcessors()
{
var workers = LaboratorySettings.Workers;
Assert.AreEqual("laboratory.workers", workers.Key);
Assert.AreEqual("1", workers.Default);
Assert.AreEqual("Operai del Laboratorio", workers.Label);
Assert.AreSame(workers, SettingsStore.Definition(workers.Key));
var max = Math.Max(1, Environment.ProcessorCount - 1);
Assert.AreEqual(max, LaboratorySettings.MaxWorkers);
Assert.IsNull(workers.Check!("1"));
Assert.IsNull(workers.Check(max.ToString(CultureInfo.InvariantCulture)));
foreach (var wrong in new[] { "0", (max + 1).ToString(CultureInfo.InvariantCulture), "", "due", "1.5", "-1", "+2", " 2" })
{
Assert.AreEqual($"Serve un numero intero tra 1 e {max}.", workers.Check(wrong), wrong);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWorkersOfTheLaboratoryAreSetInTheSystemSettings()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Operai del Laboratorio");
StringAssert.Contains(page, "Quanti calcoli di una prova del Laboratorio girano insieme: le prove restano una alla volta.");
StringAssert.Contains(page, "il Laboratorio non deve togliere tempo al trading");
StringAssert.Contains(page, "Vale dalla prossima prova.");
async Task<string> Save(string value)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LaboratorySettings.Workers.Key, ("ritorno", "/impostazioni#sistema"), ("valore", value));
return ServerHarness.Location(answer);
}
var settings = server.Host.Services!.Settings;
Assert.AreEqual("/impostazioni#sistema", await Save("1"));
Assert.AreEqual(1, await LaboratorySettings.WorkersAsync(settings, _none));
StringAssert.Contains(await Save("0"), "errore=operai");
StringAssert.Contains(await Save((LaboratorySettings.MaxWorkers + 1).ToString(CultureInfo.InvariantCulture)), "errore=operai");
StringAssert.Contains(await Save("tanti"), "errore=operai");
Assert.AreEqual("1", (await settings.GetAsync(LaboratorySettings.Workers.Key, _none)).Value);
StringAssert.Contains(await server.TextAsync("/impostazioni?errore=operai#sistema"), "Gli operai del Laboratorio sono un numero intero da 1 a");
}
private static BacktestRun Again(BacktestRun run) => TrialUnitOutcomes.Decode(RunKey, TrialUnitOutcomes.Encode(new TrialUnitResult(RunKey, run, null))).Run!;
/// <summary>The call of the recording engine a unit key stands for.</summary>
private static string CallOf(string key)
{
var parts = key.Split(':');
return parts[0] switch
{
"benchmark" => "benchmark",
"look_ahead" => $"look_ahead {parts[2]} {TrialValidation.Default.LookAheadCuts}",
_ => $"run {parts[2]} {parts[3]}",
};
}
private static (TrialPlan Plan, IStrategyFamily Family, BacktestDataset Data) SmallCross()
{
var first = new DateOnly(2024, 1, 1);
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: first));
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
first.AddDays(60), first.AddDays(399), 10_000m, grid), Now).Plan;
return (plan, MovingAverageCrossFamily.Instance, data);
}
/// <summary>The inputs of the three golden reports of <see cref="TrialSeamTests"/>, built the same way.</summary>
private static async Task<IReadOnlyList<Golden>> GoldensAsync()
{
var walk = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03));
var cross = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan;
var folder = TempFolder.Create("golden-units");
try
{
var store = new ResearchStore(folder);
var seed = 21u;
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" })
{
var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
(decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList();
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false);
}
var trend = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow,
CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan;
var data = await Laboratory.LoadResearchAsync(folder, trend.Data, _none).ConfigureAwait(false);
var family = StrategyCatalog.Find(StrategyNames.CryptoTrend)!;
return
[
new("sma_cross", cross, MovingAverageCrossFamily.Instance, walk, new PriorTrials(2, 18, [0.4, 0.9, -0.1])),
new("crypto_trend", trend, family, data, PriorTrials.None),
new("crypto_trend_judged", trend with { Judged = "coin_vol=12;max_stop=15" }, family, data, PriorTrials.None),
];
}
finally
{
TempFolder.Delete(folder);
}
}
private static void Same(string name, BacktestReport report) =>
Assert.AreEqual(Fixture.Text(Path.Combine("golden", name + ".report.json")), (report with { Seconds = 0 }).ToJson(), $"The report of {name} changed.");
/// <summary>An engine in between: it records every call (safe from several threads) and may act on the n-th one.</summary>
private sealed class RecordingEngine(ITrialEngine inner, List<string> calls, Action<int>? onCall = null) : ITrialEngine
{
private int _count;
public string Currency => inner.Currency;
public int PeriodsPerYear => inner.PeriodsPerYear;
public int Sessions => inner.Sessions;
public string Fingerprint() => inner.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() => inner.Instruments();
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
Record(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
return inner.Run(parameters, costMultiplier);
}
public BacktestRun Benchmark()
{
Record("benchmark");
return inner.Benchmark();
}
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
Record(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
return inner.LookAhead(parameters, cuts);
}
public IReadOnlyList<string> Limitations() => inner.Limitations();
public TrialExpectations Expected(BacktestRun run, double[] returns) => inner.Expected(run, returns);
private void Record(string call)
{
lock (calls)
{
calls.Add(call);
}
onCall?.Invoke(Interlocked.Increment(ref _count));
}
}
}