Fase 8 — Apprendimento #109
No files matched your search
@@ -8,6 +8,7 @@ TestResults/
|
|||||||
docs/
|
docs/
|
||||||
!docs/design/logo/
|
!docs/design/logo/
|
||||||
!docs/backtests/*.outcome.json
|
!docs/backtests/*.outcome.json
|
||||||
|
!docs/learning/first-model.json
|
||||||
**/*.md
|
**/*.md
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
@@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh
|
|||||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||||
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
||||||
- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie, Apprendimento e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
||||||
- `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea.
|
- `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea.
|
||||||
- `desktop-win` (Fase 10): non ancora disponibile.
|
- `desktop-win` (Fase 10): non ancora disponibile.
|
||||||
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
|
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ COPY src/Anubis.Guard/ src/Anubis.Guard/
|
|||||||
COPY docs/design/logo/ docs/design/logo/
|
COPY docs/design/logo/ docs/design/logo/
|
||||||
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
|
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
|
||||||
COPY docs/backtests/ docs/backtests/
|
COPY docs/backtests/ docs/backtests/
|
||||||
|
COPY docs/learning/ docs/learning/
|
||||||
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
||||||
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
|
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
|
||||||
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
|
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
|
||||||
|
|||||||
+4
-4
@@ -233,7 +233,7 @@ Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già
|
|||||||
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
| `Npgsql` | 10.0.3 | PostgreSQL License | Fase 1 | https://www.nuget.org/packages/Npgsql/10.0.3 |
|
||||||
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 1 (la custodia della chiave dei segreti su desktop nasce con lo strato di piattaforma) | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
| `System.Security.Cryptography.ProtectedData` | 10.0.14 | MIT | Fase 1 (la custodia della chiave dei segreti su desktop nasce con lo strato di piattaforma) | https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/10.0.14 |
|
||||||
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
| `Microsoft.Web.WebView2` | 1.0.4314.35 | Licenza Microsoft di tipo BSD | Fase 10 | https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.4314.35 |
|
||||||
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Fase 8 | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
| `Microsoft.ML`, `Microsoft.ML.LightGbm`, `Microsoft.ML.FastTree` | 5.0.1 | MIT | Autorizzati ma non usati: i modelli sono scritti in casa (ADR 0018) | https://www.nuget.org/packages/Microsoft.ML/5.0.1 |
|
||||||
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
| `Microsoft.ML.OnnxRuntime` | 1.31.1 (librerie native per linux-x64 e win-x64) | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime/1.31.1 |
|
||||||
| `Microsoft.ML.Tokenizers` | 2.0.1 | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.Tokenizers/2.0.1 |
|
| `Microsoft.ML.Tokenizers` | 2.0.1 | MIT | Fase 7 | https://www.nuget.org/packages/Microsoft.ML.Tokenizers/2.0.1 |
|
||||||
|
|
||||||
@@ -264,15 +264,15 @@ Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del tes
|
|||||||
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core`, `SQLitePCLRaw.lib.e_sqlite3`, `SQLitePCLRaw.provider.e_sqlite3` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 (in uso) | Contengono la libreria nativa di SQLite e il suo caricatore. Sono nell'elenco del test dalla Fase 1. |
|
| `SQLitePCLRaw.bundle_e_sqlite3`, `SQLitePCLRaw.core`, `SQLitePCLRaw.lib.e_sqlite3`, `SQLitePCLRaw.provider.e_sqlite3` 2.1.13 | Eric Sink, Apache-2.0 | `Microsoft.Data.Sqlite` | 1 (in uso) | Contengono la libreria nativa di SQLite e il suo caricatore. Sono nell'elenco del test dalla Fase 1. |
|
||||||
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | 8 | — |
|
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | — | Non entra: Microsoft.ML non si usa (ADR 0018) |
|
||||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | — | Non entra: LightGBM non si usa (ADR 0018). |
|
||||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 (in uso) | Nell'elenco del test dalla Fase 7. |
|
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 (in uso) | Nell'elenco del test dalla Fase 7. |
|
||||||
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||||
|
|
||||||
## Immagini Docker
|
## Immagini Docker
|
||||||
|
|
||||||
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
- `mcr.microsoft.com/dotnet/sdk:10.0` (SDK 10.0.403) e `mcr.microsoft.com/dotnet/aspnet:10.0` (runtime 10.0.14) esistono. Dal .NET 10 il tag `10.0` usa **Ubuntu 24.04 "noble"**, non Debian. Non esiste un tag Debian stabile.
|
||||||
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Si aggiunge nella Fase 8, insieme a LightGBM.
|
- `libgomp1` non è nelle immagini, ma si installa da Ubuntu "main" con `apt-get install -y --no-install-recommends libgomp1`. Non serve: LightGBM non si usa (ADR 0018).
|
||||||
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
- Fonti: https://mcr.microsoft.com/v2/dotnet/aspnet/tags/list · https://github.com/dotnet/dotnet-docker/blob/main/manifest.json · https://packages.ubuntu.com/noble/libgomp1
|
||||||
|
|
||||||
## Carattere
|
## Carattere
|
||||||
|
|||||||
+11
-11
@@ -239,20 +239,20 @@ Un modello che impara dall'esito dei segnali e può solo rimpicciolire le operaz
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#62](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/62) Archivio degli indizi "a una certa data" ed etichette
|
- [x] [#62](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/62) Archivio degli indizi "a una certa data" ed etichette
|
||||||
- [ ] [#63](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/63) Addestramento, convalida, calibrazione e registro dei modelli
|
- [x] [#63](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/63) Addestramento, convalida, calibrazione e registro dei modelli
|
||||||
- [ ] [#64](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/64) Ciclo continuo: modello in carica e sfidante, ombra, deriva, messa da parte
|
- [x] [#64](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/64) Ciclo continuo: modello in carica e sfidante, ombra, deriva, messa da parte
|
||||||
- [ ] [#65](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/65) Altri apprendimenti semplici: scostamento, impatto delle notizie, scoperte in chiaro
|
- [x] [#65](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/65) Altri apprendimenti semplici: scostamento, impatto delle notizie, scoperte in chiaro
|
||||||
- [ ] [#66](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/66) Schermata Apprendimento; Impostazioni sul modello
|
- [x] [#66](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/66) Schermata Apprendimento; Impostazioni sul modello
|
||||||
- [ ] [#67](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/67) Chiusura della fase, revisione indipendente e tag `fase-8`
|
- [x] [#67](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/67) Chiusura della fase, revisione indipendente e tag `fase-8`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Un test dimostra che nessun indizio usa dati successivi alla decisione
|
- [x] Un test dimostra che nessun indizio usa dati successivi alla decisione (`NoClueUsesDataAfterTheDecision`, `NothingSavedOrDatedAfterTheDecisionIsRead`, `ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue`)
|
||||||
- [ ] Il primo modello è addestrato sugli esempi storici con rapporto di convalida
|
- [x] Il primo modello è addestrato sugli esempi storici con rapporto di convalida (`docs/learning/first-model.md`; `TheFirstModelIsTheOneOfItsExamples`, `TheFirstModelTakesChargeAtTheFirstStart`). Solo crypto: le strategie azionarie aspettano lo storico di Alpaca
|
||||||
- [ ] Il moltiplicatore non può superare 1 (test di proprietà)
|
- [x] Il moltiplicatore non può superare 1 (test di proprietà: `TheMultiplierNeverExceedsOne`, `TheFilterNeverMakesAnOrderBigger`)
|
||||||
- [ ] Promozione, scarto e messa da parte sono coperti da test con dati sintetici
|
- [x] Promozione, scarto e messa da parte sono coperti da test con dati sintetici (`AChallengerThatIsReallyBetterIsPromotedAtAThreshold`, `AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases`, `ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack`, `ARisingErrorSetsTheModelAside`, `CluesNeverStudiedSetTheModelAside`)
|
||||||
- [ ] La schermata Apprendimento corrisponde al mockup
|
- [x] La schermata Apprendimento corrisponde al mockup (`TheDemoShowsTheModelAsInTheMockup` e confronto a 1440 e 390 px con il mockup 06)
|
||||||
|
|
||||||
## Fase 9 — Rifinitura e consegna in Docker
|
## Fase 9 — Rifinitura e consegna in Docker
|
||||||
|
|
||||||
|
|||||||
+13
-4
@@ -4,7 +4,7 @@ Aggiornato: 2026-12-01
|
|||||||
|
|
||||||
## Fase corrente
|
## Fase corrente
|
||||||
|
|
||||||
**Fase 7 — Notizie: completata**, tranne un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prossima è la Fase 8 — Apprendimento. La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). 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 8 — Apprendimento: completata.** La prossima è la Fase 9 — Rifinitura e consegna in Docker. Della Fase 7 resta un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
|
||||||
|
|
||||||
## Fatto
|
## Fatto
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ Aggiornato: 2026-12-01
|
|||||||
- Convalide scritte in casa: finestre che avanzano, K-fold purgato combinatorio, Deflated Sharpe Ratio, PBO, regola dell'altopiano, test contro lo sguardo in avanti. DSR e PBO riproducono i casi noti.
|
- Convalide scritte in casa: finestre che avanzano, K-fold purgato combinatorio, Deflated Sharpe Ratio, PBO, regola dell'altopiano, test contro lo sguardo in avanti. DSR e PBO riproducono i casi noti.
|
||||||
- Registro delle prove: il piano (con le soglie) e la sua impronta si scrivono prima dei risultati e non cambiano; il numero di prove del DSR conta tutti i tentativi della stessa strategia.
|
- Registro delle prove: il piano (con le soglie) e la sua impronta si scrivono prima dei risultati e non cambiano; il numero di prove del DSR conta tutti i tentativi della stessa strategia.
|
||||||
- Laboratorio su un thread a priorità bassa, una prova alla volta, con ripresa dopo un riavvio; dati dalle barre raccolte o dallo storico di ricerca Binance.
|
- Laboratorio su un thread a priorità bassa, una prova alla volta, con ripresa dopo un riavvio; dati dalle barre raccolte o dallo storico di ricerca Binance.
|
||||||
- Schermata Laboratorio: elenco delle prove, modulo per un nuovo test, rapporto completo, confronto tra due prove. Le sezioni "Migliorie in osservazione" e "Stime di costo da confermare" aspettano le Fasi 9 e 8.
|
- Schermata Laboratorio: elenco delle prove, modulo per un nuovo test, rapporto completo, confronto tra due prove. La sezione "Migliorie in osservazione" aspetta la Fase 9; "Stime di costo da confermare" è arrivata con la Fase 8.
|
||||||
- Strategia d'esempio `sma_cross` (incrocio di medie) per provare il laboratorio; le strategie di base arrivano con la Fase 5.
|
- Strategia d'esempio `sma_cross` (incrocio di medie) per provare il laboratorio; le strategie di base arrivano con la Fase 5.
|
||||||
- **Fase 5** (scelte nell'ADR 0011):
|
- **Fase 5** (scelte nell'ADR 0011):
|
||||||
- Le tre strategie di base: `crypto_trend` (rottura su nove periodi, stop a metà del canale, pesi a volatilità obiettivo, universo dei primi dieci del mese), `equity_momentum` (revisione settimanale con il filtro di SPY, pesi a volatilità inversa, stop che segue il prezzo) e `equity_meanrev` (RSI a 2 sopra la media a 200 sedute, rischio fisso, uscita alla chiusura). Le stesse classi girano in prova e dal vivo e passano il test contro lo sguardo in avanti.
|
- Le tre strategie di base: `crypto_trend` (rottura su nove periodi, stop a metà del canale, pesi a volatilità obiettivo, universo dei primi dieci del mese), `equity_momentum` (revisione settimanale con il filtro di SPY, pesi a volatilità inversa, stop che segue il prezzo) e `equity_meanrev` (RSI a 2 sopra la media a 200 sedute, rischio fisso, uscita alla chiusura). Le stesse classi girano in prova e dal vivo e passano il test contro lo sguardo in avanti.
|
||||||
@@ -114,6 +114,14 @@ Aggiornato: 2026-12-01
|
|||||||
- Esercitazione della guardia: aspetta che la vendita sia partita (#100) e il motore della prova non esce mai dal computer (#102, ADR 0016).
|
- Esercitazione della guardia: aspetta che la vendita sia partita (#100) e il motore della prova non esce mai dal computer (#102, ADR 0016).
|
||||||
- Correzioni della revisione indipendente (#61, ADR 0017): risposte malformate del modello e tetto di spesa, giro delle notizie accanto alla coda dei lavori, nomi e parole chiave, storie di società diverse, inizio delle finestre, trimestrali, acquisti rimandati, confronto a un passo.
|
- Correzioni della revisione indipendente (#61, ADR 0017): risposte malformate del modello e tetto di spesa, giro delle notizie accanto alla coda dei lavori, nomi e parole chiave, storie di società diverse, inizio delle finestre, trimestrali, acquisti rimandati, confronto a un passo.
|
||||||
|
|
||||||
|
- **Fase 8** (scelte nell'ADR 0018, niente pacchetti nuovi: i modelli sono scritti in casa):
|
||||||
|
- Archivio degli esempi (#62): ogni intenzione d'ingresso, anche rifiutata o in osservazione, diventa un esempio con gli indizi visti in quel momento. L'esito è l'operazione simulata da sola con il motore del backtest.
|
||||||
|
- Addestramento e convalida (#63): regressione logistica, alberi potenziati e foresta, finestre che avanzano e combinazioni purgate, calibrazione, registro dei modelli. `anubis learning base` scrive il primo modello e il suo rapporto in `docs/learning/`; il modello viaggia nel programma e al primo avvio prende il posto in carica, in osservazione.
|
||||||
|
- Ciclo continuo (#64): stime in ombra, controllo ogni notte alle 03:00, messa da parte e rientro automatici, sfidante la domenica, promozione o scarto a soglie fisse, avvio solo con i criteri di 11.5. Il moltiplicatore sta tra 0 e 1 e vale per l'operazione dalla nascita alla chiusura.
|
||||||
|
- Altri apprendimenti (#65): scostamento misurato sulle esecuzioni, impatto delle notizie, scoperte dette a parole.
|
||||||
|
- Schermata Apprendimento come il mockup 06 e sezione del modello in Impostazioni (#66).
|
||||||
|
- Correzioni di due revisioni indipendenti (#67, ADR 0018 punti 17 e 18).
|
||||||
|
|
||||||
## In corso
|
## In corso
|
||||||
|
|
||||||
Nulla.
|
Nulla.
|
||||||
@@ -121,14 +129,14 @@ Nulla.
|
|||||||
## Prossimo passo
|
## Prossimo passo
|
||||||
|
|
||||||
1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55.
|
1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55.
|
||||||
2. La Fase 8 — Apprendimento, in una nuova sessione, sul branch `fase-8` da `main`.
|
2. La Fase 9 — Rifinitura e consegna in Docker, in una nuova sessione, sul branch `fase-9` da `main`.
|
||||||
3. 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.
|
3. 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.
|
||||||
|
|
||||||
## Da sapere
|
## Da sapere
|
||||||
|
|
||||||
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
||||||
- La prova nel container `anubis-prova` è chiusa (ADR 0013). I compiti programmati che la sorvegliavano sono spenti; il container si può fermare con `docker stop anubis-prova`.
|
- La prova nel container `anubis-prova` è chiusa (ADR 0013). I compiti programmati che la sorvegliavano sono spenti; il container si può fermare con `docker stop anubis-prova`.
|
||||||
- La modalità dimostrativa mostra le schermate costruite fin qui. Le notizie fuori dalla demo si vedono dalla Fase 7; l'apprendimento appare solo con i dati dell'appendice F e arriva con la Fase 8. Nella demo il motore di trading e Telegram sono spenti.
|
- La modalità dimostrativa mostra le schermate costruite fin qui. Le notizie fuori dalla demo si vedono dalla Fase 7, l'apprendimento dalla Fase 8. Nella demo il motore di trading e Telegram sono spenti.
|
||||||
- In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo.
|
- In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo.
|
||||||
- La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4).
|
- La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4).
|
||||||
- Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata.
|
- Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata.
|
||||||
@@ -140,6 +148,7 @@ Nulla.
|
|||||||
- `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti.
|
- `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti.
|
||||||
- Il motore dal vivo fa girare ogni strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati.
|
- Il motore dal vivo fa girare ogni strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati.
|
||||||
- Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati).
|
- Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati).
|
||||||
|
- Il primo modello è appena migliore di chi risponde sempre la frequenza di base (errore più basso dello 0,2% e dell'1,1% nelle due prove) e ha studiato solo `crypto_trend`, che è in osservazione. Non cambia nessuna operazione finché non passa i criteri di 11.5. Per rifarlo: `anubis learning base --to AAAA-MM-GG --data-dir … --out docs/learning`, con percorsi assoluti.
|
||||||
- Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove.
|
- Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove.
|
||||||
- I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti.
|
- I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti.
|
||||||
- Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2).
|
- Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2).
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# 0018 — Scelte della Fase 8 (apprendimento)
|
||||||
|
|
||||||
|
Data: 2026-12-01 · Stato: accettata · Precisa gli ADR 0003 (riga Apprendimento) e 0004 (tabella dei componenti) e SPEC 5.4, 11 e 13.6
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
La Fase 8 costruisce il modulo che stima quanto è probabile che un segnale vada bene (SPEC 11). L'ADR 0003 prevedeva ML.NET con LightGBM. Il 18/11/2026 l'utente ha dato una regola più stretta per tutti i progetti: niente componenti esterni, tutto il codice in casa.
|
||||||
|
|
||||||
|
## Decisione
|
||||||
|
|
||||||
|
**1. I modelli sono scritti in casa.** `Microsoft.ML`, `Microsoft.ML.LightGbm` e `Microsoft.ML.FastTree` sono autorizzati ma non si usano: non entra nessun pacchetto nuovo, nessuna libreria nativa e `libgomp1` non serve. Al loro posto:
|
||||||
|
- regressione logistica regolarizzata (riferimento);
|
||||||
|
- alberi potenziati: pochi livelli, molti esempi per foglia, passo piccolo, regolarizzazione (principale, al posto di LightGBM);
|
||||||
|
- foresta casuale (sfidante, al posto del percettrone come già in ADR 0003), con lo stesso codice degli alberi;
|
||||||
|
- calibrazione di Platt e isotonica.
|
||||||
|
|
||||||
|
Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento dura meno di un secondo. Tutto è deterministico: stessi dati, stesso modello.
|
||||||
|
|
||||||
|
**2. Esempi.**
|
||||||
|
- Un esempio nasce dalla prima intenzione d'ingresso su uno strumento che la strategia non ha, anche se poi è rifiutata e anche in osservazione. Finché l'operazione simulata di quell'esempio è aperta, riproporre l'ingresso non ne crea un altro.
|
||||||
|
- L'esempio si scrive nella stessa transazione della decisione. Un guasto dell'apprendimento non ferma mai una decisione: la strategia prosegue come se il modello non ci fosse.
|
||||||
|
- `ml_features` contiene l'esempio con i suoi indizi, `ml_labels` l'esito (una volta sola), `ml_predictions` le stime. In più `ml_events` (la storia mostrata) e `ml_state`.
|
||||||
|
|
||||||
|
**3. Etichetta.** È l'operazione dell'esempio simulata da sola con il motore del backtest: si compra all'apertura dopo la decisione, sempre la stessa quota, si seguono le uscite e gli stop della strategia, senza aumenti, riduzioni né nuovi acquisti, con le commissioni e lo scostamento di sempre. Il risultato è una quota di quanto investito. Un'operazione che non può partire (sotto il minimo del mercato) resta senza esito e non addestra.
|
||||||
|
- `equity_momentum` ha bisogno di tutto l'universo, perché esce anche per la posizione in classifica; le altre guardano solo il proprio strumento.
|
||||||
|
|
||||||
|
**4. Indizi.** Tutti quelli di 11.2, calcolati con le sole barre fino alla decisione e con i valori esterni già datati **e già salvati** in quel momento.
|
||||||
|
- Si ricostruiscono dallo storico: strategia, forza, distanza dallo stop, volatilità e rapporto, volumi, regime, ampiezza, giorno della settimana.
|
||||||
|
- Restano fuori finché non ci sono 200 esempi dal vivo che li contengono: notizie, evento più grave, paura e avidità, VIX, finanziamento e open interest, giorni alla trimestrale. Paura e avidità e VIX hanno uno storico pubblico, ma non è tra i dati già scaricati: per ora seguono la stessa regola.
|
||||||
|
- L'open interest è il rapporto con la sua media di 30 giorni: il valore assoluto non vuol dire niente negli anni. Un valore esterno troppo vecchio (la fonte si è fermata) è mancante.
|
||||||
|
- La forza del segnale è della strategia e viaggia con l'intenzione (`Intent.Strength`); nessuna regola la legge.
|
||||||
|
|
||||||
|
**5. Addestramento e scelta.**
|
||||||
|
- Gli esempi vivono dalla decisione alla chiusura dell'operazione simulata. Due prove, sempre su esempi mai studiati: finestre che avanzano (5 pezzi) e combinazioni purgate (6 gruppi, 2 in verifica, 15 combinazioni). Un esempio che si sovrappone nel tempo a uno di verifica, o comincia nei 10 giorni dopo, non addestra.
|
||||||
|
- La calibrazione si adatta su stime di esempi non studiati (5 pezzi purgati): Platt sotto 1.000 casi, isotonica sopra; i gradini dell'isotonica hanno almeno 20 casi e nessuna stima va oltre 1 su 22 dai due estremi. Un punteggio che fuori campione non dice niente, o dice il contrario, diventa la frequenza di base.
|
||||||
|
- **Regola della scelta, fissata prima dei numeri**: vince il miglior guadagno medio per operazione proposta nelle combinazioni (al decimo di centesimo); a parità, il log-loss più basso; poi gli alberi potenziati. La foresta entra solo se batte gli altri su tutti e due.
|
||||||
|
- Il guadagno di un esempio è quota chiesta × risultato × capitale della strategia in euro. Se nessuna strategia con capitale ha esempi, si misura su tutte e il rapporto lo dice.
|
||||||
|
- Ogni tentativo è una riga di `ml_models`: il modello scelto con la sua versione, gli altri come `tried`.
|
||||||
|
- I pesi degli indizi vengono dal peggioramento delle stime, fuori campione, quando i valori di un gruppo di indizi si mescolano; su 100 con il metodo dei resti più alti.
|
||||||
|
- Meno di 100 esempi con esito: nessun modello.
|
||||||
|
|
||||||
|
**6. Moltiplicatore.** Come in 11.1, con le due soglie nelle Impostazioni (intero fino a 0 punti sotto la frequenza di base, zero da 10 punti sotto). Un numero non valido vale 1: un modello rotto non tocca le operazioni.
|
||||||
|
|
||||||
|
**7. Frequenza di base e primo modello.** `anubis learning base` ricostruisce gli esempi di `crypto_trend` sull'universo ampio del suo protocollo, con i parametri in uso, e scrive `docs/learning/first-model.json` (modello, rapporto, frequenze di base, esempi) e il rapporto leggibile. Il file viaggia nel programma come gli esiti dei backtest.
|
||||||
|
- Al primo avvio, se non ce n'è nessuno, diventa il modello in carica, in osservazione. Un file nuovo (revisione trimestrale) aggiorna frequenze di base ed esempi, non il modello: quello cambia solo con una promozione.
|
||||||
|
- Una strategia senza frequenza di base non viene stimata: moltiplicatore 1, nessuna stima, non conta tra i segnali valutati. Oggi vale per le due strategie sulle azioni, finché manca lo storico di Alpaca.
|
||||||
|
- **Esito onesto del primo modello**: 1.844 esempi crypto, 18,3% in guadagno. È scelta la regressione logistica. Le sue stime sono appena migliori di chi risponde sempre la frequenza di base (log-loss 0,4796 contro 0,4807 nelle combinazioni, 0,4735 contro 0,4788 in avanti); alberi e foresta fanno peggio. Il guadagno medio per operazione proposta passa da +1,69 a +1,76 euro nelle combinazioni e da +1,76 a +1,81 in avanti: differenze piccole, che possono essere caso. L'indizio che pesa di più è il giorno della settimana, e questo invita alla prudenza. Resta in osservazione come tutti i modelli; i criteri di 11.5 lo fermano se non impara altro.
|
||||||
|
|
||||||
|
**8. Il modello nelle decisioni.** È l'ultimo correttivo, prima del rischio: tocca ingressi e aumenti, mai uscite e riduzioni.
|
||||||
|
- Il moltiplicatore nasce con l'esempio e vale per l'operazione finché non si chiude, aumenti e riavvii compresi, anche se nel frattempo il modello cambia o viene messo da parte. La messa da parte vale quindi per le operazioni nuove.
|
||||||
|
- Su una posizione già rimpicciolita un aumento più piccolo del 20% della dimensione ridotta non si fa: sarebbe rincorrere gli arrotondamenti ogni giorno.
|
||||||
|
- Il modello stima solo le strategie che ha studiato.
|
||||||
|
- Un guasto del modello lascia le intenzioni com'erano e finisce nel registro tecnico. Il moltiplicatore di un'operazione già nata non si perde nemmeno se il resto dell'apprendimento non si legge.
|
||||||
|
- Finché il modello non conta, accanto a ogni operazione si scrive la stima e il moltiplicatore che avrebbe dato (riga `model` della decisione, stime in `ml_predictions`), sia del modello in carica sia dello sfidante.
|
||||||
|
|
||||||
|
**9. Controllo della notte** (03:00 di Roma; dopo un'assenza una volta sola, 5.6). Si guardano le stime che il modello in carica ha fatto per ogni esempio, quelle fatte da sfidante comprese.
|
||||||
|
- Precisione sugli ultimi 60 casi; conta da 40. Sotto il 50% il modello è messo da parte.
|
||||||
|
- ADWIN sull'errore quadratico (δ 0,002, finestra esatta, parti di almeno 10 casi), ricalcolato ogni notte da capo: nessuno stato da perdere. Un aumento vale come allarme per i 30 casi successivi; un calo lo chiude.
|
||||||
|
- Deriva degli indizi: negli ultimi 60 esempi, più del 20% dei valori di un indizio in uso sta fuori dall'intervallo 1%–99% visto in addestramento. Il giorno della settimana e la strategia non contano.
|
||||||
|
- Il rientro è automatico, al primo controllo senza motivi. Messa da parte e rientro si notificano.
|
||||||
|
|
||||||
|
**10. Domenica.** Senza sfidante se ne addestra uno, se ci sono esiti nuovi rispetto all'ultimo addestramento; con uno sfidante si guarda solo se i casi di confronto hanno passato una nuova soglia. Una domenica persa si recupera al primo controllo, una volta sola. Una promozione annullata lascia la versione tra le annullate: non torna da sola.
|
||||||
|
- Le strategie senza frequenza di base non addestrano: nessuno potrebbe stimarle.
|
||||||
|
|
||||||
|
**11. Avvio (11.5).** I 300 segnali sono quelli con un esito; almeno 100 devono essere di strategie con capitale (punto 18). Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte.
|
||||||
|
|
||||||
|
**12. Scostamento (11.6).** Il primo controllo notturno di ogni mese confronta, per fascia di liquidità (azioni; BTC, ETH e SOL; altre crypto), lo scostamento delle esecuzioni di conti di prova e reali degli ultimi 365 giorni. La fascia è l’unica variabile della regressione: il suo risultato è la media, con un intervallo al 95% a blocchi.
|
||||||
|
- Servono 30 esecuzioni. Gli stop scattati non contano: il salto di prezzo è già nel modo in cui simulatore e backtest li eseguono.
|
||||||
|
- Sale da sola solo se tutto l’intervallo sta sopra la stima in uso; scende solo su esecuzioni con soldi veri, con tutto l’intervallo sotto, e solo dopo la conferma nel Laboratorio. La stima si arrotonda per eccesso a mezzo punto base e non scende sotto mezzo punto. Una proposta non confermata scade il mese dopo.
|
||||||
|
- Lo scostamento si misura dal prezzo medio, quindi contiene anche la metà della forbice; il simulatore parte già dal denaro o dalla lettera: così conta un po’ di più, dal lato prudente.
|
||||||
|
- Un test nel Laboratorio scrive nel piano la tabella in uso, se diversa da quella di partenza: i piani già scritti restano identici. Le etichette (punto 3) e gli esiti di qualifica usano sempre la tabella di partenza: gli esempi restano confrontabili negli anni e il “previsto” di 12.3 resta quello della qualifica.
|
||||||
|
|
||||||
|
**13. Impatto delle notizie.** Per tipo di evento (parole chiave dei casi gravi, poi il tipo detto dal modello linguistico), il rendimento medio a 1 e a 5 chiusure dalla prima chiusura dopo la pubblicazione, sugli strumenti collegati. Solo informativa.
|
||||||
|
|
||||||
|
**14. Scoperte.** Le domande sono fisse nel codice (agitazione dei prezzi, fase del mercato, ampiezza, volumi, notizie molto negative, paura e avidità estreme, VIX, giorno della settimana), per strategia: il bot non ne cerca altre. L’errore conta come un caso solo ciò che è deciso nello stesso mese. Sotto i 100 casi basta che la differenza superi 1,96 errori e il giudizio dice da solo quanto vale; da 100 in su la soglia si alza con il numero di domande fatte. “Non conta” si dice solo con almeno 100 casi.
|
||||||
|
|
||||||
|
**15. Schermata Apprendimento** (mockup 06).
|
||||||
|
- I numeri del confronto tra modello in carica e sfidante sono quelli della verifica fatta all’addestramento, sui casi che il modello non aveva studiato. La precisione della Panoramica è la stessa.
|
||||||
|
- Il grafico delle probabilità mostra i segnali dal vivo appena una fascia ne ha almeno 20; fino ad allora mostra la verifica sui casi storici e lo dice. Una fascia sotto i 20 casi è dichiarata inaffidabile una per una.
|
||||||
|
- I grafici sono SVG e CSS fatti in casa, con le stesse cifre in una tabella (13.4); niente JavaScript.
|
||||||
|
- Il sottotitolo del mockup sta sotto la testata, come in Notizie: la riga con data e ora della testata è comune a tutte le schermate.
|
||||||
|
- L’operazione MSFT dei dati dimostrativi mostra la stima (61%, contro il 48% abituale): l’appendice F.7 non dà la frequenza di base, il 48% è quello della scoperta sui rimbalzi.
|
||||||
|
|
||||||
|
**16. Impostazioni del modello.** Soglie e messa da parte si cambiano solo dalla pagina Impostazioni, non dall’API generica. Rimpicciolire meno, o mettere da parte il modello, aumenta l’esposizione: con una strategia su soldi veri servono la frase e la password di 12.4. Rimpicciolire di più, o rimetterlo al suo posto, è libero.
|
||||||
|
|
||||||
|
**17. Correzioni della revisione indipendente** (due revisori a contesto pulito, sui calcoli e sulle schermate).
|
||||||
|
- La calibrazione isotonica usava come limite il primo gradino, anche di due casi: con pochi vincenti schiacciava tutte le stime verso l'alto. Il primo modello è stato rifatto con la calibrazione corretta, con la stessa regola di scelta, fissata prima.
|
||||||
|
- Una decisione recuperata in ritardo legge il mondo esterno com'era all'ora in cui doveva essere presa.
|
||||||
|
- Gli esempi si scrivono dentro un punto di salvataggio della transazione: un errore annulla solo loro, anche su PostgreSQL.
|
||||||
|
- Un'etichetta che non riesce non ferma il controllo della notte né la domenica: l'errore resta nel registro del lavoro. La notte si rifà una volta anche dopo che il computer ha dormito a lungo con il programma acceso.
|
||||||
|
- L'etichetta esce prima della trimestrale che la decisione conosceva, presa dagli indizi salvati.
|
||||||
|
- Un file storico nuovo non aggiunge un esempio per un'operazione già vissuta dal vivo. La data di addestramento del primo modello è la fine del suo storico.
|
||||||
|
- Le fasce di probabilità contano gli esempi e non le verifiche: le combinazioni verificano ogni esempio cinque volte. Sullo schermo le fasce dal vivo sono conteggi semplici; la pesatura per maturazione resta nei criteri di 11.4 e 11.5.
|
||||||
|
- Il contatore della prova mostra la prossima soglia non ancora giudicata; passata la soglia, dice quando si decide. Un controllo fatto su un'altra versione non si mostra.
|
||||||
|
- Una precisione sotto la soglia d'allarme non si mostra mai come 50%.
|
||||||
|
- La conferma di una stima di costo e "ho visto l'assenza" controllano il codice della pagina (CSRF), come gli altri moduli.
|
||||||
|
- La scheda di un'operazione mostra la stima anche quando il segnale è nato giorni prima dell'acquisto, e dice se il modello era messo da parte.
|
||||||
|
|
||||||
|
**18. Seconda lettura, sulle correzioni** (quattro lettori a contesto pulito, ogni rilievo passato da chi provava a smentirlo).
|
||||||
|
- **Avvio (11.5)**: il miglioramento si misura su almeno 100 segnali di strategie con capitale, oltre ai 300 in tutto. Prima ne bastava uno: l'intervallo su pochi casi aveva larghezza zero. Con meno di tre blocchi (30 casi) un intervallo non dice più niente. Questi segnali si pesano per maturazione tra loro, non insieme a quelli più vecchi in osservazione. La schermata dice quanti ne mancano.
|
||||||
|
- **Lavori recuperabili (5.6)**: un lavoro da recuperare conta dal primo avvio che lo conosce (la riga in `jobs` nasce subito). Prima, su un computer sempre spento alle 03:00, la notte del modello non sarebbe mai partita.
|
||||||
|
- **La notte aspetta le barre**: dopo un'assenza aspetta che lo storico dell'ultimo giorno chiuso sia scaricato, al massimo mezz'ora. Senza rete prosegue con quello che ha.
|
||||||
|
- **Notizie all'ora della decisione**: una storia si ricostruisce dagli articoli, dai collegamenti e dai giudizi salvati fino a quell'ora, perché cresce anche dopo la prima lettura.
|
||||||
|
- **Etichetta e trimestrali**: una trimestrale già uscita entro la seduta d'ingresso non chiude l'operazione simulata. Limite: l'orario della trimestrale non è tra gli indizi, quindi quella della seduta d'ingresso vale sempre come uscita. Succede solo con il filtro delle trimestrali spento dall'utente.
|
||||||
|
- Una promozione annullata fa ripartire da zero le soglie dello sfidante in prova.
|
||||||
|
- Una stima che fallisce vale 1 solo per l'operazione nuova; quelle già nate tengono il loro moltiplicatore.
|
||||||
|
- Scheda dell'operazione: la riga del modello si cerca quando manca nella decisione dell'acquisto, non in tutta la finestra, e vale anche se l'operazione simulata si è chiusa lo stesso giorno. Una riduzione non si scrive mai "al 100%" né "al 0%".
|
||||||
|
- La frase "è ben tarato" sui segnali dal vivo usa l'errore del criterio di avvio, come il resto della pagina; punti e percentuali restano conteggi semplici.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"Through":"2026-10-31","BaseRates":{"crypto_trend":0.18329718004338394},"Model":{"Clues":["strength","stop_distance","volatility","volatility_ratio","volume","market_trend","market_volatility","breadth","weekday_sin","weekday_cos"],"Learned":{"Learner":"logistic","Linear":{"Intercept":-1.5574604345197345,"Weights":[0.1590340105154227,0.11908779476819635,-0.162432512465705,-0.08003982796993969,-0.19132480071600444,0.3022103731539277,0.10780995530583182,-0.23941305842109442,-0.22326128923555164,-0.15096635705365147],"Means":[0.19601108548807236,0.050460482868763604,0.8833982208676783,0.9192900882537972,0.9662490365618214,0.0835851831670285,0.5876342481616039,0.476247288508679,0.08773042725596508,-0.05221374460412148],"Scales":[0.165485155045225,0.04067752287292153,0.4848501513845519,0.310638619072209,1.0200137514523773,0.33648118132548555,0.2603576946488006,0.34682317518394806,0.7017578634342959,0.70506240583181]},"Trees":null},"Calibration":{"Kind":"isotonic","Slope":1,"Offset":0,"Scores":[-2.31013942719076,-1.9151100659396874,-1.7663451007315563,-1.7294273092893189,-1.6834534361695037,-1.279712934228674],"Values":[0.11555555555555555,0.125,0.14736842105263157,0.15384615384615385,0.16393442622950818,0.23052959501557632]},"Ranges":{"strength":{"Low":0.11111111,"High":1,"Cases":1844},"stop_distance":{"Low":0.00554256,"High":0.2,"Cases":1844},"volatility":{"Low":0.22509683,"High":2.6730656,"Cases":1844},"volatility_ratio":{"Low":0.33680145,"High":1.81238384,"Cases":1844},"volume":{"Low":0.31563245,"High":3.85783042,"Cases":1844},"market_trend":{"Low":-0.42829195,"High":1.23482451,"Cases":1844},"market_volatility":{"Low":0.25961056,"High":1.79265636,"Cases":1844},"breadth":{"Low":0,"High":1,"Cases":1844},"weekday_sin":{"Low":-0.97492791,"High":0.97492791,"Cases":1844},"weekday_cos":{"Low":-0.90096887,"High":1,"Cases":1844}},"Strategies":["crypto_trend"]},"Report":{"Examples":1844,"Live":0,"ByStrategy":{"crypto_trend":1844},"BaseRates":{"crypto_trend":0.18329718004338394},"FirstDay":"2019-01-01","LastDay":"2026-10-28","Attempts":[{"Learner":"boosting","Forward":{"Cases":1107,"LogLoss":0.4901472349109493,"BaseLogLoss":0.47884194965218496,"Brier":0.15371685226409482,"Precision":0.507289937506103,"GainWithout":1.7619015934416593,"GainWith":1.4133353140068803,"Improvement":-0.348566279434779,"CalibrationError":0.045766180646463546,"Bands":[{"From":0.05,"To":0.1,"Cases":27,"Estimated":0.08513321633688159,"Observed":0.33327967159013155},{"From":0.1,"To":0.15,"Cases":76,"Estimated":0.1205846499171033,"Observed":0.2692438228736069},{"From":0.15,"To":0.2,"Cases":602,"Estimated":0.17613223786197266,"Observed":0.1707911333371173},{"From":0.2,"To":0.25,"Cases":261,"Estimated":0.2227211085612617,"Observed":0.14663644573512966},{"From":0.25,"To":0.3,"Cases":70,"Estimated":0.2646022340952087,"Observed":0.21307426019867914},{"From":0.3,"To":0.35,"Cases":38,"Estimated":0.3291545441015799,"Observed":0.21140647874817575},{"From":0.35,"To":0.4,"Cases":16,"Estimated":0.37353561368298727,"Observed":0.35049852907302864},{"From":0.4,"To":0.45,"Cases":12,"Estimated":0.42519433372299786,"Observed":0.283533030708765},{"From":0.45,"To":0.5,"Cases":5,"Estimated":0.4714069044078384,"Observed":0}]},"Combined":{"Cases":9220,"LogLoss":0.4837238568877384,"BaseLogLoss":0.4806696575091626,"Brier":0.15185458964467266,"Precision":0.5204232380144118,"GainWithout":1.6880808292523108,"GainWith":1.6364813104483271,"Improvement":-0.051599518803983724,"CalibrationError":0.03014685726947035,"Bands":[{"From":0,"To":0.05,"Cases":1,"Estimated":0.046564955701587085,"Observed":0.3333333333333333},{"From":0.05,"To":0.1,"Cases":46,"Estimated":0.07881756467240499,"Observed":0.15789473684210525},{"From":0.1,"To":0.15,"Cases":354,"Estimated":0.13721738144360052,"Observed":0.18972332015810275},{"From":0.15,"To":0.2,"Cases":887,"Estimated":0.17631601405250116,"Observed":0.18241262683201803},{"From":0.2,"To":0.25,"Cases":389,"Estimated":0.214237231909851,"Observed":0.19023136246786632},{"From":0.25,"To":0.3,"Cases":136,"Estimated":0.26749199949900143,"Observed":0.15905743740795286},{"From":0.3,"To":0.35,"Cases":31,"Estimated":0.30986280783768577,"Observed":0.1858974358974359},{"From":0.35,"To":0.4,"Cases":1,"Estimated":0.3668701553971652,"Observed":0.3333333333333333}]},"Chosen":false},{"Learner":"logistic","Forward":{"Cases":1107,"LogLoss":0.4735156194734787,"BaseLogLoss":0.47884194965218496,"Brier":0.14890023945017386,"Precision":0.5457932574943853,"GainWithout":1.7619015934416593,"GainWith":1.8120652589010067,"Improvement":0.05016366545934736,"CalibrationError":0.017426102268308204,"Bands":[{"From":0.05,"To":0.1,"Cases":2,"Estimated":0.0909525554691676,"Observed":0},{"From":0.1,"To":0.15,"Cases":101,"Estimated":0.140951208737604,"Observed":0.16040173361620094},{"From":0.15,"To":0.2,"Cases":520,"Estimated":0.1790306767513123,"Observed":0.1688945041903547},{"From":0.2,"To":0.25,"Cases":452,"Estimated":0.21795407082480758,"Observed":0.19599570984164852},{"From":0.25,"Line truncated
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Primo modello: rapporto di convalida
|
||||||
|
|
||||||
|
Generato con `anubis learning base --to 2026-10-31` sullo storico fino al 31/10/2026. Gli stessi dati danno sempre lo stesso modello.
|
||||||
|
|
||||||
|
## La domanda
|
||||||
|
|
||||||
|
Il modello non prevede i prezzi. Guarda un segnale di una strategia e stima quanto è probabile che l'operazione chiuda in guadagno, al netto dei costi. Può solo rimpicciolire l'operazione.
|
||||||
|
|
||||||
|
## Gli esempi
|
||||||
|
|
||||||
|
1848 esempi ricostruiti facendo girare le strategie sullo storico: 1844 con un esito, 4 con l'operazione ancora aperta, 0 mai partiti (sotto il minimo).
|
||||||
|
|
||||||
|
| Strategia | Esempi con esito | Dal | Al | In guadagno (frequenza di base) | Risultato medio dell'operazione |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| crypto_trend | 1844 | 01/01/2019 | 28/10/2026 | 18,3% | +0,8% |
|
||||||
|
| equity_momentum | 0 | | | nessuna: aspetta lo storico di Alpaca | |
|
||||||
|
| equity_meanrev | 0 | | | nessuna: aspetta lo storico di Alpaca | |
|
||||||
|
|
||||||
|
Una strategia senza frequenza di base non viene stimata: il modello lascia le sue operazioni come sono.
|
||||||
|
|
||||||
|
## La convalida
|
||||||
|
|
||||||
|
Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si studia il passato e si verifica il periodo dopo, 5 volte. «A combinazioni»: 15 combinazioni di 6 periodi, togliendo dallo studio ogni esempio che si sovrappone nel tempo a quelli di verifica, più 10 giorni di distacco.
|
||||||
|
|
||||||
|
| Modello | Prova | Casi | Errore (log-loss) | Di chi risponde sempre la frequenza di base | Errore sulle probabilità (Brier) | Previsioni azzeccate | Guadagno medio per operazione proposta, senza filtro | con il filtro |
|
||||||
|
|---|---|---|---|---|---|---|---|---|
|
||||||
|
| Alberi potenziati | in avanti | 1107 | 0,4901 | 0,4788 | 0,1537 | 50,7% | +1,76 € | +1,41 € |
|
||||||
|
| Alberi potenziati | a combinazioni | 9220 | 0,4837 | 0,4807 | 0,1519 | 52,0% | +1,69 € | +1,64 € |
|
||||||
|
| Regressione logistica (scelto) | in avanti | 1107 | 0,4735 | 0,4788 | 0,1489 | 54,6% | +1,76 € | +1,81 € |
|
||||||
|
| Regressione logistica (scelto) | a combinazioni | 9220 | 0,4796 | 0,4807 | 0,1506 | 56,0% | +1,69 € | +1,76 € |
|
||||||
|
| Foresta casuale | in avanti | 1107 | 0,4819 | 0,4788 | 0,1512 | 50,7% | +1,76 € | +1,69 € |
|
||||||
|
| Foresta casuale | a combinazioni | 9220 | 0,4821 | 0,4807 | 0,1513 | 52,6% | +1,69 € | +1,64 € |
|
||||||
|
|
||||||
|
Il guadagno è calcolato sul capitale di riferimento (10.000 € in tutto, quote predefinite). Nelle combinazioni ogni caso è verificato più volte.
|
||||||
|
|
||||||
|
**Scelta.** Regressione logistica: il miglior guadagno medio per operazione proposta su esempi mai visti. La regola era fissata prima di guardare i numeri (ADR 0018).
|
||||||
|
|
||||||
|
**Lettura onesta.** Le stime sono migliori di chi risponde sempre la frequenza di base in tutte e due le prove, ma di poco: errore più basso, 0,2% in meno nelle combinazioni e 1,1% in meno in avanti. Con il filtro il guadagno medio per operazione proposta cambia di +0,07 € nelle combinazioni e di +0,05 € in avanti.
|
||||||
|
|
||||||
|
## Cosa guarda di più
|
||||||
|
|
||||||
|
| Indizio | Peso su 100 |
|
||||||
|
|---|---|
|
||||||
|
| Giorno della settimana | 34 |
|
||||||
|
| Forza della tendenza | 30 |
|
||||||
|
| Agitazione recente dei prezzi | 19 |
|
||||||
|
| Quota di titoli in salita | 12 |
|
||||||
|
| Fase generale del mercato | 5 |
|
||||||
|
| Distanza dallo stop | 0 |
|
||||||
|
| Volumi scambiati | 0 |
|
||||||
|
|
||||||
|
Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizio. Con tutti i pesi a zero nessun indizio aiuta.
|
||||||
|
|
||||||
|
## Ci si può fidare delle probabilità?
|
||||||
|
|
||||||
|
Verifica a combinazioni, fasce da 5 punti; un esempio verificato più volte conta come un caso. Contano le fasce con almeno 20 casi; errore medio 2,2 punti.
|
||||||
|
|
||||||
|
| Stima | Casi | Stimato in media | Andate bene |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 0–5% | 12 | 4,6% | 19,0% |
|
||||||
|
| 5–10% | 38 | 8,1% | 16,9% |
|
||||||
|
| 10–15% | 377 | 13,3% | 14,6% |
|
||||||
|
| 15–20% | 837 | 17,7% | 19,1% |
|
||||||
|
| 20–25% | 395 | 21,7% | 20,6% |
|
||||||
|
| 25–30% | 167 | 26,9% | 17,7% |
|
||||||
|
| 30–35% | 13 | 31,8% | 18,2% |
|
||||||
|
| 35–40% | 5 | 35,9% | 26,9% |
|
||||||
|
|
||||||
|
## Cosa succede adesso
|
||||||
|
|
||||||
|
Il modello parte in osservazione: stima ogni segnale e non cambia nessuna operazione. Comincerà a contare solo dopo almeno 300 segnali dal vivo, con probabilità ben tarate e un miglioramento distinguibile dal caso (SPEC 11.5).
|
||||||
@@ -377,6 +377,11 @@ internal sealed partial class AnubisHost(
|
|||||||
lastDues[name] = due;
|
lastDues[name] = due;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!options.Demo)
|
||||||
|
{
|
||||||
|
await StartCountingAsync([.. SchedulerJobs(backups)], lastDues, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
if (_sampler is not null)
|
if (_sampler is not null)
|
||||||
{
|
{
|
||||||
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
|
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
|
||||||
@@ -506,13 +511,31 @@ internal sealed partial class AnubisHost(
|
|||||||
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
|
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
|
||||||
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
|
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
|
||||||
|
|
||||||
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
|
private IEnumerable<ScheduledJob> SchedulerJobs(Backups backups)
|
||||||
{
|
{
|
||||||
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
|
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
|
||||||
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
|
||||||
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
|
||||||
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
|
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
|
||||||
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
|
return new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A job to make up for after an absence counts from the first start that knows it. Otherwise a computer always off at
|
||||||
|
/// its hour would never make it: without a first run there would be no run to find missed (SPEC 5.6).
|
||||||
|
/// </summary>
|
||||||
|
private Task StartCountingAsync(IReadOnlyList<ScheduledJob> jobs, Dictionary<string, DateTimeOffset> lastDues, CancellationToken cancellationToken) => _db!.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
foreach (var job in jobs.Where(j => j.CatchUpWithin is not null && !lastDues.ContainsKey(j.Name)))
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, created_at, updated_at) VALUES (@id, @n, @d, @now, @now, @now) ON CONFLICT (name) DO NOTHING", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("n", job.Name), ("d", job.Description), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
|
||||||
|
{
|
||||||
|
foreach (var job in SchedulerJobs(backups))
|
||||||
{
|
{
|
||||||
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
|
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -681,7 +681,91 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
|||||||
.source-list li > span:first-child { display: inline-flex; }
|
.source-list li > span:first-child { display: inline-flex; }
|
||||||
.source-list .muted { text-align: right; }
|
.source-list .muted { text-align: right; }
|
||||||
|
|
||||||
|
/* ---- Apprendimento (mockup 06) ---- */
|
||||||
|
.learning-head { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); }
|
||||||
|
.learning-state { display: flex; flex-direction: column; align-items: flex-start; gap: 14px; }
|
||||||
|
.learning-state h2 { font-size: 26px; line-height: 34px; letter-spacing: -0.015em; }
|
||||||
|
.learning-text { color: var(--text-2); font-size: 15px; line-height: 23px; max-width: 62ch; }
|
||||||
|
.learning-progress { width: 100%; max-width: 560px; }
|
||||||
|
.learning-progress .usage { height: 8px; border-radius: 4px; }
|
||||||
|
.state-badge { display: inline-flex; align-items: center; gap: 8px; padding: 4px 12px; border-radius: 999px; background: var(--surface-2); color: var(--text); font-weight: 600; font-size: 13.5px; }
|
||||||
|
.state-badge.on { background: var(--gain-bg); color: var(--gain); }
|
||||||
|
.state-badge.warn { background: var(--attention-bg); color: var(--attention); }
|
||||||
|
.learning-facts { margin: 0; display: flex; flex-direction: column; justify-content: center; }
|
||||||
|
.learning-facts > div { padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.learning-facts > div:last-child { border-bottom: 0; }
|
||||||
|
.learning-facts dt { color: var(--text-3); font-size: 13.5px; }
|
||||||
|
.learning-facts dd { margin: 0; }
|
||||||
|
.learning-facts dd strong { font-size: 16px; line-height: 24px; font-weight: 650; }
|
||||||
|
.learning-facts .learning-precision { font-size: 30px; line-height: 38px; font-weight: 650; letter-spacing: -0.02em; }
|
||||||
|
.learning-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: stretch; }
|
||||||
|
.learning-row-wide { grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); }
|
||||||
|
.learning-row .panel { padding: 24px 26px; display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.learning-row .panel > h2 { margin-bottom: 4px; }
|
||||||
|
.learning-open { align-items: start; gap: 28px; }
|
||||||
|
.calibration { display: flex; flex-direction: column; margin-top: 12px; flex: 1; }
|
||||||
|
.calibration-title, .calibration-foot { color: var(--text-2); font-size: 14px; }
|
||||||
|
.calibration-foot { text-align: center; margin-right: 20%; }
|
||||||
|
.calibration-box { position: relative; display: grid; grid-template-columns: 56px minmax(0, 1fr); height: 250px; margin: 14px 20% 0 0; }
|
||||||
|
.calibration .chart-axis { display: block; }
|
||||||
|
.calibration .base { stroke: var(--control); stroke-width: 1; }
|
||||||
|
.calibration-x { position: relative; height: 30px; margin: 8px 20% 0 56px; color: var(--text-3); font-size: 13px; }
|
||||||
|
.calibration-x span { position: absolute; transform: translateX(-50%); }
|
||||||
|
.calibration .legend { margin-top: 20px; }
|
||||||
|
.calibration-text { color: var(--text-2); margin-top: 12px; }
|
||||||
|
.point-label { position: absolute; white-space: nowrap; font-size: 13.5px; font-weight: 650; pointer-events: none; }
|
||||||
|
.point-label.below { transform: translate(12px, 8px); }
|
||||||
|
.point-label.below-left { transform: translate(calc(-100% - 10px), 8px); }
|
||||||
|
.point-label.above { transform: translate(-100%, -24px); margin-left: -8px; }
|
||||||
|
.point-label.under { transform: translate(-50%, 10px); }
|
||||||
|
.hover-dot:hover { z-index: 2; }
|
||||||
|
.hover-dot.quiet { opacity: 0; }
|
||||||
|
.hover-dot.quiet:hover { opacity: 1; }
|
||||||
|
.hover-box { display: none; position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%); padding: 6px 10px; border-radius: 8px; background: var(--text); color: var(--surface); font-size: 13px; line-height: 18px; white-space: nowrap; font-weight: 500; }
|
||||||
|
.hover-dot:hover .hover-box { display: block; }
|
||||||
|
.weights { list-style: none; margin: 12px 0 0; padding: 0; }
|
||||||
|
.weights li { display: grid; grid-template-columns: minmax(0, 215px) minmax(0, 1fr) 30px; gap: 16px; align-items: center; min-height: 31px; }
|
||||||
|
.weights strong { text-align: right; font-variant-numeric: tabular-nums; font-weight: 650; }
|
||||||
|
.weight-bar span { display: block; height: 11px; border-radius: 0 4px 4px 0; background: var(--text-2); min-width: 2px; }
|
||||||
|
.weights .rest > span:first-child { color: var(--text-3); }
|
||||||
|
.weights .rest .weight-bar span { background: var(--bench); }
|
||||||
|
.weights-text { margin-top: auto; padding-top: 18px; }
|
||||||
|
.versions { margin-top: 8px; }
|
||||||
|
.versions thead td { border-bottom: 1px solid var(--rule); }
|
||||||
|
.versions thead th { color: var(--text); font-weight: 650; font-size: 13.5px; border-bottom-color: var(--rule); }
|
||||||
|
.versions th[scope="row"] { font-weight: 400; text-align: left; font-size: 13.5px; color: var(--text-2); }
|
||||||
|
@media (min-width: 761px) { .versions thead th { white-space: nowrap; } }
|
||||||
|
.learning-row .aside { margin-top: 16px; }
|
||||||
|
.learning-row .aside strong { color: var(--text); }
|
||||||
|
.learning-row .panel > .chart-table, .learning-row .panel > form { margin-top: 14px; }
|
||||||
|
.learning-watch .panel-head { margin-bottom: 8px; }
|
||||||
|
.learning-watch .aside { margin-top: auto; }
|
||||||
|
.status-pill.gain { color: var(--gain); }
|
||||||
|
.watch-list { list-style: none; margin: 0 0 14px; padding: 0; }
|
||||||
|
.watch-list li { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid var(--rule-inner); color: var(--text-2); }
|
||||||
|
.watch-list .icon { margin-top: 2px; color: var(--text-3); }
|
||||||
|
.watch-list .ok .icon { color: var(--gain); }
|
||||||
|
.watch-list .warn, .watch-list .warn .icon { color: var(--attention); }
|
||||||
|
.weekly { margin: 0 0 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); }
|
||||||
|
.weekly-box { display: grid; grid-template-columns: minmax(0, 1fr) 76px; height: 84px; margin: 12px 0 4px 6px; }
|
||||||
|
.weekly svg .bench { fill: none; stroke: var(--bench); stroke-width: 1; }
|
||||||
|
.weekly svg .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
|
||||||
|
.weekly .end-dot { width: 12px; height: 12px; margin: -6px 0 0 -6px; }
|
||||||
|
.weekly-side { position: relative; font-size: 13px; }
|
||||||
|
.weekly-side strong, .weekly-side span { position: absolute; left: 14px; line-height: 15px; white-space: nowrap; }
|
||||||
|
.weekly-side strong { transform: translateY(-60%); font-weight: 650; }
|
||||||
|
.weekly-side span { color: var(--text-3); transform: translateY(-20%); font-size: 12.5px; }
|
||||||
|
.weekly-x { display: flex; justify-content: space-between; margin: 10px 76px 0 6px; }
|
||||||
|
.found { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.found li { display: flex; flex-direction: column; gap: 5px; padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||||
|
.found li:last-child { border-bottom: 0; }
|
||||||
|
.found strong { font-weight: 650; }
|
||||||
|
.found-detail { color: var(--text-2); }
|
||||||
|
.found .attention { font-size: 13px; }
|
||||||
|
.learning-open .plain h3 { margin: 18px 0 4px; }
|
||||||
|
|
||||||
@media (max-width: 1180px) {
|
@media (max-width: 1180px) {
|
||||||
|
.learning-row, .learning-row-wide { grid-template-columns: minmax(0, 1fr); }
|
||||||
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
.overview-row-wide, .journal-columns, .news-columns { grid-template-columns: minmax(0, 1fr); }
|
.overview-row-wide, .journal-columns, .news-columns { grid-template-columns: minmax(0, 1fr); }
|
||||||
}
|
}
|
||||||
@@ -787,4 +871,14 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
|||||||
.news-panel > .panel-head .segmented { display: flex; width: 100%; }
|
.news-panel > .panel-head .segmented { display: flex; width: 100%; }
|
||||||
.news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
|
.news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
|
||||||
.news-columns, .news-side { gap: 14px; }
|
.news-columns, .news-side { gap: 14px; }
|
||||||
|
.learning-head { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.learning-state h2 { font-size: 22px; line-height: 28px; }
|
||||||
|
.learning-row { gap: 14px; }
|
||||||
|
.learning-row .panel { padding: 18px; }
|
||||||
|
.calibration-box { margin-right: 0; grid-template-columns: 42px minmax(0, 1fr); }
|
||||||
|
.calibration-x { margin-right: 0; margin-left: 42px; }
|
||||||
|
.calibration-foot { margin-right: 0; }
|
||||||
|
.calibration .legend { flex-direction: row; }
|
||||||
|
.weights li { grid-template-columns: minmax(0, 150px) minmax(0, 1fr) 26px; gap: 10px; }
|
||||||
|
.chart-table summary { min-height: 44px; display: flex; align-items: center; }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
@* How often it went well against what the model said (SPEC 13.4, mockup 06): one scale, 2 px lines, faint grid, the
|
||||||
|
perfect estimate beside it, direct labels on the fullest band and on the last one, a box on hover and the table.
|
||||||
|
As in EquityChart the lines are SVG stretched to the box; texts and points are HTML placed in percent. *@
|
||||||
|
@if (Bands.Count > 0)
|
||||||
|
{
|
||||||
|
var loX = Bands.Min(b => b.From) / 10 * 10;
|
||||||
|
var hiX = (Bands.Max(b => b.To) + 9) / 10 * 10;
|
||||||
|
var loY = Math.Min(loX, (int)Math.Floor(Bands.Min(b => b.Observed)) / 10 * 10) - 5m;
|
||||||
|
var hiY = Math.Max(hiX, Bands.Max(b => b.Observed)) + 4m;
|
||||||
|
var step = hiX - loX > 60 ? 20 : 10;
|
||||||
|
var fullest = Bands.MaxBy(b => b.Cases)!;
|
||||||
|
var last = Bands[^1];
|
||||||
|
decimal X(decimal v) => (v - loX) / (hiX - loX) * 1000m;
|
||||||
|
decimal Y(decimal v) => (hiY - v) / (hiY - loY) * 1000m;
|
||||||
|
<figure class="chart calibration" aria-label="Quanto spesso è andata bene, rispetto a quello che diceva il modello">
|
||||||
|
<p class="calibration-title" aria-hidden="true">…va bene davvero</p>
|
||||||
|
<div class="calibration-box">
|
||||||
|
<div class="chart-axis" aria-hidden="true">
|
||||||
|
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||||
|
{
|
||||||
|
<span style="top:@Pct(Y(t) / 10)">@t%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="chart-plot">
|
||||||
|
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||||
|
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||||
|
{
|
||||||
|
<line class="grid" x1="0" x2="1000" y1="@Css(Y(t))" y2="@Css(Y(t))" vector-effect="non-scaling-stroke" />
|
||||||
|
}
|
||||||
|
<line class="base" x1="0" x2="1000" y1="1000" y2="1000" vector-effect="non-scaling-stroke" />
|
||||||
|
<line class="bench" x1="0" y1="@Css(Y(loX))" x2="1000" y2="@Css(Y(hiX))" vector-effect="non-scaling-stroke" />
|
||||||
|
<polyline class="equity" points="@string.Join(" ", Bands.Select(b => Css(X(b.Estimated)) + "," + Css(Y(b.Observed))))" vector-effect="non-scaling-stroke" />
|
||||||
|
</svg>
|
||||||
|
@foreach (var b in Bands)
|
||||||
|
{
|
||||||
|
<span class="end-dot hover-dot" style="left:@Pct(X(b.Estimated) / 10);top:@Pct(Y(b.Observed) / 10)"><span class="hover-box">Tra @(b.From)% e @(b.To)%<br />@Format.Number(b.Observed)% su @Cases(b)</span></span>
|
||||||
|
}
|
||||||
|
<span class="point-label @(X(fullest.Estimated) > 450m ? "below-left" : "below")" style="left:@Pct(X(fullest.Estimated) / 10);top:@Pct(Y(fullest.Observed) / 10)">@Label(fullest)</span>
|
||||||
|
@if (last != fullest)
|
||||||
|
{
|
||||||
|
<span class="point-label above" style="left:@Pct(X(last.Estimated) / 10);top:@Pct(Y(last.Observed) / 10)">@Label(last)</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="calibration-x" aria-hidden="true">
|
||||||
|
@for (var t = loX; t <= hiX; t += step)
|
||||||
|
{
|
||||||
|
<span style="left:@Pct(X(t) / 10)">@t%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<p class="calibration-foot" aria-hidden="true">Quando il modello dice…</p>
|
||||||
|
<figcaption class="legend">
|
||||||
|
<span class="key key-equity">Il modello</span>
|
||||||
|
<span class="key key-bench">Stima perfetta</span>
|
||||||
|
</figcaption>
|
||||||
|
<p class="calibration-text">@Text</p>
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Vedi i numeri in una tabella</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Quando il modello dice</th><th scope="col" class="num">Casi</th><th scope="col" class="num">È andata bene</th><th scope="col">Affidabilità</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var b in Bands)
|
||||||
|
{
|
||||||
|
<tr><td>tra @(b.From)% e @(b.To)%</td><td class="num">@Format.Number(b.Cases)</td><td class="num">@Format.Number(b.Observed)%</td><td class="@(b.Solid ? null : "attention-text")">@(b.Solid ? "conta" : "troppo pochi casi per contarci")</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</figure>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public IReadOnlyList<LearningBand> Bands { get; set; } = [];
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string Text { get; set; } = "";
|
||||||
|
|
||||||
|
private static string Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {Cases(b)}";
|
||||||
|
|
||||||
|
private static string Cases(LearningBand b) => b.Cases == 1 ? "un caso" : Format.Number(b.Cases) + " casi";
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||||
|
}
|
||||||
@@ -89,6 +89,9 @@
|
|||||||
case "tick":
|
case "tick":
|
||||||
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
||||||
break;
|
break;
|
||||||
|
case "eye":
|
||||||
|
<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z" /><circle cx="12" cy="12" r="2.8" />
|
||||||
|
break;
|
||||||
case "logout":
|
case "logout":
|
||||||
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -1,5 +1,310 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
@page "/apprendimento"
|
@page "/apprendimento"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@using Anubis.Learning
|
||||||
|
|
||||||
<PageTitle>Apprendimento · Anubis</PageTitle>
|
<PageTitle>Apprendimento · Anubis</PageTitle>
|
||||||
|
|
||||||
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var s = v.Summary;
|
||||||
|
var c = _currency;
|
||||||
|
}
|
||||||
|
<p class="lead page-lead">Il modello impara dall'esito di ogni segnale.</p>
|
||||||
|
@if (Ok == "promozione")
|
||||||
|
{
|
||||||
|
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />Promozione annullata: è tornata in carica la versione precedente.</p>
|
||||||
|
}
|
||||||
|
else if (Errore is not null)
|
||||||
|
{
|
||||||
|
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@(Errore == "motore" ? "Nella modalità dimostrativa non si cambia nulla." : "Non c'è nessuna promozione da annullare.")</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="panel head-block learning-head" aria-labelledby="stato">
|
||||||
|
<div class="half learning-state">
|
||||||
|
<span class="state-badge @(s.State is LearningStates.Aside or LearningStates.Manual ? "warn" : s.State == LearningStates.Active ? "on" : null)"><Icon Name="@BadgeIcon(s.State)" Size="16" />@Badge(s.State)</span>
|
||||||
|
<h2 id="stato">@v.Title</h2>
|
||||||
|
<p class="learning-text">@v.Text</p>
|
||||||
|
@if (s.State != LearningStates.None)
|
||||||
|
{
|
||||||
|
<div class="limit learning-progress">
|
||||||
|
@if (s.Signals < s.Needed)
|
||||||
|
{
|
||||||
|
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@s.Signals</strong> <span class="muted">su @s.Needed necessari</span></span></div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@Format.Number(s.Signals)</strong> <span class="muted">(ne servivano @s.Needed)</span></span></div>
|
||||||
|
}
|
||||||
|
<span class="usage"><span style="width: @Css(Math.Min(100m, s.Signals * 100m / Math.Max(1, s.Needed)))%"></span></span>
|
||||||
|
@if (v.Pace is { } pace)
|
||||||
|
{
|
||||||
|
<span class="note">@pace</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (v.Missing.Count > 0)
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var m in v.Missing)
|
||||||
|
{
|
||||||
|
<li class="wait"><Icon Name="clock" Size="16" />@m</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (s.State == LearningStates.Manual)
|
||||||
|
{
|
||||||
|
<p><a href="/impostazioni#modello">Vai a Impostazioni</a></p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<dl class="half learning-facts">
|
||||||
|
<div>
|
||||||
|
<dt>Previsioni azzeccate su casi mai visti</dt>
|
||||||
|
<dd class="learning-precision">@(s.Precision is { } precision ? precision + "%" : "—")</dd>
|
||||||
|
<dd class="note">@(s.Precision is null ? "Si misura al primo addestramento" : "Tirando a caso sarebbe il 50%")</dd>
|
||||||
|
</div>
|
||||||
|
<div><dt>Ultimo addestramento</dt><dd><strong>@Capital(v.LastTraining)</strong></dd></div>
|
||||||
|
<div><dt>@s.NextLabel</dt><dd><strong>@Capital(s.NextCheck)</strong></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="learning-row">
|
||||||
|
<section class="panel" aria-labelledby="fiducia">
|
||||||
|
<h2 id="fiducia">Ci si può fidare delle sue probabilità?</h2>
|
||||||
|
@if (v.Bands.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">@v.BandsText Qui vedrai quante volte va bene davvero quando il modello dice che una cosa è probabile.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Più i punti stanno sulla linea, più la stima corrisponde ai fatti.@(v.BandsFromHistory ? " Per ora sono i casi storici che non aveva studiato: quelli dal vivo sono ancora troppo pochi." : "")</p>
|
||||||
|
<CalibrationChart Bands="v.Bands" Text="@v.BandsText" />
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel learning-weights" aria-labelledby="indizi">
|
||||||
|
<h2 id="indizi">Cosa guarda di più</h2>
|
||||||
|
@if (v.Champion is null)
|
||||||
|
{
|
||||||
|
<p class="note">Si vedrà con il primo modello.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Quanto pesa ogni informazione nelle sue stime, su 100.</p>
|
||||||
|
@if (v.Weights.Count > 0)
|
||||||
|
{
|
||||||
|
var most = v.Weights.Max(w => w.Share);
|
||||||
|
<ul class="weights">
|
||||||
|
@foreach (var w in v.Weights)
|
||||||
|
{
|
||||||
|
<li class="@(w.Rest ? "rest" : null)"><span>@w.Name</span><span class="weight-bar" aria-hidden="true"><span style="width: @Css(w.Share * 100m / most)%"></span></span><strong>@w.Share</strong></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<p class="note weights-text">@v.WeightsText</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="learning-row learning-row-wide">
|
||||||
|
<section class="panel" aria-labelledby="versioni">
|
||||||
|
<h2 id="versioni">Il modello in carica e lo sfidante</h2>
|
||||||
|
<p class="note">Lo sfidante gira in ombra accanto al modello in carica. Ne prende il posto solo se è chiaramente migliore.</p>
|
||||||
|
@if (v.Champion is { } now)
|
||||||
|
{
|
||||||
|
var other = v.Challenger;
|
||||||
|
var same = other is null || other.GainWithout == now.GainWithout;
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table versions">
|
||||||
|
<thead><tr><td></td><th scope="col" class="num">In carica, versione @now.Version</th>@if (other is not null){<th scope="col" class="num">Sfidante, versione @other.Version</th>}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row">Addestrato</th><td class="num">@now.Trained</td>@if (other is not null){<td class="num">@other.Trained</td>}</tr>
|
||||||
|
<tr><th scope="row">Casi studiati</th><td class="num">@Format.Number(now.Examples)</td>@if (other is not null){<td class="num">@Format.Number(other.Examples)</td>}</tr>
|
||||||
|
<tr><th scope="row">Previsioni azzeccate su casi mai visti</th><td class="num"><strong>@Share(now.Precision)</strong></td>@if (other is not null){<td class="num"><strong>@Share(other.Precision)</strong></td>}</tr>
|
||||||
|
<tr><th scope="row">Errore sulle probabilità <span class="muted">(più basso è meglio)</span></th><td class="num">@Error(now.Error)</td>@if (other is not null){<td class="num">@Error(other.Error)</td>}</tr>
|
||||||
|
<tr><th scope="row">Guadagno medio per operazione se filtrasse lui @if (same && now.GainWithout is { } without){<span class="muted">(senza filtro: @Shell.Money(without, c, withSign: true))</span>}</th>
|
||||||
|
<td class="num">@Gain(now, same, c)</td>@if (other is not null){<td class="num">@Gain(other, same, c)</td>}</tr>
|
||||||
|
@if (other is not null)
|
||||||
|
{
|
||||||
|
<tr><th scope="row">Casi di confronto diretto</th><td class="num muted">non serve</td><td class="num">@Format.Number(v.Pairs) su @v.PairsNeeded</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (v.GainOnReference)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna strategia con capitale affidato ha ancora casi: il guadagno è calcolato su tutte, con il capitale di riferimento.</p>
|
||||||
|
}
|
||||||
|
<p class="aside"><strong>@v.TrialTitle</strong> @v.TrialText</p>
|
||||||
|
@if (v.Choice is { } choice)
|
||||||
|
{
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Come è stato scelto il modello in carica</summary>
|
||||||
|
<p class="note">@choice Sono tutte prove su casi che il modello non aveva studiato; contano anche quelle scartate.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Tipo di modello</th><th scope="col" class="num">Previsioni azzeccate</th><th scope="col" class="num">Errore</th><th scope="col" class="num">Guadagno per operazione</th><th scope="col">Esito</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var a in v.Attempts)
|
||||||
|
{
|
||||||
|
<tr><td>@a.Learner</td><td class="num">@Share(a.Precision)</td><td class="num">@Error(a.Error)</td><td class="num nowrap">@Shell.Money(a.Gain, c, withSign: true)</td><td>@(a.Chosen ? "scelto" : "non scelto")</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
@if (v.UndoTo is { } back && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn" type="submit" data-confirm="Torna in carica la versione @back e la versione @v.Champion!.Version viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||||
|
<span class="hint">Tornerebbe in carica la versione @back.</span>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel learning-watch" aria-labelledby="sorveglianza">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="sorveglianza">Sorveglianza</h2>
|
||||||
|
@if (v.Checked)
|
||||||
|
{
|
||||||
|
<span class="status-pill @(v.Anomaly ? "attention" : "gain")"><Icon Name="@(v.Anomaly ? "alert" : "check")" Size="16" />@(v.Anomaly ? "Anomalia" : "Nessuna anomalia")</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (!v.Checked)
|
||||||
|
{
|
||||||
|
<p class="note">Il controllo gira ogni notte alle 03:00: confronta le stime con gli esiti e il mercato di oggi con quello su cui ha studiato.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="watch-list">
|
||||||
|
@foreach (var check in v.Checks)
|
||||||
|
{
|
||||||
|
<li class="@check.State"><Icon Name="@(check.State switch { "ok" => "tick", "warn" => "alert", _ => "clock" })" Size="16" /><span>@check.Text</span></li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<WeeklyPrecision Weeks="v.Weeks" />
|
||||||
|
}
|
||||||
|
<p class="aside">Se la precisione cala, il modello viene messo da parte da solo e le strategie proseguono senza di lui.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="learning-row learning-open">
|
||||||
|
<section class="plain" aria-labelledby="imparato">
|
||||||
|
<h2 id="imparato">Cosa ha imparato finora</h2>
|
||||||
|
@if (v.Found.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Ancora niente: le relazioni tra indizi ed esiti si cercano ogni notte, quando i casi bastano per un confronto.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="found">
|
||||||
|
@foreach (var d in v.Found)
|
||||||
|
{
|
||||||
|
<li>
|
||||||
|
<strong>@d.Title</strong>
|
||||||
|
<span class="found-detail">@d.Detail</span>
|
||||||
|
<span class="@(d.Cases < 20 ? "attention" : "note")">@if (d.Cases < 20){<Icon Name="alert" Size="16" />}@(d.Cases == 1 ? "Un caso" : Format.Number(d.Cases) + " casi"): @d.Trust</span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
@if (v.News.Count > 0)
|
||||||
|
{
|
||||||
|
<h3>Cosa succede ai prezzi dopo una notizia</h3>
|
||||||
|
<p class="note">Rendimento medio dalla prima chiusura dopo la notizia. È solo un'informazione: non cambia nessuna regola.</p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Tipo di notizia</th><th scope="col" class="num">Dopo 1 giorno</th><th scope="col" class="num">Dopo 5 giorni</th><th scope="col">Casi</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var n in v.News)
|
||||||
|
{
|
||||||
|
<tr><td>@NewsEventNames.Label(n.Kind)</td><td class="num">@Move(n.OneDay)</td><td class="num">@Move(n.FiveDays)</td><td class="@(n.Cases < 20 ? "attention-text" : null)">@n.Cases: @n.Trust</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="plain" aria-labelledby="storia">
|
||||||
|
<h2 id="storia">Storia</h2>
|
||||||
|
@if (v.Story.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">La storia comincia con il primo modello.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Story.Take(LearningView.StoryRows))
|
||||||
|
{
|
||||||
|
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
@if (v.Story.Count > LearningView.StoryRows)
|
||||||
|
{
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Mostra i @(v.Story.Count - LearningView.StoryRows) eventi precedenti</summary>
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Story.Skip(LearningView.StoryRows))
|
||||||
|
{
|
||||||
|
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private LearningView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
_currency = Shell.Effective((await Host.Services!.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await LearningView.LoadAsync(Host, Shell, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Gain(LearningVersion version, bool same, string currency) => version.Gain is not { } gain ? "—"
|
||||||
|
: Shell.Money(gain, currency, withSign: true) + (same || version.GainWithout is not { } without ? "" : $" (senza: {Shell.Money(without, currency, withSign: true)})");
|
||||||
|
|
||||||
|
private static string Badge(string state) => state switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "Non ancora partito",
|
||||||
|
LearningStates.Active => "Attivo",
|
||||||
|
LearningStates.Aside => "Messo da parte",
|
||||||
|
LearningStates.Manual => "Messo da parte da te",
|
||||||
|
_ => "In osservazione",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string BadgeIcon(string state) => state switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "clock",
|
||||||
|
LearningStates.Active => "check",
|
||||||
|
LearningStates.Aside => "alert",
|
||||||
|
LearningStates.Manual => "pause",
|
||||||
|
_ => "eye",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Share(int? points) => points is { } p ? p + "%" : "—";
|
||||||
|
|
||||||
|
private static string Error(decimal? value) => value is { } e ? Format.Number(e, 3) : "—";
|
||||||
|
|
||||||
|
private static string Move(double value) => Format.Percent((decimal)Math.Round(value * 100, 2), 2, withSign: true);
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
@@ -31,6 +31,8 @@
|
|||||||
"fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.",
|
"fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.",
|
||||||
"chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.",
|
"chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.",
|
||||||
"chiave-tolta" => "Chiave tolta.",
|
"chiave-tolta" => "Chiave tolta.",
|
||||||
|
"apprendimento" => "Impostazioni del modello salvate: valgono dalle prossime operazioni. Quelle già rimpicciolite restano così fino alla chiusura.",
|
||||||
|
"promozione" => "Promozione annullata: è tornata in carica la versione precedente.",
|
||||||
|
|
||||||
_ => "Fatto.",
|
_ => "Fatto.",
|
||||||
})</p>
|
})</p>
|
||||||
@@ -41,7 +43,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#modello">Modello</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<section class="panel" id="aspetto">
|
<section class="panel" id="aspetto">
|
||||||
@@ -405,6 +407,55 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="modello">
|
||||||
|
<h2>Modello</h2>
|
||||||
|
<p class="hint">Il modello non compra mai e non ingrandisce niente: quando avrà superato le sue prove potrà solo rimpicciolire, o non fare, un acquisto che giudica debole. Quanto debole lo decidi qui, in punti di probabilità sotto la frequenza con cui la strategia guadagna di solito. <a href="/apprendimento">Cosa sta facendo</a></p>
|
||||||
|
<form method="post" action="/azioni/modello" class="form-grid">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@foreach (var m in _model)
|
||||||
|
{
|
||||||
|
var definition = SettingsStore.Definition(m.Key);
|
||||||
|
<label>@ModelLabel(m.Key)
|
||||||
|
<select name="@m.Key" disabled="@(m.ReadOnly || Shell.IsDemo)">
|
||||||
|
@foreach (var choice in definition.Allowed!)
|
||||||
|
{
|
||||||
|
<option value="@choice" selected="@(choice == m.Value)">@ModelChoice(m.Key, choice)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
@if (m.ReadOnly)
|
||||||
|
{
|
||||||
|
<span class="hint">Fissato da @m.Source: si cambia lì.</span>
|
||||||
|
}
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
@if (_anyLive)
|
||||||
|
{
|
||||||
|
<p class="note">Una strategia usa soldi veri: per rimpicciolire meno, o mettere da parte il modello, servono la frase e la password.</p>
|
||||||
|
<label>Scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
}
|
||||||
|
<button class="btn" type="submit">Salva</button>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
<h3>Ultima promozione</h3>
|
||||||
|
@if (_undoTo is { } undo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/impostazioni" />
|
||||||
|
<button class="btn" type="submit" data-confirm="Torna in carica la versione @undo e quella di adesso viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||||
|
<span class="hint">Tornerebbe in carica la versione @undo.</span>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna promozione da annullare.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="panel" id="sicurezza">
|
<section class="panel" id="sicurezza">
|
||||||
<h2>Sicurezza</h2>
|
<h2>Sicurezza</h2>
|
||||||
@if (Shell.IsDemo)
|
@if (Shell.IsDemo)
|
||||||
@@ -536,6 +587,8 @@
|
|||||||
|
|
||||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||||
private readonly List<SettingValue> _newsRules = [];
|
private readonly List<SettingValue> _newsRules = [];
|
||||||
|
private readonly List<SettingValue> _model = [];
|
||||||
|
private int? _undoTo;
|
||||||
private readonly Dictionary<string, SettingValue> _llm = [];
|
private readonly Dictionary<string, SettingValue> _llm = [];
|
||||||
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
|
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
|
||||||
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
|
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
|
||||||
@@ -573,6 +626,12 @@
|
|||||||
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (var setting in Anubis.Learning.LearningSettings.All)
|
||||||
|
{
|
||||||
|
_model.Add(await services.Settings.GetAsync(setting.Key, ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
_undoTo = Shell.IsDemo ? null : await new Anubis.Learning.ModelStore(services.Db).UndoToAsync(ct);
|
||||||
foreach (var setting in Anubis.News.NewsModelSettings.All)
|
foreach (var setting in Anubis.News.NewsModelSettings.All)
|
||||||
{
|
{
|
||||||
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
|
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
|
||||||
@@ -656,6 +715,7 @@
|
|||||||
"fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.",
|
"fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.",
|
||||||
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
|
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
|
||||||
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
|
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
|
||||||
|
"promozione" => "Non c'è nessuna promozione da annullare.",
|
||||||
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
|
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
|
||||||
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
|
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
|
||||||
|
|
||||||
@@ -705,6 +765,13 @@
|
|||||||
</form>;
|
</form>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string ModelLabel(string key) => key == Anubis.Learning.LearningSettings.Full.Key ? "Acquisto intero fino a"
|
||||||
|
: key == Anubis.Learning.LearningSettings.Zero.Key ? "Nessun acquisto da" : "Il modello";
|
||||||
|
|
||||||
|
private static string ModelChoice(string key, string choice) => key == Anubis.Learning.LearningSettings.Aside.Key
|
||||||
|
? choice == "on" ? "Messo da parte: non conta" : "Al suo posto"
|
||||||
|
: choice == "0" ? "Solo alla frequenza di sempre o sopra" : choice + " punti sotto";
|
||||||
|
|
||||||
private static string ProviderName(string provider) => provider switch
|
private static string ProviderName(string provider) => provider switch
|
||||||
{
|
{
|
||||||
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
|
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
@inject IClock Clock
|
@inject IClock Clock
|
||||||
@using Anubis.Backtest
|
@using Anubis.Backtest
|
||||||
@using Anubis.Data
|
@using Anubis.Data
|
||||||
|
@using Anubis.Learning
|
||||||
@using Anubis.Strategies
|
@using Anubis.Strategies
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
<PageTitle>Laboratorio · Anubis</PageTitle>
|
<PageTitle>Laboratorio · Anubis</PageTitle>
|
||||||
|
|
||||||
@@ -173,10 +175,47 @@
|
|||||||
|
|
||||||
<section class="panel" aria-labelledby="stime">
|
<section class="panel" aria-labelledby="stime">
|
||||||
<h2 id="stime">Stime di costo da confermare</h2>
|
<h2 id="stime">Stime di costo da confermare</h2>
|
||||||
|
<p class="hint">Scostamento contato da simulatore e backtest: @string.Join("; ", SlippageTiers.All.Select(t => SlippageTiers.Label(t) + " " + Bp(_table.Of(t)))). Ogni mese si confronta con le esecuzioni ottenute dai broker, mai con quelle del simulatore. Una stima sale da sola; scende solo se viene da soldi veri e la confermi tu.</p>
|
||||||
|
@if (_costs.Where(c => c.Status == CostStatuses.Pending).ToList() is { Count: > 0 } pending)
|
||||||
|
{
|
||||||
|
@foreach (var c in pending)
|
||||||
|
{
|
||||||
|
<div class="row">
|
||||||
|
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (quasi certamente tra @Bp(c.LowBp) e @Bp(c.HighBp)). Un punto base è un centesimo di punto percentuale.</span></p>
|
||||||
|
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||||
|
<form method="post" action="/azioni/stime-di-costo/@c.Id/rifiuta" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Rifiuta</button></form>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
<div class="empty">
|
<div class="empty">
|
||||||
<p class="empty-title">Nessuna stima da confermare.</p>
|
<p class="empty-title">Nessuna stima da confermare.</p>
|
||||||
<p>Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma. Arrivano con la Fase 8.</p>
|
<p>Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma.</p>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
@if (_costs.Where(c => c.Status != CostStatuses.Pending).Reverse().Take(10).ToList() is { Count: > 0 } past)
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<caption class="sr-only">Stime di scostamento già decise</caption>
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Strumenti</th><th scope="col" class="num">Prima</th><th scope="col" class="num">Stima</th><th scope="col" class="num">Esecuzioni</th><th scope="col">Esito</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var c in past)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td class="nowrap">@Format.ShortDate(c.DecidedAt ?? c.CreatedAt, Shell.Now, Shell.Zone)</td>
|
||||||
|
<td>@Capital(SlippageTiers.Label(c.Tier))</td>
|
||||||
|
<td class="num">@Bp(c.PreviousBp)</td>
|
||||||
|
<td class="num">@Bp(c.Bp)</td>
|
||||||
|
<td class="num">@c.Cases</td>
|
||||||
|
<td>@Outcome(c.Status)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
@@ -188,6 +227,8 @@
|
|||||||
private DateOnly _from;
|
private DateOnly _from;
|
||||||
private DateOnly _to;
|
private DateOnly _to;
|
||||||
private IReadOnlyList<string> _research = [];
|
private IReadOnlyList<string> _research = [];
|
||||||
|
private IReadOnlyList<CostEstimate> _costs = [];
|
||||||
|
private SlippageTable _table = SlippageTable.Standard;
|
||||||
|
|
||||||
[CascadingParameter]
|
[CascadingParameter]
|
||||||
public HttpContext? HttpContext { get; set; }
|
public HttpContext? HttpContext { get; set; }
|
||||||
@@ -204,6 +245,9 @@
|
|||||||
var services = Host.Services!;
|
var services = Host.Services!;
|
||||||
_lab = services.Lab;
|
_lab = services.Lab;
|
||||||
_trials = await new TrialStore(services.Db, Clock).ListAsync(100, ct);
|
_trials = await new TrialStore(services.Db, Clock).ListAsync(100, ct);
|
||||||
|
var costs = new CostBook(services.Db, Clock);
|
||||||
|
_costs = await costs.ListAsync(ct);
|
||||||
|
_table = await costs.TableAsync(ct);
|
||||||
_running = _trials.Any(t => !t.IsFinished);
|
_running = _trials.Any(t => !t.IsFinished);
|
||||||
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||||
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||||
@@ -217,6 +261,7 @@
|
|||||||
_message = Errore switch
|
_message = Errore switch
|
||||||
{
|
{
|
||||||
null => null,
|
null => null,
|
||||||
|
"stima" => "Quella stima non aspetta più una conferma.",
|
||||||
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
||||||
TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.",
|
TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.",
|
||||||
TrialRequestErrors.Source => "Scegli da dove prendere i dati e, per le barre raccolte, il mercato.",
|
TrialRequestErrors.Source => "Scegli da dove prendere i dati e, per le barre raccolte, il mercato.",
|
||||||
@@ -229,6 +274,18 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string Bp(decimal bp) => Format.Quantity(Math.Round(bp, 1)) + " punti base";
|
||||||
|
|
||||||
|
private static string Capital(string text) => char.ToUpper(text[0], System.Globalization.CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Outcome(string status) => status switch
|
||||||
|
{
|
||||||
|
CostStatuses.Applied => "Salita da sola",
|
||||||
|
CostStatuses.Confirmed => "Confermata da te",
|
||||||
|
CostStatuses.Refused => "Rifiutata da te",
|
||||||
|
_ => "Superata dal mese dopo",
|
||||||
|
};
|
||||||
|
|
||||||
private string Research() => _research.Count == 0
|
private string Research() => _research.Count == 0
|
||||||
? "Lo storico di ricerca è vuoto: lo riempie la raccolta dei dati."
|
? "Lo storico di ricerca è vuoto: lo riempie la raccolta dei dati."
|
||||||
: "Nello storico di ricerca: " + LabText.Symbols(_research) + ".";
|
: "Nello storico di ricerca: " + LabText.Symbols(_research) + ".";
|
||||||
|
|||||||
@@ -364,19 +364,23 @@
|
|||||||
</section>
|
</section>
|
||||||
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
|
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
|
||||||
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
|
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
|
||||||
@if (p.Learning is not { } m)
|
@{ var m = p.Learning; }
|
||||||
|
<p><strong>@m.Sentence</strong></p>
|
||||||
|
@if (m.State == LearningStates.Observation)
|
||||||
{
|
{
|
||||||
<p class="note">L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.</p>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<p><strong>Il modello osserva e impara, ma non decide ancora.</strong></p>
|
|
||||||
<div class="limit">
|
<div class="limit">
|
||||||
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
|
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
|
||||||
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
|
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
@if (m.State == LearningStates.None)
|
||||||
|
{
|
||||||
|
<p class="note">@m.NextLabel: @m.NextCheck.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
<dl class="tile-facts">
|
<dl class="tile-facts">
|
||||||
<dt>Previsioni azzeccate</dt><dd>@m.Precision% su dati mai visti</dd>
|
<dt>Previsioni azzeccate</dt><dd>@(m.Precision is { } hit ? $"{hit}% su dati mai visti" : "non ancora misurate")</dd>
|
||||||
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
|
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
|
||||||
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
|
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
@* The precision of the model week by week with the alarm line (SPEC 13.6, mockup 06). Weeks without enough cases leave no
|
||||||
|
point; the days on the axis keep the distance between the others. *@
|
||||||
|
@if (Weeks.Count >= 2)
|
||||||
|
{
|
||||||
|
var alarm = (decimal)(Anubis.Learning.Health.Alarm * 100);
|
||||||
|
var lo = Math.Min(Weeks.Min(w => w.Precision), alarm) - 4m;
|
||||||
|
var hi = Math.Max(Weeks.Max(w => w.Precision), alarm) + 4m;
|
||||||
|
var (first, last) = (Weeks[0], Weeks[^1]);
|
||||||
|
var lowest = Weeks.MinBy(w => w.Precision)!;
|
||||||
|
decimal X(LearningWeek w) => (w.Monday.DayNumber - first.Monday.DayNumber) * 1000m / (last.Monday.DayNumber - first.Monday.DayNumber);
|
||||||
|
decimal Y(decimal v) => (hi - v) / (hi - lo) * 1000m;
|
||||||
|
<figure class="weekly" aria-label="Precisione settimana per settimana">
|
||||||
|
<figcaption class="note">Precisione settimana per settimana</figcaption>
|
||||||
|
<div class="weekly-box">
|
||||||
|
<div class="chart-plot">
|
||||||
|
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||||
|
<line class="bench" x1="0" x2="1000" y1="@Css(Y(alarm))" y2="@Css(Y(alarm))" vector-effect="non-scaling-stroke" />
|
||||||
|
<polyline class="equity" points="@string.Join(" ", Weeks.Select(w => Css(X(w)) + "," + Css(Y(w.Precision))))" vector-effect="non-scaling-stroke" />
|
||||||
|
</svg>
|
||||||
|
@foreach (var w in Weeks)
|
||||||
|
{
|
||||||
|
<span class="end-dot hover-dot @(w == last || w == lowest ? null : "quiet")" style="left:@Pct(X(w) / 10);top:@Pct(Y(w.Precision) / 10)"><span class="hover-box">Settimana del @Day(w.Monday)<br />@w.Precision%</span></span>
|
||||||
|
}
|
||||||
|
@if (lowest != last)
|
||||||
|
{
|
||||||
|
<span class="point-label under" style="left:@Pct(X(lowest) / 10);top:@Pct(Y(lowest.Precision) / 10)">@lowest.Precision%</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="weekly-side" aria-hidden="true">
|
||||||
|
<strong style="top:@Pct(Math.Min(Y(last.Precision), Y(alarm) - 300m) / 10)">@last.Precision%</strong>
|
||||||
|
<span style="top:@Pct(Y(alarm) / 10)">allarme<br />sotto @Format.Number(alarm)%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="weekly-x note" aria-hidden="true"><span>@Day(first.Monday)</span><span>@Day(last.Monday)</span></div>
|
||||||
|
<details class="chart-table">
|
||||||
|
<summary>Vedi i numeri in una tabella</summary>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Settimana dal lunedì</th><th scope="col" class="num">Precisione</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var w in Weeks.Reverse())
|
||||||
|
{
|
||||||
|
<tr><td>@Format.LongDate(w.Monday)</td><td class="num">@w.Precision%</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</figure>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired]
|
||||||
|
public IReadOnlyList<LearningWeek> Weeks { get; set; } = [];
|
||||||
|
|
||||||
|
private static string Day(DateOnly day) => day.ToString("d MMM", CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||||
|
}
|
||||||
@@ -140,6 +140,12 @@ internal static partial class Endpoints
|
|||||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The same for what lets the model shrink less.
|
||||||
|
if (Anubis.Learning.LearningSettings.All.Any(d => d.Key == key))
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||||
|
}
|
||||||
|
|
||||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,9 @@ internal static partial class Forms
|
|||||||
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
|
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
|
||||||
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
|
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
|
||||||
signed.MapPost("/laboratorio", PlanTrialAsync);
|
signed.MapPost("/laboratorio", PlanTrialAsync);
|
||||||
|
signed.MapPost("/stime-di-costo/{id:guid}/{choice}", DecideCostAsync);
|
||||||
|
signed.MapPost("/modello", SetModelAsync);
|
||||||
|
signed.MapPost("/modello/annulla-promozione", UndoPromotionAsync);
|
||||||
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
||||||
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
||||||
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
||||||
@@ -108,7 +111,8 @@ internal static partial class Forms
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
|
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
|
||||||
private static async Task<IResult> AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct)
|
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
||||||
|
private static async Task<IResult> AbsenceSeenAsync(Guid id, IFormCollection form, AnubisHost host, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (!host.IsDemo && host.Services is { } services)
|
if (!host.IsDemo && host.Services is { } services)
|
||||||
{
|
{
|
||||||
@@ -764,6 +768,84 @@ internal static partial class Forms
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6). The form is bound for the antiforgery check.</summary>
|
||||||
|
private static async Task<IResult> DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta"))
|
||||||
|
{
|
||||||
|
return Results.Redirect("/laboratorio?errore=motore#stime");
|
||||||
|
}
|
||||||
|
|
||||||
|
var book = new Anubis.Learning.CostBook(services.Db, host.Clock);
|
||||||
|
var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||||
|
if (done && services.Trading is { } trading)
|
||||||
|
{
|
||||||
|
await trading.RefreshCostsAsync(ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Redirect(done ? "/laboratorio#stime" : "/laboratorio?errore=stima#stime");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The thresholds of the multiplier and the manual set-aside (SPEC 13.5), all at once. A choice that lets operations be
|
||||||
|
/// bigger while a strategy has real money needs the phrase and the password, like a risk limit (SPEC 12.4).
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<IResult> SetModelAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
const string back = "/impostazioni";
|
||||||
|
if (host.IsDemo || host.Services is not { } services)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=motore#modello");
|
||||||
|
}
|
||||||
|
|
||||||
|
var current = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
foreach (var definition in Anubis.Learning.LearningSettings.All)
|
||||||
|
{
|
||||||
|
var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false);
|
||||||
|
current[definition.Key] = value.Value;
|
||||||
|
var chosen = form[definition.Key].ToString();
|
||||||
|
if (value.ReadOnly || chosen.Length == 0)
|
||||||
|
{
|
||||||
|
next[definition.Key] = value.Value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!definition.Allowed!.Contains(chosen, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=impostazione#modello");
|
||||||
|
}
|
||||||
|
|
||||||
|
next[definition.Key] = chosen;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Anubis.Learning.LearningSettings.Raised(k => current[k], k => next[k]) && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=" + refusal + "#modello");
|
||||||
|
}
|
||||||
|
|
||||||
|
var by = context.User.Identity?.Name ?? "utente";
|
||||||
|
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
|
||||||
|
{
|
||||||
|
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Redirect(back + "?ok=apprendimento#modello");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One click takes back the last promotion (SPEC 11.4).</summary>
|
||||||
|
private static async Task<IResult> UndoPromotionAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (page, anchor) = Back(form, "/apprendimento") == "/impostazioni" ? ("/impostazioni", "#modello") : ("/apprendimento", "");
|
||||||
|
if (host.IsDemo || host.Services is not { } services)
|
||||||
|
{
|
||||||
|
return Results.Redirect(page + "?errore=motore" + anchor);
|
||||||
|
}
|
||||||
|
|
||||||
|
var done = await Anubis.Learning.LearningCycle.UndoPromotionAsync(services.Db, host.Clock, ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect(page + (done ? "?ok=promozione" : "?errore=promozione") + anchor);
|
||||||
|
}
|
||||||
|
|
||||||
private static DateOnly? ParseDay(string text) =>
|
private static DateOnly? ParseDay(string text) =>
|
||||||
DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null;
|
DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Learning;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "anubis learning base": the first model (SPEC 11.2, issue #63). It rebuilds the examples of <c>crypto_trend</c> on the
|
||||||
|
/// history that "anubis backtest base" already downloaded and converted, trains, and writes the validation report and the
|
||||||
|
/// file that travels with the program. It never uses the network. The stock strategies wait for the Alpaca history.
|
||||||
|
/// </summary>
|
||||||
|
internal static class LearningCommand
|
||||||
|
{
|
||||||
|
private const string Usage =
|
||||||
|
"Uso: anubis learning base [--to AAAA-MM-GG] [--out docs/learning]\n" +
|
||||||
|
" Usa gli storici già scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||||
|
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 1 || args[0] != "base")
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rest = args[1..].ToList();
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
|
||||||
|
var now = new SystemClock().UtcNow;
|
||||||
|
var to = Option(rest, "--to") is { } t ? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture) : new DateOnly(now.Year, now.Month, 1).AddDays(-1);
|
||||||
|
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "learning"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(outDir);
|
||||||
|
var file = await FirstModel.BuildAsync(config.Data.Research, to, null, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.json"), FirstModel.ToJson(file)).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.md"),
|
||||||
|
FirstModel.Markdown(file, "anubis learning base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{file.Examples.Count} esempi, {file.Examples.Count(e => e.IsLabelled)} con un esito. ")
|
||||||
|
+ (file.Report is { } report ? report.Reason : "Nessun modello: esempi troppo pochi.")).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync("Rapporto scritto in " + outDir).ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or InvalidOperationException or FormatException or UnauthorizedAccessException or InvalidDataException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(List<string> args, string name)
|
||||||
|
{
|
||||||
|
var index = args.IndexOf(name);
|
||||||
|
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Learning;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>What the model is doing, for the badge and the sentences at the top.</summary>
|
||||||
|
internal static class LearningStates
|
||||||
|
{
|
||||||
|
/// <summary>No model yet: the night after the first start prepares it.</summary>
|
||||||
|
public const string None = "none";
|
||||||
|
|
||||||
|
public const string Observation = "observation";
|
||||||
|
public const string Active = "active";
|
||||||
|
|
||||||
|
/// <summary>Set aside on its own by the nightly check.</summary>
|
||||||
|
public const string Aside = "aside";
|
||||||
|
|
||||||
|
/// <summary>Set aside by the user.</summary>
|
||||||
|
public const string Manual = "manual";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A band of estimates: percentages as they are read, the point at the mean estimate.</summary>
|
||||||
|
public sealed record LearningBand(int From, int To, int Cases, decimal Estimated, decimal Observed)
|
||||||
|
{
|
||||||
|
public bool Solid => Cases >= Judge.BandMin;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record LearningWeight(string Name, int Share, bool Rest);
|
||||||
|
|
||||||
|
/// <summary>A column of the comparison between the model in charge and the one on trial.</summary>
|
||||||
|
internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout);
|
||||||
|
|
||||||
|
/// <summary>What was tried when a model was trained, the chosen one included.</summary>
|
||||||
|
internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen);
|
||||||
|
|
||||||
|
public sealed record LearningWeek(DateOnly Monday, int Precision);
|
||||||
|
|
||||||
|
/// <summary>A line of "Sorveglianza": <paramref name="State"/> is ok, warn or wait.</summary>
|
||||||
|
internal sealed record LearningCheck(string State, string Text);
|
||||||
|
|
||||||
|
internal sealed record LearningStory(string When, string Text);
|
||||||
|
|
||||||
|
/// <summary>The model box of the Panoramica: the same state in few words.</summary>
|
||||||
|
internal sealed record LearningSummary(string State, int Signals, int Needed, int? Precision, string Trained, string NextLabel, string NextCheck)
|
||||||
|
{
|
||||||
|
public string Sentence => State switch
|
||||||
|
{
|
||||||
|
LearningStates.None => "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.",
|
||||||
|
LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.",
|
||||||
|
LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.",
|
||||||
|
LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.",
|
||||||
|
_ => "Il modello osserva e impara, ma non decide ancora.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Apprendimento screen (SPEC 13.6, mockup 06): what the model is doing, whether its probabilities can be trusted,
|
||||||
|
/// what it looks at, the model in charge against the challenger, the watch, the discoveries and the history. In demo mode
|
||||||
|
/// the numbers of appendix F.7 come from the aggregates.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record LearningView
|
||||||
|
{
|
||||||
|
/// <summary>The clues named one by one; the others are "Tutto il resto".</summary>
|
||||||
|
public const int NamedWeights = 9;
|
||||||
|
|
||||||
|
public const int StoryRows = 12;
|
||||||
|
|
||||||
|
private const string Fear = "Paura o avidità";
|
||||||
|
|
||||||
|
/// <summary>The pace is measured on the last four weeks, and needs at least one.</summary>
|
||||||
|
private const int PaceDays = 28;
|
||||||
|
|
||||||
|
private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
private static readonly string[] _numbers = ["zero", "una", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici"];
|
||||||
|
|
||||||
|
public required LearningSummary Summary { get; init; }
|
||||||
|
|
||||||
|
public required string Title { get; init; }
|
||||||
|
|
||||||
|
public required string Text { get; init; }
|
||||||
|
|
||||||
|
public string? Pace { get; init; }
|
||||||
|
|
||||||
|
/// <summary>With 300 signals done, what still stops it from counting.</summary>
|
||||||
|
public IReadOnlyList<string> Missing { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>"domenica 4 ottobre, versione 3".</summary>
|
||||||
|
public required string LastTraining { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningBand> Bands { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>The sentence under the calibration chart.</summary>
|
||||||
|
public string BandsText { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>True when the bands are those of the verification on the history, because the live ones are still too few.</summary>
|
||||||
|
public bool BandsFromHistory { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningWeight> Weights { get; init; } = [];
|
||||||
|
|
||||||
|
public string WeightsText { get; init; } = "";
|
||||||
|
|
||||||
|
public LearningVersion? Champion { get; init; }
|
||||||
|
|
||||||
|
public LearningVersion? Challenger { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The signals both estimated, with their outcome, and how many the next decision needs.</summary>
|
||||||
|
public int Pairs { get; init; }
|
||||||
|
|
||||||
|
public int PairsNeeded { get; init; }
|
||||||
|
|
||||||
|
/// <summary>No strategy with capital had examples when the model in charge was trained.</summary>
|
||||||
|
public bool GainOnReference { get; init; }
|
||||||
|
|
||||||
|
public string TrialTitle { get; init; } = "";
|
||||||
|
|
||||||
|
public string TrialText { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>How the model in charge was chosen, with everything that was tried.</summary>
|
||||||
|
public string? Choice { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningAttempt> Attempts { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Set when the last promotion can be taken back: the version that would return.</summary>
|
||||||
|
public int? UndoTo { get; init; }
|
||||||
|
|
||||||
|
public bool Anomaly { get; init; }
|
||||||
|
|
||||||
|
public bool Checked { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningCheck> Checks { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningWeek> Weeks { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<LearningStory> Story { get; init; } = [];
|
||||||
|
|
||||||
|
// ---- Panoramica ---------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The few numbers of the Panoramica.</summary>
|
||||||
|
public static async Task<LearningSummary> SummaryAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(shell);
|
||||||
|
using var aggregates = shell.Aggregates();
|
||||||
|
if (aggregates is not null)
|
||||||
|
{
|
||||||
|
return DemoSummary(aggregates.RootElement.GetProperty("apprendimento"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var services = host.Services!;
|
||||||
|
var desk = new LearningDesk(services.Db, host.Clock, services.Settings);
|
||||||
|
var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningSummary Summarise(IReadOnlyList<ModelRow> models, int evaluated, CycleState state, bool aside, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
|
||||||
|
var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
|
||||||
|
var last = models.LastOrDefault(m => m.Version is not null);
|
||||||
|
var status = champion is null ? LearningStates.None
|
||||||
|
: aside ? LearningStates.Manual
|
||||||
|
: state.Aside is not null ? LearningStates.Aside
|
||||||
|
: state.ActivatedAt is not null ? LearningStates.Active
|
||||||
|
: LearningStates.Observation;
|
||||||
|
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now),
|
||||||
|
champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningSummary DemoSummary(JsonElement demo) => new(demo.GetProperty("stato").GetString()!, demo.GetProperty("segnali").GetInt32(), demo.GetProperty("necessari").GetInt32(),
|
||||||
|
demo.GetProperty("precisione_pct").GetInt32(), demo.GetProperty("ultimo_addestramento").GetString()!, "Prossima verifica dello sfidante", demo.GetProperty("prossima_verifica").GetString()!);
|
||||||
|
|
||||||
|
// ---- Page ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static async Task<LearningView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(host);
|
||||||
|
ArgumentNullException.ThrowIfNull(shell);
|
||||||
|
using var aggregates = shell.Aggregates();
|
||||||
|
if (aggregates is not null)
|
||||||
|
{
|
||||||
|
return Demo(aggregates.RootElement.GetProperty("apprendimento"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var services = host.Services!;
|
||||||
|
var clock = host.Clock;
|
||||||
|
var desk = new LearningDesk(services.Db, clock, services.Settings);
|
||||||
|
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
|
||||||
|
var capitals = await LearningCycle.CapitalsAsync(services.Db, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return Of(snapshot, desk.BaseRates, capitals, aside, found, events, clock.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The page from what was read, without touching the database.</summary>
|
||||||
|
public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capitals, bool aside, DiscoverySet discoveries,
|
||||||
|
IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(snapshot);
|
||||||
|
ArgumentNullException.ThrowIfNull(discoveries);
|
||||||
|
ArgumentNullException.ThrowIfNull(events);
|
||||||
|
var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State);
|
||||||
|
var inCharge = snapshot.InCharge;
|
||||||
|
var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now);
|
||||||
|
var activation = ActivationCheck.Of(inCharge, baseRates, capitals);
|
||||||
|
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
|
||||||
|
var (title, text) = Words(summary, state, now);
|
||||||
|
|
||||||
|
// What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene".
|
||||||
|
var live = Judge.Bands(inCharge);
|
||||||
|
var history = !live.Any(b => b.Cases >= Judge.BandMin);
|
||||||
|
var verified = Verified(champion);
|
||||||
|
var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList();
|
||||||
|
var view = new LearningView
|
||||||
|
{
|
||||||
|
Summary = summary,
|
||||||
|
Title = title,
|
||||||
|
Text = text,
|
||||||
|
Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null,
|
||||||
|
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
|
||||||
|
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
|
||||||
|
Bands = bands,
|
||||||
|
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands, history ? null : activation.CalibrationError),
|
||||||
|
BandsFromHistory = history && bands.Count > 0,
|
||||||
|
Champion = Column(champion, now),
|
||||||
|
Challenger = Column(challenger, now),
|
||||||
|
Choice = champion?.Report.Reason is { Length: > 0 } reason ? reason : null,
|
||||||
|
Attempts = champion is null ? [] :
|
||||||
|
[
|
||||||
|
.. champion.Report.Attempts.Select(a =>
|
||||||
|
new LearningAttempt(LearnerNames.Label(a.Learner), Points(a.Combined.Precision), Round(a.Combined.Brier, 3), Round(a.Combined.GainWith, 2), a.Chosen)),
|
||||||
|
],
|
||||||
|
UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null,
|
||||||
|
Anomaly = state.Aside is not null,
|
||||||
|
Checked = state.Health is not null,
|
||||||
|
GainOnReference = champion?.Report.AllStrategiesCounted == true,
|
||||||
|
Found = discoveries.Found,
|
||||||
|
News = discoveries.News,
|
||||||
|
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
|
||||||
|
};
|
||||||
|
view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []);
|
||||||
|
if (champion is not null)
|
||||||
|
{
|
||||||
|
view = view with
|
||||||
|
{
|
||||||
|
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Health.Shown(w.Precision)))],
|
||||||
|
Checks = state.Health is not { } health ? []
|
||||||
|
: health.Version is { } seen && seen != champion.Version ? [new("wait", "Il modello in carica è cambiato: il primo controllo è alle 03:00. " + AlarmText(events, now))]
|
||||||
|
: ChecksOf(health, snapshot, champion, verified, events, now),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return champion is not null && challenger is not null
|
||||||
|
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), challenger.ThresholdDone, summary.NextCheck, champion.Version, challenger.Version)
|
||||||
|
: view with
|
||||||
|
{
|
||||||
|
TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.",
|
||||||
|
TrialText = champion is null ? "" : $"Il prossimo si addestra {At(summary.NextCheck)}, se nel frattempo ci sono casi nuovi.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero.";
|
||||||
|
const string Limits = "Non potrà mai ingrandirle, né aprirne di sue.";
|
||||||
|
const string Alone = "Le strategie proseguono senza di lui.";
|
||||||
|
return summary.State switch
|
||||||
|
{
|
||||||
|
LearningStates.None => ("Non ha ancora cominciato.", $"{How} La prima verifica, {At(summary.NextCheck)}, prepara il primo modello dai dati storici; da lì parte in osservazione."),
|
||||||
|
LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.",
|
||||||
|
$"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."),
|
||||||
|
LearningStates.Aside => ("Per ora è messo da parte.",
|
||||||
|
$"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."),
|
||||||
|
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione nuova; quelle già rimpicciolite restano così fino alla chiusura. Si riattiva da Impostazioni."),
|
||||||
|
_ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.",
|
||||||
|
$"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"),
|
||||||
|
_ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How long the missing signals take at the pace of the last four weeks.</summary>
|
||||||
|
public static string? PaceText(IReadOnlyList<Estimate> inCharge, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(inCharge);
|
||||||
|
var missing = ActivationCheck.Needed - inCharge.Count;
|
||||||
|
if (missing <= 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var today = DayOf(now);
|
||||||
|
if (inCharge.Count == 0 || (today.DayNumber - inCharge.Min(e => e.Case.Label!.ClosedDay!.Value).DayNumber) is not (>= 7 and var seen))
|
||||||
|
{
|
||||||
|
return "È presto per dire quanto manca.";
|
||||||
|
}
|
||||||
|
|
||||||
|
var days = Math.Min(PaceDays, seen);
|
||||||
|
var recent = inCharge.Count(e => e.Case.Label!.ClosedDay!.Value > today.AddDays(-days));
|
||||||
|
return recent == 0 ? "Nelle ultime settimane nessun segnale si è concluso." : PaceWords(missing * days / 7.0 / recent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing.</summary>
|
||||||
|
public static string PaceWords(double weeks)
|
||||||
|
{
|
||||||
|
if (weeks <= 1)
|
||||||
|
{
|
||||||
|
return "Al ritmo attuale, meno di una settimana.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (weeks > 52)
|
||||||
|
{
|
||||||
|
return "Al ritmo attuale, più di un anno.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (weeks > 12)
|
||||||
|
{
|
||||||
|
return string.Create(_it, $"Al ritmo attuale, circa {Math.Round(weeks / 4.345):0} mesi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var (low, high) = ((int)Math.Floor(weeks), (int)Math.Ceiling(weeks));
|
||||||
|
return low == high ? $"Al ritmo attuale, circa {_numbers[low]} settimane." : $"Al ritmo attuale, tra {_numbers[low]} e {_numbers[high]} settimane.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> Missings(ActivationCheck check)
|
||||||
|
{
|
||||||
|
var missing = new List<string>();
|
||||||
|
if (!check.Calibrated)
|
||||||
|
{
|
||||||
|
missing.Add(check.CalibrationError is { } error
|
||||||
|
? string.Create(_it, $"Le probabilità non sono ancora ben tarate: sbagliano in media di {error * 100:0.0} punti, il massimo è {ActivationCheck.MaxCalibrationError * 100:0}.")
|
||||||
|
: $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (check.Funded < ActivationCheck.FundedNeeded)
|
||||||
|
{
|
||||||
|
missing.Add($"Servono almeno {ActivationCheck.FundedNeeded} segnali di strategie con un capitale, anche in simulazione: per ora {(check.Funded == 1 ? "è uno" : $"sono {Format.Number(check.Funded)}")}.");
|
||||||
|
}
|
||||||
|
else if (!check.Improves)
|
||||||
|
{
|
||||||
|
missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Calibration and clues ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not
|
||||||
|
/// count. <paramref name="measured"/> is the error of the criterion to start counting (11.5), when it is the judge.
|
||||||
|
/// </summary>
|
||||||
|
public static string BandsWords(IReadOnlyList<LearningBand> bands, double? measured = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(bands);
|
||||||
|
var solid = bands.Where(b => b.Solid).ToList();
|
||||||
|
if (solid.Count == 0)
|
||||||
|
{
|
||||||
|
return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci.";
|
||||||
|
}
|
||||||
|
|
||||||
|
var error = measured is { } known ? Round(known * 100, 1) : solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
|
||||||
|
var best = solid[^1];
|
||||||
|
var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " +
|
||||||
|
((measured is { } exact ? exact < ActivationCheck.MaxCalibrationError : error < (decimal)ActivationCheck.MaxCalibrationError * 100) ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
|
||||||
|
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
|
||||||
|
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
|
||||||
|
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
|
||||||
|
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : Format.Number(cases) + " casi, troppo pochi")} per contarci.";
|
||||||
|
return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") +
|
||||||
|
(between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights)
|
||||||
|
{
|
||||||
|
var rest = weights.Skip(NamedWeights).Sum(w => w.Share);
|
||||||
|
var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList();
|
||||||
|
if (rest > 0)
|
||||||
|
{
|
||||||
|
rows.Add(new LearningWeight("Tutto il resto", rest, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share);
|
||||||
|
var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share);
|
||||||
|
var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
|
||||||
|
: news + fear == 0 && weights.Any(w => Clues.NewsGroups.Contains(w.Name) || w.Name == Fear) ? "Notizie, paura e avidità le studia già, ma per ora non pesano."
|
||||||
|
: news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono."
|
||||||
|
: news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100."
|
||||||
|
: $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100.";
|
||||||
|
return view with { Weights = rows, WeightsText = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Versions -----------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The scores of a model on the cases it had not studied, from the verification of its training.</summary>
|
||||||
|
private static Scores? Verified(ModelRow? model) => model?.Report.Attempts.FirstOrDefault(a => a.Chosen)?.Combined;
|
||||||
|
|
||||||
|
private static LearningVersion? Column(ModelRow? model, DateTimeOffset now) => model?.Version is not { } version ? null
|
||||||
|
: Verified(model) is { Cases: > 0 } s
|
||||||
|
? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2))
|
||||||
|
: new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null);
|
||||||
|
|
||||||
|
/// <param name="done">The last threshold already judged: at the next one, passed or not, there is a decision (SPEC 11.4).</param>
|
||||||
|
private static LearningView WithTrial(LearningView view, TrialCheck check, int done, string nextCheck, int? champion, int? challenger)
|
||||||
|
{
|
||||||
|
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, TrialCheck.Thresholds[^1]);
|
||||||
|
var first = TrialCheck.Thresholds[0];
|
||||||
|
var text = check.Pairs switch
|
||||||
|
{
|
||||||
|
0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||||
|
_ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " +
|
||||||
|
$"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||||
|
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. {(check.Pairs >= next ? $"Si decide {At(nextCheck)}" : $"Si decide di nuovo a {next} casi")}: " +
|
||||||
|
$"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.",
|
||||||
|
};
|
||||||
|
return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Watch --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static List<LearningCheck> ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var known = champion.Model is { } model ? snapshot.Examples.Count(e => e.Source == CaseSources.Live && model.Strategies.Contains(e.Strategy)) : 0;
|
||||||
|
var checks = new List<LearningCheck>
|
||||||
|
{
|
||||||
|
health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it))
|
||||||
|
: known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}")
|
||||||
|
: new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||||
|
PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)),
|
||||||
|
};
|
||||||
|
if (health.ErrorDrift)
|
||||||
|
{
|
||||||
|
checks.Add(new("warn", "I suoi errori sono aumentati negli ultimi casi"));
|
||||||
|
}
|
||||||
|
|
||||||
|
checks.Add(new("wait", $"Ultimo controllo {Moment(health.At, now)}. {AlarmText(events, now)}"));
|
||||||
|
return checks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LearningCheck PrecisionCheck(int? precision, int cases, int? expected)
|
||||||
|
{
|
||||||
|
if (precision is not { } seen || cases < Health.MinCases)
|
||||||
|
{
|
||||||
|
return new("wait", cases == 0 ? $"Nessun segnale concluso: la precisione si giudica da {Health.MinCases} casi" : $"Segnali conclusi: {cases}. La precisione si giudica da {Health.MinCases} casi");
|
||||||
|
}
|
||||||
|
|
||||||
|
var against = expected is not { } e ? "" : Math.Abs(seen - e) <= 5 ? $", in linea con il {e}% atteso" : seen < e ? $", sotto il {e}% atteso" : $", sopra il {e}% atteso";
|
||||||
|
return new(seen < Health.Alarm * 100 ? "warn" : "ok", $"Precisione sugli ultimi {cases} casi: {seen}%{against}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string AlarmText(IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
if (events.LastOrDefault(e => e.Kind == ModelEvents.SetAside) is not { } alarm)
|
||||||
|
{
|
||||||
|
return "Nessun allarme finora";
|
||||||
|
}
|
||||||
|
|
||||||
|
var back = events.FirstOrDefault(e => e.Kind == ModelEvents.Back && e.At >= alarm.At);
|
||||||
|
var days = back is null ? 0 : Math.Max(1, (int)Math.Round((back.At - alarm.At).TotalDays));
|
||||||
|
return $"Ultimo allarme il {DayText(DayOf(alarm.At), now)}, {(back is null ? "ancora in corso" : days == 1 ? "rientrato in un giorno" : $"rientrato in {days} giorni")}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Demo ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static LearningView Demo(JsonElement demo)
|
||||||
|
{
|
||||||
|
static decimal Amount(JsonElement e, string name) => decimal.Parse(e.GetProperty(name).GetString()!, CultureInfo.InvariantCulture);
|
||||||
|
LearningVersion Version(string name)
|
||||||
|
{
|
||||||
|
var v = demo.GetProperty(name);
|
||||||
|
return new LearningVersion(v.GetProperty("versione").GetInt32(), v.GetProperty("addestrato").GetString()!, v.GetProperty("casi").GetInt32(), v.GetProperty("precisione_pct").GetInt32(),
|
||||||
|
Amount(v, "errore"), Amount(v, "guadagno"), Amount(demo, "guadagno_senza_filtro"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var summary = DemoSummary(demo);
|
||||||
|
var champion = Version("in_carica");
|
||||||
|
var challenger = Version("sfidante");
|
||||||
|
var watch = demo.GetProperty("sorveglianza");
|
||||||
|
var (title, text) = Words(summary, new CycleState(), DateTimeOffset.MinValue);
|
||||||
|
var view = new LearningView
|
||||||
|
{
|
||||||
|
Summary = summary,
|
||||||
|
Title = title,
|
||||||
|
Text = text,
|
||||||
|
Pace = PaceWords(demo.GetProperty("settimane_mancanti").GetDouble()),
|
||||||
|
LastTraining = $"{summary.Trained}, versione {challenger.Version}",
|
||||||
|
Bands =
|
||||||
|
[
|
||||||
|
.. demo.GetProperty("fasce").EnumerateArray().Select(b => (From: b.GetProperty("da").GetInt32(), To: b.GetProperty("a").GetInt32(), Band: b))
|
||||||
|
.Select(b => new LearningBand(b.From, b.To, b.Band.GetProperty("casi").GetInt32(), (b.From + b.To) / 2m, b.Band.GetProperty("pct").GetInt32())),
|
||||||
|
],
|
||||||
|
BandsText = demo.GetProperty("fasce_testo").GetString()!,
|
||||||
|
Champion = champion,
|
||||||
|
Challenger = challenger,
|
||||||
|
Checked = true,
|
||||||
|
Checks =
|
||||||
|
[
|
||||||
|
new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||||
|
PrecisionCheck(watch.GetProperty("precisione_pct").GetInt32(), watch.GetProperty("casi").GetInt32(), champion.Precision),
|
||||||
|
new("wait", watch.GetProperty("controllo").GetString()!),
|
||||||
|
],
|
||||||
|
Weeks = [.. watch.GetProperty("settimane").EnumerateArray().Select(w => new LearningWeek(DateOnly.Parse(w.GetProperty("lunedi").GetString()!, CultureInfo.InvariantCulture), w.GetProperty("pct").GetInt32()))],
|
||||||
|
Found = [.. demo.GetProperty("scoperte").EnumerateArray().Select(d => new Discovery(d.GetProperty("titolo").GetString()!, d.GetProperty("dettaglio").GetString()!, d.GetProperty("casi").GetInt32()))],
|
||||||
|
Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))],
|
||||||
|
};
|
||||||
|
var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList();
|
||||||
|
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Words --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model.</summary>
|
||||||
|
private static string NextText(DateTimeOffset now, bool sunday)
|
||||||
|
{
|
||||||
|
var local = TimeZoneInfo.ConvertTime(now, Zones.Rome);
|
||||||
|
var today = DateOnly.FromDateTime(local.DateTime);
|
||||||
|
var day = local.Hour < 3 ? today : today.AddDays(1);
|
||||||
|
if (sunday)
|
||||||
|
{
|
||||||
|
day = day.AddDays((7 - (int)day.DayOfWeek) % 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Format.Day(day) + ", 03:00";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"domenica 11 ottobre alle 03:00" from the short form.</summary>
|
||||||
|
private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>"oggi alle 03:00", "il 4 ottobre alle 03:00".</summary>
|
||||||
|
private static string Moment(DateTimeOffset at, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
var time = TimeZoneInfo.ConvertTime(at, Zones.Rome).ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||||
|
return (DayOf(now).DayNumber - DayOf(at).DayNumber) switch
|
||||||
|
{
|
||||||
|
0 => $"oggi alle {time}",
|
||||||
|
1 => $"ieri alle {time}",
|
||||||
|
_ => $"il {DayText(DayOf(at), now)} alle {time}",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome);
|
||||||
|
|
||||||
|
/// <summary>"domenica 4 ottobre", with the year when it is another one.</summary>
|
||||||
|
private static string LongDay(DateOnly day, DateTimeOffset now) => Format.Day(day) + (day.Year == DayOf(now).Year ? "" : day.ToString(" yyyy", CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
/// <summary>"4 ottobre", with the year when it is another one.</summary>
|
||||||
|
private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day);
|
||||||
|
|
||||||
|
private static int? Points(double? share) => share is { } s ? (int)Math.Round(s * 100, MidpointRounding.AwayFromZero) : null;
|
||||||
|
|
||||||
|
private static decimal Round(double value, int decimals) => Math.Round((decimal)value, decimals, MidpointRounding.AwayFromZero);
|
||||||
|
}
|
||||||
@@ -14,8 +14,6 @@ internal sealed record AccountTrend(decimal Month, IReadOnlyList<decimal> Points
|
|||||||
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
|
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
|
||||||
|
|
||||||
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
|
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
|
||||||
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
|
|
||||||
|
|
||||||
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
|
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
|
||||||
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
|
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
|
||||||
|
|
||||||
@@ -39,7 +37,7 @@ internal sealed record PanoramaView(
|
|||||||
IReadOnlyList<LastAction>? DemoLast,
|
IReadOnlyList<LastAction>? DemoLast,
|
||||||
string? NextDecision,
|
string? NextDecision,
|
||||||
IReadOnlyList<PanoramaNews>? News,
|
IReadOnlyList<PanoramaNews>? News,
|
||||||
PanoramaLearning? Learning,
|
LearningSummary Learning,
|
||||||
DateTimeOffset? FractionStops)
|
DateTimeOffset? FractionStops)
|
||||||
{
|
{
|
||||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||||
@@ -93,12 +91,13 @@ internal sealed record PanoramaView(
|
|||||||
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
|
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
|
||||||
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
|
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
|
||||||
|
|
||||||
|
var learning = await LearningView.SummaryAsync(host, shell, cancellationToken).ConfigureAwait(false);
|
||||||
using var aggregates = shell.Aggregates();
|
using var aggregates = shell.Aggregates();
|
||||||
if (aggregates is null)
|
if (aggregates is null)
|
||||||
{
|
{
|
||||||
var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||||
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone),
|
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone),
|
||||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), null, fractions);
|
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions);
|
||||||
}
|
}
|
||||||
|
|
||||||
var root = aggregates.RootElement;
|
var root = aggregates.RootElement;
|
||||||
@@ -108,9 +107,6 @@ internal sealed record PanoramaView(
|
|||||||
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
|
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
|
||||||
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
|
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
|
||||||
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
|
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
|
||||||
var model = root.GetProperty("apprendimento");
|
|
||||||
var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
|
|
||||||
model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
|
|
||||||
|
|
||||||
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
|
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
|
||||||
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
|
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ if (args.Length >= 1 && args[0] == "backtest")
|
|||||||
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// "anubis learning base": the first model and its validation report, written to docs/learning (Phase 8).
|
||||||
|
if (args.Length >= 1 && args[0] == "learning")
|
||||||
|
{
|
||||||
|
return await LearningCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
|
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
|
||||||
if (args.Length >= 1 && args[0] == "soak")
|
if (args.Length >= 1 && args[0] == "soak")
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -41,12 +41,49 @@ internal static class ReasonTexts
|
|||||||
yield break;
|
yield break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (stage == DecisionStages.Model)
|
||||||
|
{
|
||||||
|
if (Model(data) is { } line)
|
||||||
|
{
|
||||||
|
yield return new WhyLine(line, good);
|
||||||
|
}
|
||||||
|
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var reason in reasons)
|
foreach (var reason in reasons)
|
||||||
{
|
{
|
||||||
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
|
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>What the model said of an entry (SPEC 11.5): its estimate, the usual share of gains, what it changed.</summary>
|
||||||
|
internal static string? Model(string? data)
|
||||||
|
{
|
||||||
|
if (data is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var json = JsonDocument.Parse(data);
|
||||||
|
double? Number(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number ? value.GetDouble() : null;
|
||||||
|
if (Number("probability") is not { } probability || Number("base_rate") is not { } rate)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
var said = string.Create(it, $"Il modello stimava il {probability * 100:0}% di probabilità di guadagno (di solito {rate * 100:0}%)");
|
||||||
|
var applied = Number("applied") ?? 1;
|
||||||
|
if (applied < 1)
|
||||||
|
{
|
||||||
|
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {Math.Clamp(Math.Round(applied * 100), 1, 99):0}%") : said + ": acquisto non fatto";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Is(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
|
||||||
|
return said + (Is("counts") ? ": taglia piena" : Is("aside") ? ": era messo da parte, non ha cambiato la dimensione" : ": solo osservazione, non ha cambiato la dimensione");
|
||||||
|
}
|
||||||
|
|
||||||
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
|
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
|
||||||
private static string Asked(string? data)
|
private static string Asked(string? data)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ internal sealed record TradesView(
|
|||||||
private static async Task<(List<WhyLine> Bought, List<WhyLine> Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t,
|
private static async Task<(List<WhyLine> Bought, List<WhyLine> Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var (executions, decisions) = await services.Db.ReadAsync(async s =>
|
var (executions, decisions, earlier) = await services.Db.ReadAsync(async s =>
|
||||||
{
|
{
|
||||||
var e = await s.QueryAsync(
|
var e = await s.QueryAsync(
|
||||||
"SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " +
|
"SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " +
|
||||||
@@ -178,7 +178,14 @@ internal sealed record TradesView(
|
|||||||
"SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id",
|
"SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id",
|
||||||
r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")),
|
r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")),
|
||||||
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
|
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
|
||||||
return (e, d);
|
|
||||||
|
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
|
||||||
|
var m = await s.QueryAsync(
|
||||||
|
"SELECT d.outcome, d.data FROM decisions d JOIN ml_features f ON f.decision_id = d.decision_id AND f.symbol = d.symbol LEFT JOIN ml_labels l ON l.feature_id = f.id " +
|
||||||
|
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day >= @o) ORDER BY d.created_at DESC LIMIT 1",
|
||||||
|
r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), ("st", DecisionStages.Model), ("s", t.Strategy), ("sym", t.Symbol), ("t", t.OpenedAt.AddMinutes(5)),
|
||||||
|
("o", DateOnly.FromDateTime(t.OpenedAt.UtcDateTime).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||||
|
return (e, d, m);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
|
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
|
||||||
@@ -193,6 +200,10 @@ internal sealed record TradesView(
|
|||||||
: sell.Purpose is "stop" or "protective" ? "stop" : null;
|
: sell.Purpose is "stop" or "protective" ? "stop" : null;
|
||||||
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
|
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
|
||||||
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
|
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
|
||||||
return (Lines(buy.Key), sold, entrySlip, exitSlip, code);
|
|
||||||
|
// The decision of the purchase has its own line when the example was born with it.
|
||||||
|
var own = buy.Key is not null && byKey.TryGetValue(buy.Key, out var entryRows) && entryRows.Any(r => r.Stage == DecisionStages.Model);
|
||||||
|
List<WhyLine> bought = [.. Lines(buy.Key), .. (own ? [] : earlier).SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
|
||||||
|
return (bought, sold, entrySlip, exitSlip, code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,8 @@
|
|||||||
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
||||||
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
|
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
|
||||||
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
|
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
|
||||||
|
<!-- The first model with its examples and base rates (SPEC 11.2): loaded at the first start. -->
|
||||||
|
<EmbeddedResource Include="..\..\docs\learning\first-model.json" LogicalName="Anubis.Learning.first-model.json" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||||
|
|||||||
@@ -20,6 +20,9 @@ public sealed record CostModel(decimal Multiplier = 1m)
|
|||||||
{
|
{
|
||||||
public static CostModel Standard { get; } = new();
|
public static CostModel Standard { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>The slippage in force when the test was planned (SPEC 11.6).</summary>
|
||||||
|
public SlippageTable Slippage { get; init; } = SlippageTable.Standard;
|
||||||
|
|
||||||
/// <summary>The price list of the venue where the instrument would trade. Research archives trade like OKX.</summary>
|
/// <summary>The price list of the venue where the instrument would trade. Research archives trade like OKX.</summary>
|
||||||
public static PaperOptions PriceList(InstrumentSpec spec)
|
public static PaperOptions PriceList(InstrumentSpec spec)
|
||||||
{
|
{
|
||||||
@@ -27,7 +30,7 @@ public sealed record CostModel(decimal Multiplier = 1m)
|
|||||||
return spec.Venue == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(spec.QuoteCurrency);
|
return spec.Venue == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(spec.QuoteCurrency);
|
||||||
}
|
}
|
||||||
|
|
||||||
public decimal SlippageRate(InstrumentSpec spec) => PaperBroker.SlippageBp(spec) / 10_000m * Multiplier;
|
public decimal SlippageRate(InstrumentSpec spec) => Slippage.Bp(spec) / 10_000m * Multiplier;
|
||||||
|
|
||||||
/// <summary>The price paid or received: the reference moved by the slippage, rounded to the tick against us.</summary>
|
/// <summary>The price paid or received: the reference moved by the slippage, rounded to the tick against us.</summary>
|
||||||
public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference)
|
public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using Anubis.Core;
|
|||||||
using Anubis.Data;
|
using Anubis.Data;
|
||||||
using Anubis.Db;
|
using Anubis.Db;
|
||||||
using Anubis.Strategies;
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
@@ -78,14 +79,14 @@ public sealed partial class Laboratory : IDisposable
|
|||||||
/// <summary>Checks the request, writes the plan and queues the trial. The plan is final from here on.</summary>
|
/// <summary>Checks the request, writes the plan and queues the trial. The plan is final from here on.</summary>
|
||||||
public async Task<Trial> PlanAsync(TrialRequest request, CancellationToken cancellationToken)
|
public async Task<Trial> PlanAsync(TrialRequest request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var (plan, variants) = BuildPlan(request, _clock.UtcNow);
|
var (plan, variants) = BuildPlan(request, _clock.UtcNow, await new Anubis.Learning.CostBook(_db, _clock).TableAsync(cancellationToken).ConfigureAwait(false));
|
||||||
var trial = await Trials.PlanAsync(plan, variants, cancellationToken).ConfigureAwait(false);
|
var trial = await Trials.PlanAsync(plan, variants, cancellationToken).ConfigureAwait(false);
|
||||||
await _queue.Writer.WriteAsync(trial.Id, cancellationToken).ConfigureAwait(false);
|
await _queue.Writer.WriteAsync(trial.Id, cancellationToken).ConfigureAwait(false);
|
||||||
return trial;
|
return trial;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <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)
|
public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta.");
|
var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta.");
|
||||||
@@ -146,6 +147,7 @@ public sealed partial class Laboratory : IDisposable
|
|||||||
now)
|
now)
|
||||||
{
|
{
|
||||||
ReferenceShare = StrategyPipeline.DefaultShare(family.Id),
|
ReferenceShare = StrategyPipeline.DefaultShare(family.Id),
|
||||||
|
Slippage = slippage == SlippageTable.Standard ? null : slippage,
|
||||||
};
|
};
|
||||||
var variants = ParameterGrid.Of(family, plan.Grid).Count;
|
var variants = ParameterGrid.Of(family, plan.Grid).Count;
|
||||||
if (variants == 0)
|
if (variants == 0)
|
||||||
|
|||||||
@@ -158,17 +158,7 @@ public static class CryptoTrendProtocol
|
|||||||
|
|
||||||
public static async Task<ProtocolOutcome> RunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action<string>? progress, CancellationToken cancellationToken)
|
public static async Task<ProtocolOutcome> RunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action<string>? progress, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var store = new ResearchStore(researchRoot);
|
var broad = await BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
|
||||||
var broad = new List<string>();
|
|
||||||
foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day))
|
|
||||||
{
|
|
||||||
// Every converted pair goes in: the strategy picks its top 10 month by month, among coins that died too.
|
|
||||||
if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false))
|
|
||||||
{
|
|
||||||
broad.Add(symbol);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Narrow.Any(s => !broad.Contains(s)))
|
if (Narrow.Any(s => !broad.Contains(s)))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Mancano gli storici di BTC, ETH o SOL in euro: scarica prima gli archivi Binance e il cambio BCE.");
|
throw new InvalidOperationException("Mancano gli storici di BTC, ETH o SOL in euro: scarica prima gli archivi Binance e il cambio BCE.");
|
||||||
@@ -184,6 +174,22 @@ public static class CryptoTrendProtocol
|
|||||||
return new ProtocolOutcome(QualificationOf(runs), runs);
|
return new ProtocolOutcome(QualificationOf(runs), runs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Every converted pair with bars in the period: the strategy picks its top 10 month by month, among coins that died too.</summary>
|
||||||
|
public static async Task<IReadOnlyList<string>> BroadAsync(ResearchStore store, DateOnly to, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(store);
|
||||||
|
var broad = new List<string>();
|
||||||
|
foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day))
|
||||||
|
{
|
||||||
|
if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
broad.Add(symbol);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return broad;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live.</summary>
|
/// <summary>The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live.</summary>
|
||||||
public static Qualification QualificationOf(IReadOnlyList<ProtocolRun> runs)
|
public static Qualification QualificationOf(IReadOnlyList<ProtocolRun> runs)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using System.Globalization;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Anubis.Data;
|
using Anubis.Data;
|
||||||
using Anubis.Strategies;
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
namespace Anubis.Backtest;
|
namespace Anubis.Backtest;
|
||||||
|
|
||||||
@@ -119,7 +120,7 @@ public static class TrialRunner
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does.
|
// The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does.
|
||||||
var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To };
|
var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } };
|
||||||
var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare);
|
var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare);
|
||||||
var runs = new BacktestRun[variants.Count];
|
var runs = new BacktestRun[variants.Count];
|
||||||
for (var i = 0; i < variants.Count; i++)
|
for (var i = 0; i < variants.Count; i++)
|
||||||
@@ -141,7 +142,7 @@ public static class TrialRunner
|
|||||||
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 : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = new CostModel(multiplier) });
|
var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
|
||||||
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear);
|
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear);
|
||||||
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));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ using System.Text.Json;
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Anubis.Core;
|
using Anubis.Core;
|
||||||
using Anubis.Db;
|
using Anubis.Db;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
namespace Anubis.Backtest;
|
namespace Anubis.Backtest;
|
||||||
|
|
||||||
@@ -68,6 +69,9 @@ public sealed record TrialPlan(
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public decimal? ReferenceShare { get; init; }
|
public decimal? ReferenceShare { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The slippage in force when the plan was written (SPEC 11.6); null for the standard one.</summary>
|
||||||
|
public SlippageTable? Slippage { get; init; }
|
||||||
|
|
||||||
public static readonly JsonSerializerOptions Json = new()
|
public static readonly JsonSerializerOptions Json = new()
|
||||||
{
|
{
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||||
|
|||||||
@@ -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, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All];
|
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.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,94 @@
|
|||||||
|
-- Learning (SPEC 11, ADR 0018): the archive of examples with the clues as known at the decision, their labels, the
|
||||||
|
-- models, what each model estimated, what happened to them, and the small state of the nightly check.
|
||||||
|
|
||||||
|
-- One example: the first entry intent of a strategy on an instrument it does not hold (11.2), executed or not. source
|
||||||
|
-- is 'live' or 'history' (rebuilt by running the strategy on the past). weight is the share of the strategy's capital
|
||||||
|
-- it asked for; stop and stop_offset are the ones of the intent, kept to simulate the operation for the label; stage
|
||||||
|
-- is the strategy's stage at the decision (null for history). multiplier is the one the operation was born with.
|
||||||
|
CREATE TABLE ml_features (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
strategy TEXT NOT NULL,
|
||||||
|
symbol TEXT NOT NULL,
|
||||||
|
source TEXT NOT NULL,
|
||||||
|
decided_day TEXT NOT NULL,
|
||||||
|
decided_at {timestamp} NOT NULL,
|
||||||
|
decision_id {uuid},
|
||||||
|
stage TEXT,
|
||||||
|
reason TEXT NOT NULL,
|
||||||
|
weight {money} NOT NULL,
|
||||||
|
stop {money},
|
||||||
|
stop_offset {money},
|
||||||
|
features {json} NOT NULL,
|
||||||
|
multiplier {float} NOT NULL,
|
||||||
|
created_at {timestamp} NOT NULL,
|
||||||
|
UNIQUE (strategy, symbol, decided_day, source)
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
CREATE INDEX ml_features_decided ON ml_features (decided_at);
|
||||||
|
|
||||||
|
-- The outcome of an example, known when its simulated operation closes; no row means still open. label is 1 when it
|
||||||
|
-- closed with a gain net of costs, 0 otherwise, null when the operation could never start (void). result is the
|
||||||
|
-- return on what was invested.
|
||||||
|
CREATE TABLE ml_labels (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
feature_id {uuid} NOT NULL UNIQUE REFERENCES ml_features (id),
|
||||||
|
label INTEGER,
|
||||||
|
result {float},
|
||||||
|
opened_day TEXT,
|
||||||
|
closed_day TEXT,
|
||||||
|
exit_reason TEXT NOT NULL,
|
||||||
|
created_at {timestamp} NOT NULL
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
-- The register of every attempt (11.3): champion, challenger, retired, discarded, undone, and the ones tried while
|
||||||
|
-- choosing ('tried'). model holds the learner, its calibration and the statistics of the clues; report its validation.
|
||||||
|
CREATE TABLE ml_models (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
version INTEGER,
|
||||||
|
learner TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
source TEXT NOT NULL,
|
||||||
|
trained_at {timestamp} NOT NULL,
|
||||||
|
examples INTEGER NOT NULL,
|
||||||
|
threshold_done INTEGER NOT NULL,
|
||||||
|
replaced_id {uuid},
|
||||||
|
model {json},
|
||||||
|
report {json} NOT NULL,
|
||||||
|
created_at {timestamp} NOT NULL,
|
||||||
|
updated_at {timestamp} NOT NULL
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
CREATE INDEX ml_models_status ON ml_models (status);
|
||||||
|
|
||||||
|
-- What a model said of an example when it was born: in_charge marks the estimate that counted (the champion's).
|
||||||
|
CREATE TABLE ml_predictions (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
feature_id {uuid} NOT NULL REFERENCES ml_features (id),
|
||||||
|
model_id {uuid} NOT NULL REFERENCES ml_models (id),
|
||||||
|
probability {float} NOT NULL,
|
||||||
|
base_rate {float} NOT NULL,
|
||||||
|
multiplier {float} NOT NULL,
|
||||||
|
in_charge {bool} NOT NULL,
|
||||||
|
created_at {timestamp} NOT NULL,
|
||||||
|
UNIQUE (feature_id, model_id)
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
-- The history the user reads: trainings, promotions, discards, alarms.
|
||||||
|
CREATE TABLE ml_events (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
version INTEGER,
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
data {json},
|
||||||
|
created_at {timestamp} NOT NULL
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
CREATE INDEX ml_events_created ON ml_events (created_at);
|
||||||
|
|
||||||
|
CREATE TABLE ml_state (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
key TEXT NOT NULL UNIQUE,
|
||||||
|
value {json} NOT NULL,
|
||||||
|
created_at {timestamp} NOT NULL,
|
||||||
|
updated_at {timestamp} NOT NULL
|
||||||
|
){strict};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- The slippage estimates of SPEC 11.6 (issue #65): one row for each change proposed by the monthly regression on the
|
||||||
|
-- executions of a broker. A rise is applied at once; a fall, only from real money, waits for the user.
|
||||||
|
|
||||||
|
CREATE TABLE cost_estimates (
|
||||||
|
id {uuid} PRIMARY KEY,
|
||||||
|
tier TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
previous_bp {money} NOT NULL,
|
||||||
|
bp {money} NOT NULL,
|
||||||
|
measured_bp {money} NOT NULL,
|
||||||
|
low_bp {money} NOT NULL,
|
||||||
|
high_bp {money} NOT NULL,
|
||||||
|
cases INTEGER NOT NULL,
|
||||||
|
decided_by TEXT,
|
||||||
|
decided_at {timestamp},
|
||||||
|
created_at {timestamp} NOT NULL,
|
||||||
|
updated_at {timestamp} NOT NULL
|
||||||
|
){strict};
|
||||||
|
|
||||||
|
CREATE INDEX cost_estimates_created ON cost_estimates (created_at);
|
||||||
@@ -76,7 +76,40 @@
|
|||||||
},
|
},
|
||||||
"apprendimento": {
|
"apprendimento": {
|
||||||
"stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56,
|
"stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56,
|
||||||
"ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00"
|
"ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00",
|
||||||
|
"settimane_mancanti": 3.5, "confronti": 14, "guadagno_senza_filtro": "5.84",
|
||||||
|
"in_carica": { "versione": 2, "addestrato": "16 agosto", "casi": 2152, "precisione_pct": 56, "errore": "0.241", "guadagno": "7.90" },
|
||||||
|
"sfidante": { "versione": 3, "addestrato": "4 ottobre", "casi": 2332, "precisione_pct": 57, "errore": "0.239", "guadagno": "8.10" },
|
||||||
|
"fasce": [
|
||||||
|
{ "da": 40, "a": 45, "casi": 22, "pct": 41 }, { "da": 45, "a": 50, "casi": 40, "pct": 45 }, { "da": 50, "a": 55, "casi": 61, "pct": 54 },
|
||||||
|
{ "da": 55, "a": 60, "casi": 50, "pct": 58 }, { "da": 60, "a": 65, "casi": 25, "pct": 60 }, { "da": 65, "a": 70, "casi": 14, "pct": 71 }
|
||||||
|
],
|
||||||
|
"fasce_testo": "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.",
|
||||||
|
"indizi": [
|
||||||
|
{ "nome": "Forza della tendenza", "peso": 22 }, { "nome": "Agitazione recente dei prezzi", "peso": 17 }, { "nome": "Fase generale del mercato", "peso": 14 },
|
||||||
|
{ "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Tono delle notizie, 3 giorni", "peso": 9 }, { "nome": "Paura o avidità", "peso": 8 },
|
||||||
|
{ "nome": "Volumi scambiati", "peso": 7 }, { "nome": "Scommesse a leva sulle crypto", "peso": 5 }, { "nome": "Giorno della settimana", "peso": 3 },
|
||||||
|
{ "nome": "Altro", "peso": 4 }
|
||||||
|
],
|
||||||
|
"sorveglianza": {
|
||||||
|
"precisione_pct": 55, "casi": 60, "controllo": "Ultimo controllo oggi alle 03:00. Ultimo allarme il 19 settembre, rientrato in 3 giorni",
|
||||||
|
"settimane": [
|
||||||
|
{ "lunedi": "2026-08-17", "pct": 53 }, { "lunedi": "2026-08-24", "pct": 54 }, { "lunedi": "2026-08-31", "pct": 55 }, { "lunedi": "2026-09-07", "pct": 52 },
|
||||||
|
{ "lunedi": "2026-09-14", "pct": 49 }, { "lunedi": "2026-09-21", "pct": 54 }, { "lunedi": "2026-09-28", "pct": 56 }, { "lunedi": "2026-10-05", "pct": 55 }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"scoperte": [
|
||||||
|
{ "titolo": "I segnali di trend riescono meno quando il mercato è molto agitato", "dettaglio": "44% di riusciti, contro il 58% dei periodi normali", "casi": 32 },
|
||||||
|
{ "titolo": "Dopo una notizia molto negativa i rimbalzi falliscono più spesso", "dettaglio": "29% di riusciti, contro il 48% del solito", "casi": 17 },
|
||||||
|
{ "titolo": "Il giorno della settimana non conta", "dettaglio": "Le differenze stanno tutte dentro il margine d'errore", "casi": 212 }
|
||||||
|
],
|
||||||
|
"storia": [
|
||||||
|
{ "quando": "4 ottobre", "testo": "Addestrata la versione 3. È in prova come sfidante." },
|
||||||
|
{ "quando": "27 settembre", "testo": "La versione 2 prende il posto della 1: due punti di precisione in più su 120 casi di confronto." },
|
||||||
|
{ "quando": "19 settembre", "testo": "Allarme: precisione scesa al 49% su 41 casi. Modello messo da parte per 3 giorni, poi rientrato." },
|
||||||
|
{ "quando": "16 agosto", "testo": "Addestrata la versione 2. In prova come sfidante." },
|
||||||
|
{ "quando": "12 agosto", "testo": "Prima versione, addestrata su 2.140 segnali ricostruiti dai dati storici." }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"sistema": {
|
"sistema": {
|
||||||
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
|
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
|
||||||
|
|||||||
@@ -287,7 +287,8 @@ public static class DemoMode
|
|||||||
"VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)",
|
"VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)",
|
||||||
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought),
|
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought),
|
||||||
("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false);
|
("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false);
|
||||||
await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken)
|
await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m,
|
||||||
|
rows[i].Length > 3 && rows[i][3] == "MSFT", now, cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -295,7 +296,7 @@ public static class DemoMode
|
|||||||
// F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on
|
// F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on
|
||||||
// the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss.
|
// the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss.
|
||||||
private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought,
|
private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought,
|
||||||
decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken)
|
decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, bool estimated, DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var (entry, exit) = strategy switch
|
var (entry, exit) = strategy switch
|
||||||
{
|
{
|
||||||
@@ -304,11 +305,11 @@ public static class DemoMode
|
|||||||
_ => ("meanrev_entry", "meanrev_exit_average"),
|
_ => ("meanrev_entry", "meanrev_exit_average"),
|
||||||
};
|
};
|
||||||
|
|
||||||
async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) =>
|
async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at, object? data = null) =>
|
||||||
await s.ExecuteAsync(
|
await s.ExecuteAsync(
|
||||||
"INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, NULL, @t)",
|
"INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, @data, @t)",
|
||||||
cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome),
|
cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome),
|
||||||
("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false);
|
("r", new DbJson(JsonSerializer.Serialize(reasons))), ("data", data is null ? null : new DbJson(JsonSerializer.Serialize(data))), ("t", at)).ConfigureAwait(false);
|
||||||
|
|
||||||
async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) =>
|
async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) =>
|
||||||
await s.ExecuteAsync(
|
await s.ExecuteAsync(
|
||||||
@@ -320,6 +321,13 @@ public static class DemoMode
|
|||||||
var buy = ids.Next();
|
var buy = ids.Next();
|
||||||
await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false);
|
await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false);
|
||||||
await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
|
await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
|
||||||
|
if (estimated)
|
||||||
|
{
|
||||||
|
// F.6: the estimate of the model on MSFT, noted in observation; the usual share is the one of F.7.
|
||||||
|
await DecideAsync(buy, Trading.DecisionStages.Model, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1),
|
||||||
|
new { probability = 0.61, base_rate = 0.48, multiplier = 1, applied = 1, counts = false }).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
|
await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
|
||||||
await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false);
|
await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false);
|
||||||
if (stopped)
|
if (stopped)
|
||||||
|
|||||||
@@ -0,0 +1,261 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.News;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A clue of SPEC 11.2. <see cref="Group"/> is what the interface calls it: several clues may tell the same thing.
|
||||||
|
/// <see cref="FromHistory"/> is false for one whose past cannot be rebuilt here: it stays out of the model until at least
|
||||||
|
/// <see cref="Clues.MinLive"/> live examples contain it.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record Clue(string Key, string Group, bool FromHistory);
|
||||||
|
|
||||||
|
/// <summary>What was known outside the bars at a decision: each value only if it was already out and already read.</summary>
|
||||||
|
public sealed record OutsideView
|
||||||
|
{
|
||||||
|
public static OutsideView Nothing { get; } = new();
|
||||||
|
|
||||||
|
public double? FearGreed { get; init; }
|
||||||
|
|
||||||
|
public double? Vix { get; init; }
|
||||||
|
|
||||||
|
public double? BtcFunding { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Open interest over its own mean of the last 30 days: the level alone means nothing over the years.</summary>
|
||||||
|
public double? BtcOpenInterest { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, InstrumentNewsState> News { get; init; } = new Dictionary<string, InstrumentNewsState>();
|
||||||
|
|
||||||
|
/// <summary>Stories of the last 3 days by symbol.</summary>
|
||||||
|
public IReadOnlyDictionary<string, int> Stories3Days { get; init; } = new Dictionary<string, int>();
|
||||||
|
|
||||||
|
/// <summary>Next earnings day by symbol; only while the calendar is fresh.</summary>
|
||||||
|
public IReadOnlyDictionary<string, DateOnly>? Earnings { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The clues of SPEC 11.2, all computed from what was known at the decision.</summary>
|
||||||
|
public static class Clues
|
||||||
|
{
|
||||||
|
/// <summary>Live examples needed before a clue without history enters the model (SPEC 11.2).</summary>
|
||||||
|
public const int MinLive = 200;
|
||||||
|
|
||||||
|
public const string StrategyPrefix = "strategy_";
|
||||||
|
|
||||||
|
public const string Strength = "strength";
|
||||||
|
public const string StopDistance = "stop_distance";
|
||||||
|
public const string Volatility = "volatility";
|
||||||
|
public const string VolatilityRatio = "volatility_ratio";
|
||||||
|
public const string Volume = "volume";
|
||||||
|
public const string MarketTrend = "market_trend";
|
||||||
|
public const string MarketVolatility = "market_volatility";
|
||||||
|
public const string Breadth = "breadth";
|
||||||
|
public const string WeekSin = "weekday_sin";
|
||||||
|
public const string WeekCos = "weekday_cos";
|
||||||
|
public const string Tone1 = "news_tone_1d";
|
||||||
|
public const string Tone3 = "news_tone_3d";
|
||||||
|
public const string Count1 = "news_count_1d";
|
||||||
|
public const string Count3 = "news_count_3d";
|
||||||
|
public const string WorstEvent = "news_worst";
|
||||||
|
public const string FearGreed = "fear_greed";
|
||||||
|
public const string Vix = "vix";
|
||||||
|
public const string Funding = "btc_funding";
|
||||||
|
public const string OpenInterest = "btc_open_interest";
|
||||||
|
public const string EarningsDays = "earnings_days";
|
||||||
|
|
||||||
|
/// <summary>A report this far or more, or none known.</summary>
|
||||||
|
public const int FarReport = 31;
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<Clue> All =
|
||||||
|
[
|
||||||
|
new(StrategyPrefix + StrategyNames.CryptoTrend, "Strategia", true),
|
||||||
|
new(StrategyPrefix + StrategyNames.EquityMomentum, "Strategia", true),
|
||||||
|
new(StrategyPrefix + StrategyNames.EquityMeanrev, "Strategia", true),
|
||||||
|
new(Strength, "Forza della tendenza", true),
|
||||||
|
new(StopDistance, "Distanza dallo stop", true),
|
||||||
|
new(Volatility, "Agitazione recente dei prezzi", true),
|
||||||
|
new(VolatilityRatio, "Agitazione recente dei prezzi", true),
|
||||||
|
new(Volume, "Volumi scambiati", true),
|
||||||
|
new(MarketTrend, "Fase generale del mercato", true),
|
||||||
|
new(MarketVolatility, "Fase generale del mercato", true),
|
||||||
|
new(Breadth, "Quota di titoli in salita", true),
|
||||||
|
new(WeekSin, "Giorno della settimana", true),
|
||||||
|
new(WeekCos, "Giorno della settimana", true),
|
||||||
|
new(Tone1, "Tono delle notizie, 1 giorno", false),
|
||||||
|
new(Tone3, "Tono delle notizie, 3 giorni", false),
|
||||||
|
new(Count1, "Numero di notizie", false),
|
||||||
|
new(Count3, "Numero di notizie", false),
|
||||||
|
new(WorstEvent, "Notizia più grave", false),
|
||||||
|
new(FearGreed, "Paura o avidità", false),
|
||||||
|
new(Vix, "Nervosismo di Wall Street", false),
|
||||||
|
new(Funding, "Scommesse a leva sulle crypto", false),
|
||||||
|
new(OpenInterest, "Scommesse a leva sulle crypto", false),
|
||||||
|
new(EarningsDays, "Giorni alla trimestrale", false),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>The groups that come from the news, for the sentence under the weights of the clues.</summary>
|
||||||
|
public static readonly IReadOnlySet<string> NewsGroups = new HashSet<string>(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"Tono delle notizie, 1 giorno", "Tono delle notizie, 3 giorni", "Numero di notizie", "Notizia più grave",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static Clue? Find(string key) => All.FirstOrDefault(c => c.Key == key);
|
||||||
|
|
||||||
|
/// <summary>The instrument whose trend is the market's: Bitcoin for crypto, SPY for stocks.</summary>
|
||||||
|
public static string? MarketOf(string strategy, StrategyContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
if (strategy != StrategyNames.CryptoTrend)
|
||||||
|
{
|
||||||
|
return StrategyNames.MarketSymbol;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new[] { NoBot.BitcoinSymbol, "BTCEUR" }.FirstOrDefault(s => context.Bars(s).Count > 0)
|
||||||
|
?? context.Universe.FirstOrDefault(s => Symbols.BaseOf(context.Spec(s), s) == "BTC");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The clues of one entry intent. A value that cannot be computed is simply missing.</summary>
|
||||||
|
public static IReadOnlyDictionary<string, double> Of(string strategy, StrategyContext context, Intent intent, OutsideView outside)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
ArgumentNullException.ThrowIfNull(intent);
|
||||||
|
ArgumentNullException.ThrowIfNull(outside);
|
||||||
|
var values = new SortedDictionary<string, double>(StringComparer.Ordinal);
|
||||||
|
void Put(string key, double? value)
|
||||||
|
{
|
||||||
|
if (value is { } v && double.IsFinite(v))
|
||||||
|
{
|
||||||
|
values[key] = Math.Round(v, 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (name, _, _) in StrategyNames.Base)
|
||||||
|
{
|
||||||
|
Put(StrategyPrefix + name, name == strategy ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
var bars = context.Bars(intent.Symbol);
|
||||||
|
var close = bars.Count > 0 ? bars.Close(bars.Count - 1) : 0;
|
||||||
|
Put(Strength, intent.Strength);
|
||||||
|
if (close > 0)
|
||||||
|
{
|
||||||
|
var distance = intent.Stop is { } stop ? close - (double)stop : intent.StopOffset is { } offset ? (double)offset : (double?)null;
|
||||||
|
Put(StopDistance, distance / close);
|
||||||
|
}
|
||||||
|
|
||||||
|
var year = context.PeriodsPerYear;
|
||||||
|
var recent = Indicators.Volatility(bars, 20, year);
|
||||||
|
var longer = Indicators.Volatility(bars, 100, year);
|
||||||
|
Put(Volatility, recent);
|
||||||
|
Put(VolatilityRatio, recent is { } r && longer is > 0 and var l ? r / l : null);
|
||||||
|
Put(Volume, Indicators.MedianValue(bars, 60, bars.Count - 1) is > 0 and var normal ? Indicators.MedianValue(bars, 5, bars.Count - 1) / normal : null);
|
||||||
|
if (MarketOf(strategy, context) is { } market)
|
||||||
|
{
|
||||||
|
var index = context.Bars(market);
|
||||||
|
Put(MarketTrend, Indicators.Sma(index, 200) is > 0 and var average ? (index.Close(index.Count - 1) / average) - 1 : null);
|
||||||
|
Put(MarketVolatility, Indicators.Volatility(index, 30, year));
|
||||||
|
}
|
||||||
|
|
||||||
|
Put(Breadth, BreadthOf(context));
|
||||||
|
var week = 2 * Math.PI * (int)context.Day.DayOfWeek / 7;
|
||||||
|
Put(WeekSin, Math.Sin(week));
|
||||||
|
Put(WeekCos, Math.Cos(week));
|
||||||
|
if (outside.News.TryGetValue(intent.Symbol, out var news))
|
||||||
|
{
|
||||||
|
Put(Tone1, news.Tone1Day);
|
||||||
|
Put(Tone3, news.Tone3Days);
|
||||||
|
Put(Count1, news.Stories1Day);
|
||||||
|
Put(Count3, outside.Stories3Days.GetValueOrDefault(intent.Symbol));
|
||||||
|
Put(WorstEvent, news.Active?.Story.RuleImportance ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Put(FearGreed, outside.FearGreed);
|
||||||
|
Put(Vix, outside.Vix);
|
||||||
|
Put(Funding, outside.BtcFunding);
|
||||||
|
Put(OpenInterest, outside.BtcOpenInterest);
|
||||||
|
if (strategy != StrategyNames.CryptoTrend && outside.Earnings is { } earnings)
|
||||||
|
{
|
||||||
|
Put(EarningsDays, earnings.TryGetValue(intent.Symbol, out var day) ? Math.Clamp(day.DayNumber - context.Day.DayNumber, 0, FarReport) : FarReport);
|
||||||
|
}
|
||||||
|
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The report the decision knew of, which <c>equity_meanrev</c> leaves before; null when none was near.</summary>
|
||||||
|
public static DateOnly? ReportOf(Example example)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(example);
|
||||||
|
return example.Strategy == StrategyNames.EquityMeanrev && example.Features.TryGetValue(EarningsDays, out var days) && days < FarReport ? example.Day.AddDays((int)days) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The share of the strategy's universe that closes above its 200-session average.</summary>
|
||||||
|
private static double? BreadthOf(StrategyContext context)
|
||||||
|
{
|
||||||
|
int above = 0, counted = 0;
|
||||||
|
foreach (var symbol in context.Universe)
|
||||||
|
{
|
||||||
|
var bars = context.Bars(symbol);
|
||||||
|
if (Indicators.Sma(bars, 200) is not { } average)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
counted++;
|
||||||
|
above += bars.Close(bars.Count - 1) > average ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return counted > 0 ? (double)above / counted : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads what was known outside the bars at a moment (SPEC 11.2): mood values dated and saved by then, the news of each
|
||||||
|
/// instrument already read, the earnings calendar. Nothing saved after the moment is seen.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OutsideReader(Database db, IClock clock, SettingsStore? settings = null)
|
||||||
|
{
|
||||||
|
private readonly NewsDesk _desk = new(db, clock, settings);
|
||||||
|
|
||||||
|
public async Task<OutsideView> ReadAsync(DateTimeOffset at, IReadOnlyDictionary<string, InstrumentSpec> specs, IReadOnlyDictionary<string, DateOnly>? earnings,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(specs);
|
||||||
|
var news = new Dictionary<string, InstrumentNewsState>(StringComparer.Ordinal);
|
||||||
|
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||||
|
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(first_seen_at) AS first FROM news_stories", r => r.MomentOrNull("first")), cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
if (first is { } start && start <= at)
|
||||||
|
{
|
||||||
|
var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
foreach (var (symbol, spec) in specs)
|
||||||
|
{
|
||||||
|
var stories = await _desk.StoriesAtAsync(NewsDesk.Target(spec), at - NewsRules.NormWindow, at, cancellationToken).ConfigureAwait(false);
|
||||||
|
news[symbol] = NewsRules.State([.. stories], at, switches, first);
|
||||||
|
counts[symbol] = stories.Count(s => s.FirstSeenAt <= at && s.Start > at - TimeSpan.FromDays(3) && s.Start <= at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var interest = await MoodAsync(MoodIndicators.BtcOpenInterest, at, TimeSpan.FromDays(30), cancellationToken).ConfigureAwait(false);
|
||||||
|
return new OutsideView
|
||||||
|
{
|
||||||
|
News = news,
|
||||||
|
Stories3Days = counts,
|
||||||
|
Earnings = earnings,
|
||||||
|
FearGreed = Last(await MoodAsync(MoodIndicators.FearGreed, at, TimeSpan.FromDays(4), cancellationToken).ConfigureAwait(false)),
|
||||||
|
Vix = Last(await MoodAsync(MoodIndicators.Vix, at, TimeSpan.FromDays(6), cancellationToken).ConfigureAwait(false)),
|
||||||
|
BtcFunding = Last(await MoodAsync(MoodIndicators.BtcFunding, at, TimeSpan.FromDays(2), cancellationToken).ConfigureAwait(false)),
|
||||||
|
BtcOpenInterest = interest.Count >= 5 && interest.Average() is > 0 and var mean ? interest[^1] / mean : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double? Last(IReadOnlyList<double> values) => values.Count > 0 ? values[^1] : null;
|
||||||
|
|
||||||
|
// The values of the window already dated and saved at the moment, oldest first; a value too old is no value.
|
||||||
|
private async Task<IReadOnlyList<double>> MoodAsync(string indicator, DateTimeOffset at, TimeSpan window, CancellationToken cancellationToken) =>
|
||||||
|
await db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT value FROM market_mood WHERE indicator = @i AND as_of >= @f AND as_of <= @t AND created_at <= @t ORDER BY as_of",
|
||||||
|
r => r.Measure("value"), ("i", indicator), ("f", at - window), ("t", at)), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Notifications;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
public static class CostStatuses
|
||||||
|
{
|
||||||
|
/// <summary>In force since it was made: a rise.</summary>
|
||||||
|
public const string Applied = "applied";
|
||||||
|
|
||||||
|
/// <summary>A fall that waits for the user.</summary>
|
||||||
|
public const string Pending = "pending";
|
||||||
|
|
||||||
|
/// <summary>A fall in force because the user confirmed it.</summary>
|
||||||
|
public const string Confirmed = "confirmed";
|
||||||
|
|
||||||
|
public const string Refused = "refused";
|
||||||
|
|
||||||
|
/// <summary>A proposal that a later month replaced before the user decided.</summary>
|
||||||
|
public const string Replaced = "replaced";
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record CostEstimate(Guid Id, string Tier, string Status, decimal PreviousBp, decimal Bp, decimal MeasuredBp, decimal LowBp, decimal HighBp, int Cases, DateTimeOffset CreatedAt,
|
||||||
|
string? DecidedBy = null, DateTimeOffset? DecidedAt = null);
|
||||||
|
|
||||||
|
/// <summary>An execution obtained from a broker: never the internal simulator, which would give back its own guess.</summary>
|
||||||
|
public sealed record PaidFill(string Tier, double SlippageBp, bool RealMoney, DateTimeOffset At);
|
||||||
|
|
||||||
|
/// <summary>What the executions of a tier propose.</summary>
|
||||||
|
public sealed record CostProposal(string Tier, bool Rise, decimal Bp, decimal Measured, decimal Low, decimal High, int Cases);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The monthly regression of SPEC 11.6: the slippage of the executions against their tier. With the tier alone among its
|
||||||
|
/// variables its answer is the mean of each, with an interval that keeps neighbours together.
|
||||||
|
/// </summary>
|
||||||
|
public static class CostRegression
|
||||||
|
{
|
||||||
|
/// <summary>Fewer executions than this in a tier say nothing.</summary>
|
||||||
|
public const int MinCases = 30;
|
||||||
|
|
||||||
|
/// <summary>The estimates move by half basis points, always up to the next: cautious.</summary>
|
||||||
|
public const decimal Step = 0.5m;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the executions propose against the table in force. A rise needs the whole interval above what is in force, on
|
||||||
|
/// any broker account; a fall the whole interval below it, on real money alone.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<CostProposal> Of(IReadOnlyList<PaidFill> fills, SlippageTable table)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(fills);
|
||||||
|
ArgumentNullException.ThrowIfNull(table);
|
||||||
|
var proposals = new List<CostProposal>();
|
||||||
|
foreach (var tier in SlippageTiers.All)
|
||||||
|
{
|
||||||
|
var current = table.Of(tier);
|
||||||
|
var all = fills.Where(f => f.Tier == tier).OrderBy(f => f.At).ToList();
|
||||||
|
if (Fit(all) is { } seen && seen.Low > (double)current)
|
||||||
|
{
|
||||||
|
proposals.Add(Proposed(tier, true, seen, all.Count));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var real = all.Where(f => f.RealMoney).ToList();
|
||||||
|
if (Fit(real) is { } paid && paid.High < (double)current && Proposed(tier, false, paid, real.Count) is var fall && fall.Bp < current)
|
||||||
|
{
|
||||||
|
proposals.Add(fall);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proposals;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (double Mean, double Low, double High)? Fit(List<PaidFill> fills)
|
||||||
|
{
|
||||||
|
if (fills.Count < MinCases)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var values = fills.Select(f => f.SlippageBp).ToList();
|
||||||
|
var (low, high) = Judge.Interval(values, [.. values.Select(_ => 1.0)], 0.95);
|
||||||
|
return (values.Average(), low, high);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CostProposal Proposed(string tier, bool rise, (double Mean, double Low, double High) fit, int cases) =>
|
||||||
|
new(tier, rise, Math.Max(Step, Math.Ceiling((decimal)fit.Mean / Step) * Step), Rounded(fit.Mean), Rounded(fit.Low), Rounded(fit.High), cases);
|
||||||
|
|
||||||
|
private static decimal Rounded(double value) => Math.Round((decimal)value, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The slippage estimates: the table in force, the monthly run, what waits for the user (SPEC 11.6).</summary>
|
||||||
|
public sealed class CostBook(Database db, IClock clock)
|
||||||
|
{
|
||||||
|
public const string StateKey = "cost_month";
|
||||||
|
|
||||||
|
/// <summary>How far back the executions count.</summary>
|
||||||
|
public static readonly TimeSpan Window = TimeSpan.FromDays(365);
|
||||||
|
|
||||||
|
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
private sealed record Month(string Name);
|
||||||
|
|
||||||
|
public async Task<SlippageTable> TableAsync(CancellationToken cancellationToken) =>
|
||||||
|
TableOf(await ListAsync(cancellationToken).ConfigureAwait(false));
|
||||||
|
|
||||||
|
/// <summary>Every estimate, oldest first.</summary>
|
||||||
|
public Task<List<CostEstimate>> ListAsync(CancellationToken cancellationToken) => db.ReadAsync(ListAsync, cancellationToken);
|
||||||
|
|
||||||
|
private static Task<List<CostEstimate>> ListAsync(DbSession s) =>
|
||||||
|
s.QueryAsync("SELECT id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, decided_by, decided_at, created_at FROM cost_estimates ORDER BY created_at, id",
|
||||||
|
r => new CostEstimate(r.Id("id"), r.Text("tier"), r.Text("status"), r.Money("previous_bp"), r.Money("bp"), r.Money("measured_bp"), r.Money("low_bp"), r.Money("high_bp"),
|
||||||
|
(int)r.Number("cases"), r.Moment("created_at"), r.TextOrNull("decided_by"), r.MomentOrNull("decided_at")));
|
||||||
|
|
||||||
|
private static SlippageTable TableOf(IEnumerable<CostEstimate> estimates)
|
||||||
|
{
|
||||||
|
var table = SlippageTable.Standard;
|
||||||
|
foreach (var e in estimates.Where(e => e.Status is CostStatuses.Applied or CostStatuses.Confirmed && SlippageTiers.All.Contains(e.Tier)).OrderBy(e => e.DecidedAt ?? e.CreatedAt))
|
||||||
|
{
|
||||||
|
table = table.With(e.Tier, e.Bp);
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The run of the month: once for each month, at the first night it finds. True when it ran.</summary>
|
||||||
|
public async Task<bool> MonthAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var month = Zones.DayIn(now, Zones.Rome).ToString("yyyy-MM", CultureInfo.InvariantCulture);
|
||||||
|
if ((await new LearningStore(db, clock).StateAsync<Month>(StateKey, cancellationToken).ConfigureAwait(false))?.Name == month)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var fills = await FillsAsync(now - Window, cancellationToken).ConfigureAwait(false);
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
var table = TableOf(await ListAsync(s).ConfigureAwait(false));
|
||||||
|
|
||||||
|
// A proposal of an earlier month still open is out of date, whatever this month says.
|
||||||
|
await s.ExecuteAsync("UPDATE cost_estimates SET status = @r, updated_at = @now WHERE status = @p", cancellationToken,
|
||||||
|
("r", CostStatuses.Replaced), ("now", now), ("p", CostStatuses.Pending)).ConfigureAwait(false);
|
||||||
|
foreach (var proposal in CostRegression.Of(fills, table))
|
||||||
|
{
|
||||||
|
await ProposeAsync(s, proposal, table.Of(proposal.Tier), now, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, StateKey, new Month(month), cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ProposeAsync(DbSession s, CostProposal p, decimal current, DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync(
|
||||||
|
"INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, @t, @st, @prev, @bp, @m, @l, @h, @n, @now, @now)",
|
||||||
|
cancellationToken, ("id", Ids.NewId(clock)), ("t", p.Tier), ("st", p.Rise ? CostStatuses.Applied : CostStatuses.Pending), ("prev", current), ("bp", p.Bp), ("m", p.Measured),
|
||||||
|
("l", p.Low), ("h", p.High), ("n", p.Cases), ("now", now)).ConfigureAwait(false);
|
||||||
|
var what = string.Create(It, $"Scostamento misurato su {p.Cases} esecuzioni ({SlippageTiers.Label(p.Tier)}): {p.Measured:0.0} punti base (centesimi di punto percentuale) invece dei {current:0.0} previsti.");
|
||||||
|
if (p.Rise)
|
||||||
|
{
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "cost_raised", string.Create(It, $"{what} Da ora simulatore e backtest ne contano {p.Bp:0.0}."), null, cancellationToken).ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = what + " La stima più bassa aspetta la tua conferma nel Laboratorio.";
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "cost_pending", text, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
await NotificationSender.EnqueueAsync(s, clock, "cost_pending", text, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The user confirms or refuses a fall. False when it is not waiting any more, or it would not be a fall now.</summary>
|
||||||
|
public Task<bool> DecideAsync(Guid id, bool accept, string user, CancellationToken cancellationToken) =>
|
||||||
|
db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
var rows = await ListAsync(s).ConfigureAwait(false);
|
||||||
|
if (rows.FirstOrDefault(e => e.Id == id) is not { Status: CostStatuses.Pending } row || (accept && row.Bp >= TableOf(rows).Of(row.Tier)))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await s.ExecuteAsync("UPDATE cost_estimates SET status = @st, decided_by = @u, decided_at = @now, updated_at = @now WHERE id = @id AND status = @p", cancellationToken,
|
||||||
|
("st", accept ? CostStatuses.Confirmed : CostStatuses.Refused), ("u", user), ("now", clock.UtcNow), ("id", id), ("p", CostStatuses.Pending)).ConfigureAwait(false);
|
||||||
|
var text = string.Create(It, $"{(accept ? "Confermata" : "Rifiutata")} da te la stima di scostamento più bassa ({SlippageTiers.Label(row.Tier)}): da {row.PreviousBp:0.0} a {row.Bp:0.0} punti base.");
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, accept ? "cost_confirmed" : "cost_refused", text, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The executions obtained from a broker since <paramref name="since"/>. A stop that jumped a gap is not slippage: the
|
||||||
|
/// simulator and the backtest already fill it at the price after the gap.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IReadOnlyList<PaidFill>> FillsAsync(DateTimeOffset since, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var rows = await db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT f.slippage_bp, f.executed_at, a.environment, i.symbol, i.asset_class, i.base_currency FROM fills f JOIN accounts a ON a.id = f.account_id JOIN instruments i ON i.id = f.instrument_id LEFT JOIN orders o ON o.id = f.order_id " +
|
||||||
|
"WHERE f.slippage_bp IS NOT NULL AND f.executed_at >= @f AND a.environment <> @sim AND (o.purpose IS NULL OR o.purpose <> @stop) ORDER BY f.executed_at, f.id",
|
||||||
|
r => (Bp: r.Money("slippage_bp"), At: r.Moment("executed_at"), Environment: r.Text("environment"), Symbol: r.Text("symbol"), Class: r.Text("asset_class"), Base: r.TextOrNull("base_currency")),
|
||||||
|
("f", since), ("sim", TradingEnvironments.Simulation), ("stop", Wire.Text(OrderPurpose.Stop))), cancellationToken).ConfigureAwait(false);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. rows.Where(r => r.Environment is TradingEnvironments.Demo or TradingEnvironments.Live)
|
||||||
|
.Select(r => new PaidFill(SlippageTiers.Of(r.Class, r.Base, r.Symbol), (double)r.Bp, r.Environment == TradingEnvironments.Live, r.At)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.News;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>A relation in plain Italian, with what supports it (SPEC 11.6).</summary>
|
||||||
|
public sealed record Discovery(string Title, string Detail, int Cases)
|
||||||
|
{
|
||||||
|
/// <summary>The judgement on the number of cases, with the words of SPEC 11.6.</summary>
|
||||||
|
public string Trust => TrustOf(Cases);
|
||||||
|
|
||||||
|
public static string TrustOf(int cases) => cases < 20 ? "troppo pochi per fidarsi" : cases < 100 ? "un indizio discreto" : "conclusione solida";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What happened to the prices after the news of a kind: the mean return one and five closes later.</summary>
|
||||||
|
public sealed record NewsImpact(string Kind, int Cases, double OneDay, double FiveDays)
|
||||||
|
{
|
||||||
|
public string Trust => Discovery.TrustOf(Cases);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The discoveries as they were last computed.</summary>
|
||||||
|
public sealed record DiscoverySet
|
||||||
|
{
|
||||||
|
public const string Key = "discoveries";
|
||||||
|
|
||||||
|
public DateTimeOffset At { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The relations between the clues and the outcomes (SPEC 11.6). The questions are fixed here, before any number: the bot
|
||||||
|
/// answers these and does not go looking for others, because among many relations some always look good by chance.
|
||||||
|
/// </summary>
|
||||||
|
public static class DiscoveryFinder
|
||||||
|
{
|
||||||
|
/// <summary>A group smaller than this is not worth a sentence.</summary>
|
||||||
|
public const int MinGroup = 10;
|
||||||
|
|
||||||
|
public const int MaxShown = 8;
|
||||||
|
|
||||||
|
private const double Clear = 1.96;
|
||||||
|
|
||||||
|
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
/// <summary>A question: the examples in which the condition held against all the others of the strategy.</summary>
|
||||||
|
private sealed record Question(string Clue, Func<double, bool> Holds, string Less, string More, string Neither);
|
||||||
|
|
||||||
|
private static readonly IReadOnlyList<Question> Questions =
|
||||||
|
[
|
||||||
|
new(Clues.VolatilityRatio, v => v >= 1.5, "{0} riescono meno quando i prezzi sono molto più agitati del solito", "{0} riescono di più quando i prezzi sono molto più agitati del solito",
|
||||||
|
"Che i prezzi siano più agitati del solito non conta per {1}"),
|
||||||
|
new(Clues.MarketTrend, v => v < 0, "{0} riescono meno quando il mercato è in discesa", "{0} riescono di più quando il mercato è in discesa", "La fase del mercato non conta per {1}"),
|
||||||
|
new(Clues.Breadth, v => v < 0.5, "{0} riescono meno quando sale meno di metà del mercato", "{0} riescono di più quando sale meno di metà del mercato",
|
||||||
|
"Quanta parte del mercato sale non conta per {1}"),
|
||||||
|
new(Clues.Volume, v => v >= 1.5, "{0} riescono meno con scambi molto sopra la norma", "{0} riescono di più con scambi molto sopra la norma", "I volumi scambiati non contano per {1}"),
|
||||||
|
new(Clues.Tone3, v => v <= -0.6, "Dopo notizie molto negative {1} riescono meno", "Dopo notizie molto negative {1} riescono di più", "Le notizie molto negative non contano per {1}"),
|
||||||
|
new(Clues.FearGreed, v => v < 25, "{0} riescono meno quando c'è paura estrema", "{0} riescono di più quando c'è paura estrema", "La paura estrema non conta per {1}"),
|
||||||
|
new(Clues.FearGreed, v => v > 75, "{0} riescono meno quando c'è avidità estrema", "{0} riescono di più quando c'è avidità estrema", "L'avidità estrema non conta per {1}"),
|
||||||
|
new(Clues.Vix, v => v > 30, "{0} riescono meno quando il VIX è nel panico", "{0} riescono di più quando il VIX è nel panico", "Il panico del VIX non conta per {1}"),
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] Days = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
|
||||||
|
|
||||||
|
public static string SignalsOf(string strategy) => strategy switch
|
||||||
|
{
|
||||||
|
StrategyNames.CryptoTrend => "i segnali di trend sulle crypto",
|
||||||
|
StrategyNames.EquityMomentum => "i segnali sulle azioni più forti",
|
||||||
|
StrategyNames.EquityMeanrev => "i rimbalzi sulle azioni",
|
||||||
|
_ => "i segnali",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The relations that hold, and those that surely do not, the clearest first.</summary>
|
||||||
|
public static IReadOnlyList<Discovery> Of(IReadOnlyList<Example> examples)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(examples);
|
||||||
|
var answers = new List<(double Z, int Group, Func<int, Discovery?> Say)>();
|
||||||
|
foreach (var strategy in examples.Where(e => e.IsLabelled).GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
var signals = SignalsOf(strategy.Key);
|
||||||
|
foreach (var q in Questions)
|
||||||
|
{
|
||||||
|
var known = strategy.Where(e => e.Features.ContainsKey(q.Clue)).ToList();
|
||||||
|
if (Compare(known, e => q.Holds(e.Features[q.Clue])) is { } c)
|
||||||
|
{
|
||||||
|
answers.Add((Math.Abs(c.Z), c.Group, bar => Sentence(c, signals, q.Less, q.More, q.Neither, bar)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The weekday: the day that stands out most, against a bar raised because there are seven of them.
|
||||||
|
var days = Enumerable.Range(0, 7).Select(d => (Day: d, Found: Compare([.. strategy], e => (int)e.Day.DayOfWeek == d))).Where(x => x.Found is not null).ToList();
|
||||||
|
if (days.Count >= 2)
|
||||||
|
{
|
||||||
|
var (day, found) = days.MaxBy(x => Math.Abs(x.Found!.Z));
|
||||||
|
var c = found! with { Corrected = days.Count };
|
||||||
|
answers.Add((Math.Abs(c.Z), c.Group, bar => Sentence(c, signals, "{0} riescono meno di " + Days[day], "{0} riescono di più di " + Days[day], "Il giorno della settimana non conta per {1}", bar)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var bar = answers.Count;
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. answers.Select(a => (a.Z, Text: a.Say(bar))).Where(a => a.Text is not null).OrderByDescending(a => a.Z).Select(a => a.Text!).Take(MaxShown),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Comparison(double Z, int Group, int All, double InGroup, double Others)
|
||||||
|
{
|
||||||
|
/// <summary>How many comparisons hide behind this one.</summary>
|
||||||
|
public int Corrected { get; init; } = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The difference between the shares of winners, over a standard error that counts as one the operations decided in the
|
||||||
|
/// same month: many coins move together, and a hundred of them in a week are not a hundred proofs.
|
||||||
|
/// </summary>
|
||||||
|
private static Comparison? Compare(IReadOnlyList<Example> examples, Func<Example, bool> holds)
|
||||||
|
{
|
||||||
|
var inside = examples.Where(holds).ToList();
|
||||||
|
var outside = examples.Where(e => !holds(e)).ToList();
|
||||||
|
if (inside.Count < MinGroup || outside.Count < MinGroup)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
double Share(List<Example> group) => (double)group.Count(e => e.Label!.Win == true) / group.Count;
|
||||||
|
var (a, b) = (Share(inside), Share(outside));
|
||||||
|
var all = Share([.. inside, .. outside]);
|
||||||
|
var simple = Math.Sqrt(all * (1 - all) * ((1.0 / inside.Count) + (1.0 / outside.Count)));
|
||||||
|
var months = new Dictionary<(int Year, int Month), double>();
|
||||||
|
void Add(List<Example> group, double share, double sign)
|
||||||
|
{
|
||||||
|
foreach (var e in group)
|
||||||
|
{
|
||||||
|
var key = (e.Day.Year, e.Day.Month);
|
||||||
|
months[key] = months.GetValueOrDefault(key) + (sign * ((e.Label!.Win == true ? 1 : 0) - share) / group.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Add(inside, a, 1);
|
||||||
|
Add(outside, b, -1);
|
||||||
|
var clustered = months.Count > 1 ? Math.Sqrt(months.Values.Sum(x => x * x) * months.Count / (months.Count - 1)) : 0;
|
||||||
|
var error = Math.Max(simple, clustered);
|
||||||
|
return error > 0 ? new Comparison((a - b) / error, inside.Count, inside.Count + outside.Count, a, b) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Discovery? Sentence(Comparison c, string signals, string less, string more, string neither, int questions)
|
||||||
|
{
|
||||||
|
string Fill(string text)
|
||||||
|
{
|
||||||
|
var filled = string.Format(It, text, char.ToUpper(signals[0], It) + signals[1..], signals);
|
||||||
|
return char.ToUpper(filled[0], It) + filled[1..];
|
||||||
|
}
|
||||||
|
|
||||||
|
// A conclusion called solid has to survive having asked many questions; a hint says by itself how little it is worth.
|
||||||
|
var needed = c.Group >= 100 ? Quantile(0.05 / questions / c.Corrected) : c.Corrected > 1 ? Quantile(0.05 / c.Corrected) : Clear;
|
||||||
|
if (Math.Abs(c.Z) >= needed)
|
||||||
|
{
|
||||||
|
return new Discovery(Fill(c.Z < 0 ? less : more), string.Create(It, $"{c.InGroup * 100:0}% di riusciti contro il {c.Others * 100:0}% degli altri"), c.Group);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.Abs(c.Z) < Clear && c.Group >= 20 && c.All >= 100 ? new Discovery(Fill(neither), "Le differenze stanno tutte dentro il margine d'errore", c.All) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How many standard errors leave <paramref name="probability"/> outside, both sides together.</summary>
|
||||||
|
internal static double Quantile(double probability)
|
||||||
|
{
|
||||||
|
var (low, high) = (0.0, 10.0);
|
||||||
|
for (var i = 0; i < 60; i++)
|
||||||
|
{
|
||||||
|
var middle = (low + high) / 2;
|
||||||
|
(low, high) = Outside(middle) > probability ? (middle, high) : (low, middle);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (low + high) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Outside(double z)
|
||||||
|
{
|
||||||
|
// Abramowitz and Stegun 26.2.17: the tail of the normal, good to 7 digits.
|
||||||
|
var t = 1 / (1 + (0.2316419 * z));
|
||||||
|
var d = Math.Exp(-z * z / 2) / Math.Sqrt(2 * Math.PI);
|
||||||
|
return 2 * d * t * (0.319381530 + (t * (-0.356563782 + (t * (1.781477937 + (t * (-1.821255978 + (t * 1.330274429))))))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Computes the discoveries and the table of the news, and keeps them for the page.</summary>
|
||||||
|
public sealed class DiscoveryDesk(Database db, IClock clock, LearningStore store)
|
||||||
|
{
|
||||||
|
public async Task<DiscoverySet> LatestAsync(CancellationToken cancellationToken) =>
|
||||||
|
await store.StateAsync<DiscoverySet>(DiscoverySet.Key, cancellationToken).ConfigureAwait(false) ?? new DiscoverySet();
|
||||||
|
|
||||||
|
public async Task RefreshAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var found = DiscoveryFinder.Of(await store.AllAsync(cancellationToken).ConfigureAwait(false));
|
||||||
|
var news = await NewsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var set = new DiscoverySet { At = clock.UtcNow, Found = found, News = news };
|
||||||
|
await db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, DiscoverySet.Key, set, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The mean return after each kind of event, from the first daily close after the publication. Only informative: it
|
||||||
|
/// changes neither the importance of SPEC 10.2 nor the rules of 10.5.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IReadOnlyList<NewsImpact>> NewsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var rows = await db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT n.id, n.published_at, n.severe, v.event_type, i.id AS instrument_id, i.asset_class FROM news_stories n JOIN news_links k ON k.story_id = n.id AND k.scope = @sc " +
|
||||||
|
"JOIN instruments i ON i.venue || ':' || i.symbol = k.target LEFT JOIN news_verdicts v ON v.id = n.verdict_id WHERE n.severe IS NOT NULL OR v.event_type IS NOT NULL",
|
||||||
|
r => (At: r.Moment("published_at"), Kind: NewsEventNames.KindOf(r.TextOrNull("event_type"), r.TextOrNull("severe")), Instrument: r.Id("instrument_id"), Class: r.Text("asset_class")),
|
||||||
|
("sc", LinkScopes.Instrument)), cancellationToken).ConfigureAwait(false);
|
||||||
|
var store = new BarStore(db, clock);
|
||||||
|
var moves = new List<(string Kind, double One, double Five)>();
|
||||||
|
foreach (var group in rows.Where(r => r.Kind is not null).GroupBy(r => (r.Instrument, r.Class)))
|
||||||
|
{
|
||||||
|
var first = DateOnly.FromDateTime(group.Min(r => r.At).UtcDateTime).AddDays(-1);
|
||||||
|
var bars = await store.DailyAsync(group.Key.Instrument, first, DateOnly.FromDateTime(clock.UtcNow.UtcDateTime), cancellationToken).ConfigureAwait(false);
|
||||||
|
foreach (var (at, kind, _, _) in group)
|
||||||
|
{
|
||||||
|
if (AfterNews(bars, group.Key.Class, at) is { } move)
|
||||||
|
{
|
||||||
|
moves.Add((kind!, move.One, move.Five));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. moves.GroupBy(m => m.Kind, StringComparer.Ordinal).Select(g => new NewsImpact(g.Key, g.Count(), g.Average(m => m.One), g.Average(m => m.Five)))
|
||||||
|
.OrderByDescending(n => n.Cases).ThenBy(n => n.Kind, StringComparer.Ordinal),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The returns one and five closes after the first close that came after the news; null until they are there.</summary>
|
||||||
|
internal static (double One, double Five)? AfterNews(IReadOnlyList<DailyBar> bars, string assetClass, DateTimeOffset published)
|
||||||
|
{
|
||||||
|
var start = -1;
|
||||||
|
for (var i = 0; i < bars.Count && start < 0; i++)
|
||||||
|
{
|
||||||
|
start = CloseOf(bars[i].Day, assetClass) > published ? i : start;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start < 0 || start + 5 >= bars.Count)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
double Close(int i) => bars[i].Adjusted?.Close ?? bars[i].Close;
|
||||||
|
return Close(start) > 0 ? ((Close(start + 1) / Close(start)) - 1, (Close(start + 5) / Close(start)) - 1) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTimeOffset CloseOf(DateOnly day, string assetClass)
|
||||||
|
{
|
||||||
|
if (assetClass != AssetClasses.Equity)
|
||||||
|
{
|
||||||
|
return new DateTimeOffset(day.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
|
||||||
|
var local = day.ToDateTime(new TimeOnly(16, 0));
|
||||||
|
return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The kinds of event of the language model and of the keywords, with one name for each thing.</summary>
|
||||||
|
public static class NewsEventNames
|
||||||
|
{
|
||||||
|
/// <summary>The kind of a story: the keywords of a serious case first, then what the language model said.</summary>
|
||||||
|
public static string? KindOf(string? eventType, string? severe) => severe switch
|
||||||
|
{
|
||||||
|
SevereKinds.Cyberattack => "security_incident",
|
||||||
|
SevereKinds.Suspension => "trading_halt",
|
||||||
|
SevereKinds.Fraud or SevereKinds.Investigation => "fraud_or_investigation",
|
||||||
|
SevereKinds.Bankruptcy => "bankruptcy",
|
||||||
|
SevereKinds.Delisting => "delisting",
|
||||||
|
_ => string.IsNullOrEmpty(eventType) ? null : eventType,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string Label(string kind) => kind switch
|
||||||
|
{
|
||||||
|
"network_upgrade" => "Aggiornamento della rete",
|
||||||
|
"earnings" => "Trimestrale",
|
||||||
|
"guidance" => "Previsioni della società",
|
||||||
|
"regulation" => "Nuove regole",
|
||||||
|
"security_incident" => "Attacco informatico",
|
||||||
|
"fraud_or_investigation" => "Frode o indagine",
|
||||||
|
"bankruptcy" => "Fallimento",
|
||||||
|
"trading_halt" => "Sospensione degli scambi",
|
||||||
|
"listing" => "Arrivo su un mercato",
|
||||||
|
"delisting" => "Revoca dalla quotazione",
|
||||||
|
"macro_data" => "Dato economico",
|
||||||
|
"central_bank" => "Banca centrale",
|
||||||
|
"analyst_opinion" => "Parere di un analista",
|
||||||
|
"rumor" => "Voce non confermata",
|
||||||
|
_ => "Altro",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>Where an example comes from.</summary>
|
||||||
|
public static class CaseSources
|
||||||
|
{
|
||||||
|
public const string Live = "live";
|
||||||
|
public const string History = "history";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An example (SPEC 11.2; "segnale" and "caso" for the user): an entry intent and the clues known at that moment.</summary>
|
||||||
|
public sealed record Example(Guid Id, string Strategy, string Symbol, string Source, DateOnly Day, DateTimeOffset At, string Reason, decimal Weight, decimal? Stop, decimal? StopOffset,
|
||||||
|
IReadOnlyDictionary<string, double> Features)
|
||||||
|
{
|
||||||
|
/// <summary>The stage of the strategy at the decision; null for an example of the history.</summary>
|
||||||
|
public string? Stage { get; init; }
|
||||||
|
|
||||||
|
public Guid? DecisionId { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The multiplier the operation was born with, valid to its close, increases included (SPEC 11.1).</summary>
|
||||||
|
public double Multiplier { get; init; } = 1;
|
||||||
|
|
||||||
|
public CaseLabel? Label { get; init; }
|
||||||
|
|
||||||
|
/// <summary>A label that can train: the operation started and closed.</summary>
|
||||||
|
[JsonIgnore]
|
||||||
|
public bool IsLabelled => Label is { Win: not null, ClosedDay: not null };
|
||||||
|
|
||||||
|
public bool IsOpenAfter(DateOnly day) => Label is null || (Label.ClosedDay is { } closed && closed > day);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How the simulated operation of an example ended. <see cref="Win"/> is null when it could never start.</summary>
|
||||||
|
public sealed record CaseLabel(bool? Win, double? Result, DateOnly? OpenedDay, DateOnly? ClosedDay, string ExitReason);
|
||||||
|
|
||||||
|
/// <summary>Why an example has no outcome.</summary>
|
||||||
|
public static class CaseOutcomes
|
||||||
|
{
|
||||||
|
/// <summary>The operation could not start: below the minimum of the market.</summary>
|
||||||
|
public const string NeverStarted = "never_started";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The first step of the decision: it changes nothing and notes the entry intents that make an example, with their clues.
|
||||||
|
/// One example for the first intent on an instrument not held; while the simulated operation of that example is open, a
|
||||||
|
/// repeated proposal is the same example (SPEC 11.2).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class CaseCollector(string strategy, Func<StrategyContext, Intent, bool> isNew, OutsideView? outside = null, DateOnly? only = null) : IIntentStage
|
||||||
|
{
|
||||||
|
private readonly List<Example> _cases = [];
|
||||||
|
|
||||||
|
public string Name => "learning_cases";
|
||||||
|
|
||||||
|
public IReadOnlyList<Example> Cases => _cases;
|
||||||
|
|
||||||
|
/// <summary>Told of each new example, as soon as it is noted.</summary>
|
||||||
|
public Action<Example>? Noted { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
ArgumentNullException.ThrowIfNull(intents);
|
||||||
|
if (only is { } day && context.Day != day)
|
||||||
|
{
|
||||||
|
return intents;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var intent in intents.Where(i => IsEntry(context, i) && isNew(context, i)))
|
||||||
|
{
|
||||||
|
var made = new Example(Guid.Empty, strategy, intent.Symbol, CaseSources.History, context.Day, context.Now, intent.Reason, intent.TargetWeight!.Value, intent.Stop,
|
||||||
|
intent.StopOffset, Clues.Of(strategy, context, intent, outside ?? OutsideView.Nothing));
|
||||||
|
_cases.Add(made);
|
||||||
|
Noted?.Invoke(made);
|
||||||
|
}
|
||||||
|
|
||||||
|
return intents;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsEntry(StrategyContext context, Intent intent)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
ArgumentNullException.ThrowIfNull(intent);
|
||||||
|
return intent.TargetWeight is > 0m && !context.Portfolio.Holds(intent.Symbol);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One operation on its own: the entry of an example on its day, then the exits and the stops of its strategy and
|
||||||
|
/// nothing else. The size never changes and the instrument is never bought again, so the outcome does not depend on what
|
||||||
|
/// the bot did with the signal (SPEC 11.2).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SingleOperation(IStrategy inner, Example example) : IStrategy
|
||||||
|
{
|
||||||
|
/// <summary>The same for every example: the result is a share of what is invested.</summary>
|
||||||
|
public const decimal Weight = 0.5m;
|
||||||
|
|
||||||
|
public string Id => inner.Id;
|
||||||
|
|
||||||
|
public string Version => inner.Version;
|
||||||
|
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => inner.Schedule();
|
||||||
|
|
||||||
|
/// <summary>Only <c>equity_momentum</c> needs the others, to know the rank; the rest look at their own instrument.</summary>
|
||||||
|
public static bool NeedsUniverse(string strategy) => strategy == StrategyNames.EquityMomentum;
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context) => NeedsUniverse(inner.Id) ? inner.Universe(context) : [example.Symbol];
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
if (context.Day == example.Day)
|
||||||
|
{
|
||||||
|
return [new Intent(example.Symbol, Weight, example.Reason) { Stop = example.Stop, StopOffset = example.StopOffset }];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!context.Portfolio.Holds(example.Symbol))
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var kept = new List<Intent>();
|
||||||
|
foreach (var intent in inner.Decide(context).Where(i => i.Symbol == example.Symbol))
|
||||||
|
{
|
||||||
|
if (intent.TargetWeight == 0m)
|
||||||
|
{
|
||||||
|
kept.Add(intent);
|
||||||
|
}
|
||||||
|
else if (intent.Stop is not null)
|
||||||
|
{
|
||||||
|
kept.Add(intent with { TargetWeight = null });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label of an example: its operation simulated alone, at full size, net of every cost (SPEC 11.2).</summary>
|
||||||
|
public static class CaseLabels
|
||||||
|
{
|
||||||
|
private static readonly int[] Horizons = [40, 160, 640];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The outcome with the bars of <paramref name="data"/> up to <paramref name="through"/>; null while the operation is
|
||||||
|
/// open. The strategy is built fresh: it walks the bars again. <paramref name="earnings"/> is the first report after the
|
||||||
|
/// decision, which <c>equity_meanrev</c> leaves before; one out by the entry session is not ahead any more.
|
||||||
|
/// </summary>
|
||||||
|
public static CaseLabel? Of(Example example, Func<IStrategy> strategy, BacktestDataset data, DateOnly through, CostModel? costs = null, DateOnly? earnings = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(example);
|
||||||
|
ArgumentNullException.ThrowIfNull(strategy);
|
||||||
|
ArgumentNullException.ThrowIfNull(data);
|
||||||
|
if (data[example.Symbol] is not { } instrument || through <= example.Day)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (earnings is { } report && (instrument.Bars.FirstOrDefault(b => b.Day > example.Day) is not { } entry || report <= entry.Day))
|
||||||
|
{
|
||||||
|
earnings = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var alone = SingleOperation.NeedsUniverse(example.Strategy) ? data : new BacktestDataset([instrument], data.Currency, data.Calendar);
|
||||||
|
foreach (var until in Horizons.Select(h => example.Day.AddDays(h)).Where(d => d < through).Append(through))
|
||||||
|
{
|
||||||
|
var run = BacktestEngine.Run(new SingleOperation(strategy(), example), alone, new BacktestOptions
|
||||||
|
{
|
||||||
|
From = example.Day,
|
||||||
|
To = until,
|
||||||
|
Costs = costs ?? CostModel.Standard,
|
||||||
|
NextEarnings = earnings is { } date ? s => s == example.Symbol ? date : null : null,
|
||||||
|
});
|
||||||
|
var trade = run.Trades.FirstOrDefault(t => t.Symbol == example.Symbol);
|
||||||
|
if (trade is null)
|
||||||
|
{
|
||||||
|
// Bars came after the decision and nothing was bought: the operation cannot exist.
|
||||||
|
if (instrument.Bars.FirstOrDefault(b => b.Day > example.Day && b.Day <= until) is { } bar)
|
||||||
|
{
|
||||||
|
return new CaseLabel(null, null, null, bar.Day, CaseOutcomes.NeverStarted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (trade.Closed is { } closed)
|
||||||
|
{
|
||||||
|
var result = trade.Invested > 0m ? (double)(trade.Result / trade.Invested) : 0;
|
||||||
|
return new CaseLabel(trade.Result > 0m, Math.Round(result, 8), trade.Opened, closed, run.Fills.Last(f => f.Symbol == example.Symbol).Reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The examples of the past: the strategy runs on the history and every first entry becomes one (SPEC 11.2).</summary>
|
||||||
|
public static class HistoryCases
|
||||||
|
{
|
||||||
|
public static IReadOnlyList<Example> Build(string strategy, Func<IStrategy> create, BacktestDataset data, BacktestOptions options, Action<int>? progress = null,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(create);
|
||||||
|
ArgumentNullException.ThrowIfNull(data);
|
||||||
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
|
var through = options.To ?? data.Sessions[^1];
|
||||||
|
var last = new Dictionary<string, Example>(StringComparer.Ordinal);
|
||||||
|
var cases = new List<Example>();
|
||||||
|
|
||||||
|
// The label reads the bars after the decision, but the only thing the run uses of it is whether the operation
|
||||||
|
// was already over on a later day: known on that day.
|
||||||
|
var collector = new CaseCollector(strategy, (context, intent) => !last.TryGetValue(intent.Symbol, out var previous) || !previous.IsOpenAfter(context.Day))
|
||||||
|
{
|
||||||
|
Noted = made =>
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
var labelled = made with { Label = CaseLabels.Of(made, create, data, through, options.Costs) };
|
||||||
|
last[made.Symbol] = labelled;
|
||||||
|
cases.Add(labelled);
|
||||||
|
progress?.Invoke(cases.Count);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
BacktestEngine.Run(create(), data, options with { Correctives = [collector, .. options.Correctives] });
|
||||||
|
return cases;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The first model (SPEC 11.2): trained on the examples rebuilt by running the strategies on the history. The file travels
|
||||||
|
/// with the program, as the outcomes of the backtests do: it also gives the base rate of each strategy (SPEC 11.1), which
|
||||||
|
/// a new file updates at each quarterly review.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FirstModelFile
|
||||||
|
{
|
||||||
|
/// <summary>The last day of the history it was built on.</summary>
|
||||||
|
public DateOnly Through { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The share of winners of each strategy on the history; a strategy not here has no base rate yet.</summary>
|
||||||
|
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
|
||||||
|
|
||||||
|
public TrainedModel? Model { get; init; }
|
||||||
|
|
||||||
|
public ModelReport? Report { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<Example> Examples { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class FirstModel
|
||||||
|
{
|
||||||
|
public const string Resource = "Anubis.Learning.first-model.json";
|
||||||
|
|
||||||
|
/// <summary>The reference total the gain is measured on when no strategy has capital yet (SPEC 8.6).</summary>
|
||||||
|
public const double ReferenceCapital = 10_000;
|
||||||
|
|
||||||
|
private static readonly Lazy<FirstModelFile?> Loaded = new(Load);
|
||||||
|
|
||||||
|
/// <summary>The file built into the program; null when there is none.</summary>
|
||||||
|
public static FirstModelFile? Embedded => Loaded.Value;
|
||||||
|
|
||||||
|
public static IReadOnlyDictionary<string, double> ReferenceCapitals { get; } =
|
||||||
|
StrategyNames.Base.ToDictionary(s => s.Name, s => ReferenceCapital * (double)(StrategyPipeline.DefaultShare(s.Name) ?? 0m), StringComparer.Ordinal);
|
||||||
|
|
||||||
|
private static FirstModelFile? Load()
|
||||||
|
{
|
||||||
|
using var stream = typeof(FirstModel).Assembly.GetManifestResourceStream(Resource);
|
||||||
|
return stream is null ? null : JsonSerializer.Deserialize<FirstModelFile>(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string ToJson(FirstModelFile file) => JsonSerializer.Serialize(file) + "\n";
|
||||||
|
|
||||||
|
public static string Fingerprint(FirstModelFile file) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(ToJson(file))));
|
||||||
|
|
||||||
|
/// <summary>Rebuilds the examples of <c>crypto_trend</c> on the broad universe of its protocol, then trains.</summary>
|
||||||
|
public static async Task<FirstModelFile> BuildAsync(string researchRoot, DateOnly to, Action<string>? progress, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var symbols = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (symbols.Count == 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Mancano gli storici delle crypto in euro: esegui prima anubis backtest base.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = await Laboratory.LoadResearchAsync(researchRoot, new TrialData(TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, to), cancellationToken).ConfigureAwait(false);
|
||||||
|
var parameters = BacktestOutcomes.Find(StrategyNames.CryptoTrend)?.Parameters;
|
||||||
|
var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = CryptoTrendProtocol.Capital, From = CryptoTrendProtocol.From, To = to });
|
||||||
|
var examples = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, parameters), data, options,
|
||||||
|
n => progress?.Invoke(string.Create(CultureInfo.InvariantCulture, $"esempi: {n}")), cancellationToken);
|
||||||
|
return Train([.. examples.Select(WithStableId)], to, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FirstModelFile Train(IReadOnlyList<Example> examples, DateOnly through, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(examples);
|
||||||
|
var rates = Trainer.SharesOf(examples);
|
||||||
|
var result = Trainer.Train(new TrainingInput(examples)
|
||||||
|
{
|
||||||
|
BaseRates = rates,
|
||||||
|
Capital = ReferenceCapitals,
|
||||||
|
}, cancellationToken);
|
||||||
|
return new FirstModelFile { Through = through, BaseRates = rates, Model = result?.Model, Report = result?.Report, Examples = examples };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same example always has the same id, so the same history writes the same file.
|
||||||
|
private static Example WithStableId(Example example) =>
|
||||||
|
example with { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes($"{example.Strategy}|{example.Symbol}|{example.Day:yyyy-MM-dd}")).AsSpan(0, 16)) };
|
||||||
|
|
||||||
|
/// <summary>The validation report, in plain Italian.</summary>
|
||||||
|
public static string Markdown(FirstModelFile file, string command)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(file);
|
||||||
|
var it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
var text = new StringBuilder();
|
||||||
|
void Line(FormattableString line) => text.Append(line.ToString(it)).Append('\n');
|
||||||
|
Line($"# Primo modello: rapporto di convalida");
|
||||||
|
Line($"");
|
||||||
|
Line($"Generato con `{command}` sullo storico fino al {file.Through:dd/MM/yyyy}. Gli stessi dati danno sempre lo stesso modello.");
|
||||||
|
Line($"");
|
||||||
|
Line($"## La domanda");
|
||||||
|
Line($"");
|
||||||
|
Line($"Il modello non prevede i prezzi. Guarda un segnale di una strategia e stima quanto è probabile che l'operazione chiuda in guadagno, al netto dei costi. Può solo rimpicciolire l'operazione.");
|
||||||
|
Line($"");
|
||||||
|
Line($"## Gli esempi");
|
||||||
|
Line($"");
|
||||||
|
var labelled = file.Examples.Where(e => e.IsLabelled).ToList();
|
||||||
|
var open = file.Examples.Count(e => e.Label is null);
|
||||||
|
Line($"{file.Examples.Count} esempi ricostruiti facendo girare le strategie sullo storico: {labelled.Count} con un esito, {open} con l'operazione ancora aperta, {file.Examples.Count - labelled.Count - open} mai partiti (sotto il minimo).");
|
||||||
|
Line($"");
|
||||||
|
Line($"| Strategia | Esempi con esito | Dal | Al | In guadagno (frequenza di base) | Risultato medio dell'operazione |");
|
||||||
|
Line($"|---|---|---|---|---|---|");
|
||||||
|
foreach (var group in labelled.GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
Line($"| {group.Key} | {group.Count()} | {group.Min(e => e.Day):dd/MM/yyyy} | {group.Max(e => e.Day):dd/MM/yyyy} | {file.BaseRates[group.Key] * 100:0.0}% | {group.Average(e => e.Label!.Result ?? 0) * 100:+0.0;-0.0}% |");
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var missing in StrategyNames.Base.Select(s => s.Name).Where(s => !file.BaseRates.ContainsKey(s)))
|
||||||
|
{
|
||||||
|
Line($"| {missing} | 0 | | | nessuna: aspetta lo storico di Alpaca | |");
|
||||||
|
}
|
||||||
|
|
||||||
|
Line($"");
|
||||||
|
Line($"Una strategia senza frequenza di base non viene stimata: il modello lascia le sue operazioni come sono.");
|
||||||
|
if (file.Report is not { } report || file.Model is not { } model)
|
||||||
|
{
|
||||||
|
Line($"");
|
||||||
|
Line($"**Nessun modello**: gli esempi sono troppo pochi.");
|
||||||
|
return text.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
Line($"");
|
||||||
|
Line($"## La convalida");
|
||||||
|
Line($"");
|
||||||
|
Line($"Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si studia il passato e si verifica il periodo dopo, 5 volte. «A combinazioni»: {report.Splits} combinazioni di 6 periodi, togliendo dallo studio ogni esempio che si sovrappone nel tempo a quelli di verifica, più {CaseSplits.Embargo} giorni di distacco.");
|
||||||
|
Line($"");
|
||||||
|
Line($"| Modello | Prova | Casi | Errore (log-loss) | Di chi risponde sempre la frequenza di base | Errore sulle probabilità (Brier) | Previsioni azzeccate | Guadagno medio per operazione proposta, senza filtro | con il filtro |");
|
||||||
|
Line($"|---|---|---|---|---|---|---|---|---|");
|
||||||
|
foreach (var attempt in report.Attempts)
|
||||||
|
{
|
||||||
|
foreach (var (name, s) in new[] { ("in avanti", attempt.Forward), ("a combinazioni", attempt.Combined) })
|
||||||
|
{
|
||||||
|
Line($"| {LearnerNames.Label(attempt.Learner)}{(attempt.Chosen ? " (scelto)" : "")} | {name} | {s.Cases} | {s.LogLoss:0.0000} | {s.BaseLogLoss:0.0000} | {s.Brier:0.0000} | {(s.Precision is { } p ? p * 100 : 0):0.0}% | {s.GainWithout:+0.00;-0.00} € | {s.GainWith:+0.00;-0.00} € |");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Line($"");
|
||||||
|
Line($"Il guadagno è calcolato sul capitale di riferimento ({ReferenceCapital:#,0} € in tutto, quote predefinite). Nelle combinazioni ogni caso è verificato più volte.");
|
||||||
|
Line($"");
|
||||||
|
Line($"**Scelta.** {report.Reason} La regola era fissata prima di guardare i numeri (ADR 0018).");
|
||||||
|
Line($"");
|
||||||
|
Line($"**Lettura onesta.** {Verdict(report.Chosen!, it)}");
|
||||||
|
Line($"");
|
||||||
|
Line($"## Cosa guarda di più");
|
||||||
|
Line($"");
|
||||||
|
Line($"| Indizio | Peso su 100 |");
|
||||||
|
Line($"|---|---|");
|
||||||
|
foreach (var weight in report.Weights)
|
||||||
|
{
|
||||||
|
Line($"| {weight.Group} | {weight.Share:0} |");
|
||||||
|
}
|
||||||
|
|
||||||
|
Line($"");
|
||||||
|
Line($"Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizio. Con tutti i pesi a zero nessun indizio aiuta.");
|
||||||
|
Line($"");
|
||||||
|
Line($"## Ci si può fidare delle probabilità?");
|
||||||
|
Line($"");
|
||||||
|
Line($"Verifica a combinazioni, fasce da 5 punti; un esempio verificato più volte conta come un caso. Contano le fasce con almeno {Judge.BandMin} casi; errore medio {(report.Chosen!.Combined.CalibrationError is { } error ? error * 100 : 0):0.0} punti.");
|
||||||
|
Line($"");
|
||||||
|
Line($"| Stima | Casi | Stimato in media | Andate bene |");
|
||||||
|
Line($"|---|---|---|---|");
|
||||||
|
foreach (var band in report.Chosen.Combined.Bands)
|
||||||
|
{
|
||||||
|
Line($"| {band.From * 100:0}–{band.To * 100:0}% | {band.Cases} | {band.Estimated * 100:0.0}% | {band.Observed * 100:0.0}% |");
|
||||||
|
}
|
||||||
|
|
||||||
|
Line($"");
|
||||||
|
Line($"## Cosa succede adesso");
|
||||||
|
Line($"");
|
||||||
|
Line($"Il modello parte in osservazione: stima ogni segnale e non cambia nessuna operazione. Comincerà a contare solo dopo almeno 300 segnali dal vivo, con probabilità ben tarate e un miglioramento distinguibile dal caso (SPEC 11.5).");
|
||||||
|
return text.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Verdict(Attempt chosen, CultureInfo it)
|
||||||
|
{
|
||||||
|
var (s, f) = (chosen.Combined, chosen.Forward);
|
||||||
|
var probabilities = s.LogLoss < s.BaseLogLoss && f.LogLoss < f.BaseLogLoss
|
||||||
|
? string.Create(it, $"Le stime sono migliori di chi risponde sempre la frequenza di base in tutte e due le prove, ma di poco: errore più basso, {(1 - (s.LogLoss / s.BaseLogLoss)) * 100:0.0}% in meno nelle combinazioni e {(1 - (f.LogLoss / f.BaseLogLoss)) * 100:0.0}% in meno in avanti.")
|
||||||
|
: s.LogLoss >= s.BaseLogLoss && f.LogLoss >= f.BaseLogLoss
|
||||||
|
? "Le stime non sono migliori di chi risponde sempre la frequenza di base: su questo storico il modello non ha trovato niente di solido."
|
||||||
|
: "Le stime sono migliori di chi risponde sempre la frequenza di base in una sola delle due prove: non è un risultato solido.";
|
||||||
|
return probabilities + string.Create(it, $" Con il filtro il guadagno medio per operazione proposta cambia di {s.Improvement:+0.00;-0.00} € nelle combinazioni e di {f.Improvement:+0.00;-0.00} € in avanti.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>An estimate saved when its example was born, with the model that made it.</summary>
|
||||||
|
public sealed record SeenEstimate(Guid ModelId, bool InCharge, Estimate Estimate);
|
||||||
|
|
||||||
|
/// <summary>A week of the watch: the precision on the last cases closed by its end.</summary>
|
||||||
|
public sealed record WeekPrecision(DateOnly Monday, double Precision, int Cases);
|
||||||
|
|
||||||
|
/// <summary>What the nightly check saw (SPEC 11.4).</summary>
|
||||||
|
public sealed record HealthCheck
|
||||||
|
{
|
||||||
|
public DateTimeOffset At { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The version that was checked.</summary>
|
||||||
|
public int? Version { get; init; }
|
||||||
|
|
||||||
|
/// <summary>On the last <see cref="Health.Recent"/> cases of the model in charge; null without both wins and losses.</summary>
|
||||||
|
public double? Precision { get; init; }
|
||||||
|
|
||||||
|
public int Cases { get; init; }
|
||||||
|
|
||||||
|
public bool ErrorDrift { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The groups of clues whose values are too often outside what the model studied.</summary>
|
||||||
|
public IReadOnlyList<string> DriftingClues { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Why the model should stay aside; null when nothing is wrong.</summary>
|
||||||
|
public string? Aside { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ADWIN, written here (SPEC 11.4): it keeps the values since the last change and compares every possible older part with
|
||||||
|
/// the newer one. When two means differ more than chance allows, the older part is dropped: the error has changed.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class Adwin(double delta = 0.002)
|
||||||
|
{
|
||||||
|
private const int MinPart = 10;
|
||||||
|
|
||||||
|
private readonly List<double> _window = [];
|
||||||
|
|
||||||
|
public int Count => _window.Count;
|
||||||
|
|
||||||
|
/// <summary>Adds a value between 0 and 1: 1 when the mean has risen, -1 when it has fallen, 0 when nothing changed.</summary>
|
||||||
|
public int Add(double value)
|
||||||
|
{
|
||||||
|
_window.Add(Math.Clamp(value, 0, 1));
|
||||||
|
var change = 0;
|
||||||
|
while (Cut() is { } cut)
|
||||||
|
{
|
||||||
|
change = cut.Risen ? 1 : -1;
|
||||||
|
_window.RemoveRange(0, cut.At);
|
||||||
|
}
|
||||||
|
|
||||||
|
return change;
|
||||||
|
}
|
||||||
|
|
||||||
|
private (int At, bool Risen)? Cut()
|
||||||
|
{
|
||||||
|
var n = _window.Count;
|
||||||
|
if (n < 2 * MinPart)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var total = _window.Sum();
|
||||||
|
var mean = total / n;
|
||||||
|
var variance = _window.Sum(v => (v - mean) * (v - mean)) / n;
|
||||||
|
var log = Math.Log(2 * Math.Log(n) / delta);
|
||||||
|
var older = 0.0;
|
||||||
|
for (var at = 1; at <= n - MinPart; at++)
|
||||||
|
{
|
||||||
|
older += _window[at - 1];
|
||||||
|
if (at < MinPart)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var m = 1 / ((1.0 / at) + (1.0 / (n - at)));
|
||||||
|
var limit = Math.Sqrt(2 / m * variance * log) + (2 / (3 * m) * log);
|
||||||
|
var (before, after) = (older / at, (total - older) / (n - at));
|
||||||
|
if (Math.Abs(before - after) > limit)
|
||||||
|
{
|
||||||
|
return (at, after > before);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rules that set the model aside (SPEC 11.4, ADR 0018).</summary>
|
||||||
|
public static class Health
|
||||||
|
{
|
||||||
|
public const int Recent = 60;
|
||||||
|
|
||||||
|
/// <summary>The precision counts from this many cases.</summary>
|
||||||
|
public const int MinCases = 40;
|
||||||
|
|
||||||
|
public const double Alarm = 0.50;
|
||||||
|
|
||||||
|
/// <summary>An alarm of the error lasts for this many labelled cases.</summary>
|
||||||
|
public const int AlarmCases = 30;
|
||||||
|
|
||||||
|
/// <summary>A clue drifts when more than this share of the recent cases is outside the 1%–99% it was studied on.</summary>
|
||||||
|
public const double OutsideShare = 0.20;
|
||||||
|
|
||||||
|
/// <summary>A precision in points as it is shown: one under the alarm never reads like the alarm line.</summary>
|
||||||
|
public static int Shown(double precision) => precision < Alarm ? Math.Min((int)Math.Round(precision * 100, MidpointRounding.AwayFromZero), (int)(Alarm * 100) - 1)
|
||||||
|
: (int)Math.Round(precision * 100, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The check on the estimates of the model in charge, the ones it made on trial included: <paramref name="labelled"/> in
|
||||||
|
/// the order the outcomes came, <paramref name="recent"/> the latest live examples with or without an outcome.
|
||||||
|
/// </summary>
|
||||||
|
public static HealthCheck Check(ModelRow champion, IReadOnlyList<Estimate> labelled, IReadOnlyList<Example> recent, DateTimeOffset at)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(champion);
|
||||||
|
ArgumentNullException.ThrowIfNull(labelled);
|
||||||
|
ArgumentNullException.ThrowIfNull(recent);
|
||||||
|
var last = labelled.Skip(Math.Max(0, labelled.Count - Recent)).ToList();
|
||||||
|
var precision = Judge.Precision(last);
|
||||||
|
var error = ErrorDrift(labelled);
|
||||||
|
var clues = champion.Model is { } model ? ClueDrift(model, recent) : [];
|
||||||
|
return new HealthCheck
|
||||||
|
{
|
||||||
|
At = at,
|
||||||
|
Version = champion.Version,
|
||||||
|
Precision = precision,
|
||||||
|
Cases = last.Count,
|
||||||
|
ErrorDrift = error,
|
||||||
|
DriftingClues = clues,
|
||||||
|
Aside = last.Count >= MinCases && precision < Alarm ? AsideCodes.Precision : error ? AsideCodes.ErrorDrift : clues.Count > 0 ? AsideCodes.ClueDrift : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The squared error has risen within the last cases. Computed from the beginning each time: no state to lose.</summary>
|
||||||
|
public static bool ErrorDrift(IReadOnlyList<Estimate> labelled)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(labelled);
|
||||||
|
var adwin = new Adwin();
|
||||||
|
var alarm = -1;
|
||||||
|
for (var i = 0; i < labelled.Count; i++)
|
||||||
|
{
|
||||||
|
var change = adwin.Add(Math.Pow(labelled[i].Probability - (labelled[i].Win ? 1 : 0), 2));
|
||||||
|
alarm = change > 0 ? i : change < 0 ? -1 : alarm;
|
||||||
|
}
|
||||||
|
|
||||||
|
return alarm >= 0 && labelled.Count - alarm <= AlarmCases;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> ClueDrift(TrainedModel model, IReadOnlyList<Example> recent)
|
||||||
|
{
|
||||||
|
var known = recent.Where(e => model.Strategies.Contains(e.Strategy)).ToList();
|
||||||
|
var last = known.Skip(Math.Max(0, known.Count - Recent)).ToList();
|
||||||
|
var drifting = new List<string>();
|
||||||
|
foreach (var clue in model.Clues.Where(c => !c.StartsWith(Clues.StrategyPrefix, StringComparison.Ordinal) && c is not (Clues.WeekSin or Clues.WeekCos)))
|
||||||
|
{
|
||||||
|
var values = last.Where(e => e.Features.ContainsKey(clue)).Select(e => e.Features[clue]).ToList();
|
||||||
|
if (values.Count >= MinCases && model.Ranges.TryGetValue(clue, out var range) && values.Count(v => v < range.Low || v > range.High) > OutsideShare * values.Count)
|
||||||
|
{
|
||||||
|
drifting.Add(Clues.Find(clue)?.Group ?? clue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. drifting.Distinct(StringComparer.Ordinal)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The precision week by week: each on the last cases closed by its end, when they are enough.</summary>
|
||||||
|
public static IReadOnlyList<WeekPrecision> Weeks(IReadOnlyList<Estimate> labelled, DateOnly today, int weeks = 8)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(labelled);
|
||||||
|
var monday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
|
||||||
|
var result = new List<WeekPrecision>();
|
||||||
|
for (var k = weeks - 1; k >= 0; k--)
|
||||||
|
{
|
||||||
|
var start = monday.AddDays(-7 * k);
|
||||||
|
var closed = labelled.Where(e => e.Case.Label!.ClosedDay < start.AddDays(7)).ToList();
|
||||||
|
var last = closed.Skip(Math.Max(0, closed.Count - Recent)).ToList();
|
||||||
|
if (last.Count >= MinCases && Judge.Precision(last) is { } precision)
|
||||||
|
{
|
||||||
|
result.Add(new WeekPrecision(start, precision, last.Count));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether the model may start to count (SPEC 11.5).</summary>
|
||||||
|
public sealed record ActivationCheck(int Evaluated, Scores Scores, double? CalibrationError, double Low, double High)
|
||||||
|
{
|
||||||
|
public const int Needed = 300;
|
||||||
|
|
||||||
|
public const double MaxCalibrationError = 0.05;
|
||||||
|
|
||||||
|
/// <summary>The improvement is measured on at least this many signals of strategies with capital (ADR 0018).</summary>
|
||||||
|
public const int FundedNeeded = 100;
|
||||||
|
|
||||||
|
/// <summary>The signals of strategies with capital at that moment: those the improvement is measured on.</summary>
|
||||||
|
public int Funded { get; init; }
|
||||||
|
|
||||||
|
public bool Enough => Evaluated >= Needed;
|
||||||
|
|
||||||
|
public bool Calibrated => CalibrationError is { } error && error < MaxCalibrationError;
|
||||||
|
|
||||||
|
public bool Improves => Funded >= FundedNeeded && Low > 0;
|
||||||
|
|
||||||
|
public bool Passed => Enough && Calibrated && Improves;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// On the estimates that were in charge when each signal came, whatever version made them, weighed by maturation; the
|
||||||
|
/// improvement only on signals of strategies with capital at that moment, weighed among themselves.
|
||||||
|
/// </summary>
|
||||||
|
public static ActivationCheck Of(IReadOnlyList<Estimate> inCharge, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capital)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(inCharge);
|
||||||
|
var funded = Judge.Weigh([.. inCharge.Where(e => IsFunded(e.Case))], baseRates);
|
||||||
|
var paid = Judge.Score(funded, capital);
|
||||||
|
var scores = Judge.Score(Judge.Weigh(inCharge, baseRates), capital) with { GainWithout = paid.GainWithout, GainWith = paid.GainWith };
|
||||||
|
var (low, high) = Judge.Interval([.. funded.Select(e => (e.Multiplier - 1) * Judge.Gain(e.Case, capital))], [.. funded.Select(e => e.Weight)], 0.90);
|
||||||
|
return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high) { Funded = funded.Count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A signal of a strategy that had capital: zeroing those of a candidate in observation is no merit (SPEC 11.3).</summary>
|
||||||
|
public static bool IsFunded(Example example) => example?.Stage is { } stage && stage != Trading.StrategyStages.Observation;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The trial of the challenger against the model in charge (SPEC 11.4).</summary>
|
||||||
|
public sealed record TrialCheck(int Pairs, int Threshold, double Low, double High, double Mean, double ChallengerPrecision, double ChampionPrecision)
|
||||||
|
{
|
||||||
|
public static readonly IReadOnlyList<int> Thresholds = [100, 150, 200, 250, 300];
|
||||||
|
|
||||||
|
/// <summary>Pairs of estimates on the same example, both with their outcome, in the order the outcomes came.</summary>
|
||||||
|
public static TrialCheck Of(IReadOnlyList<(Estimate Champion, Estimate Challenger)> pairs, IReadOnlyDictionary<string, double> baseRates)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(pairs);
|
||||||
|
var weights = Judge.Weigh([.. pairs.Select(p => p.Champion)], baseRates).Select(e => e.Weight).ToList();
|
||||||
|
var differences = pairs.Select(p => Judge.LogLoss(p.Champion.Win, p.Champion.Probability) - Judge.LogLoss(p.Champion.Win, p.Challenger.Probability)).ToList();
|
||||||
|
var (low, high) = Judge.Interval(differences, weights, 0.95);
|
||||||
|
var total = weights.Sum();
|
||||||
|
return new TrialCheck(pairs.Count, Thresholds.LastOrDefault(t => t <= pairs.Count), low, high, total > 0 ? differences.Zip(weights, (d, w) => d * w).Sum() / total : 0,
|
||||||
|
Judge.Precision([.. pairs.Select(p => p.Challenger)]) ?? 0, Judge.Precision([.. pairs.Select(p => p.Champion)]) ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The advantage of the challenger cannot be told from chance unless the whole interval is above zero.</summary>
|
||||||
|
public bool Wins => Low > 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The multiplier of SPEC 11.1: 1 at the base rate or above, 0 at <paramref name="Zero"/> or more below it, in proportion
|
||||||
|
/// between. <paramref name="Full"/> is how far below the base rate the size is still whole. It can never exceed 1.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record MultiplierRule(double Full, double Zero)
|
||||||
|
{
|
||||||
|
public static readonly MultiplierRule Standard = new(0, 0.10);
|
||||||
|
|
||||||
|
public double Of(double probability, double baseRate)
|
||||||
|
{
|
||||||
|
// A number that is not a number must never move an operation.
|
||||||
|
if (!double.IsFinite(probability) || !double.IsFinite(baseRate) || !double.IsFinite(Full) || !double.IsFinite(Zero) || Zero <= Full)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hair below the base rate is the base rate: a model that always answers the base rate leaves everything as it is.
|
||||||
|
var below = baseRate - probability;
|
||||||
|
return below <= Full + 1e-9 ? 1 : Math.Round(Math.Clamp((Zero - below) / (Zero - Full), 0, 1), 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One estimate on an example whose outcome is known. <see cref="Weight"/> is its weight by maturation.</summary>
|
||||||
|
public sealed record Estimate(Example Case, double Probability, double BaseRate, double Multiplier)
|
||||||
|
{
|
||||||
|
public double Weight { get; init; } = 1;
|
||||||
|
|
||||||
|
public bool Win => Case.Label?.Win == true;
|
||||||
|
|
||||||
|
/// <summary>The estimate says the operation is at least as likely to win as usual.</summary>
|
||||||
|
public bool SaysWin => Probability >= BaseRate - 1e-9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A band of estimated probabilities and how often it went well. An example verified by several combinations is one case.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record CalibrationBand(double From, double To, int Cases, double Estimated, double Observed);
|
||||||
|
|
||||||
|
/// <summary>How good a set of estimates is (SPEC 11.3): the gain per proposed operation counts, not the accuracy.</summary>
|
||||||
|
public sealed record Scores
|
||||||
|
{
|
||||||
|
public int Cases { get; init; }
|
||||||
|
|
||||||
|
public double LogLoss { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The log-loss of who always answers the base rate.</summary>
|
||||||
|
public double BaseLogLoss { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Brier score: what the interface calls "errore sulle probabilità".</summary>
|
||||||
|
public double Brier { get; init; }
|
||||||
|
|
||||||
|
/// <summary>"Previsioni azzeccate": balanced, 50% for who always says the same. Null without both wins and losses.</summary>
|
||||||
|
public double? Precision { get; init; }
|
||||||
|
|
||||||
|
public double GainWithout { get; init; }
|
||||||
|
|
||||||
|
public double GainWith { get; init; }
|
||||||
|
|
||||||
|
public double Improvement => GainWith - GainWithout;
|
||||||
|
|
||||||
|
/// <summary>Mean calibration error on the bands with at least <see cref="Judge.BandMin"/> cases; null with none.</summary>
|
||||||
|
public double? CalibrationError { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<CalibrationBand> Bands { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The measures of SPEC 11.3–11.5.</summary>
|
||||||
|
public static class Judge
|
||||||
|
{
|
||||||
|
/// <summary>A band counts with at least this many cases (SPEC 11.5).</summary>
|
||||||
|
public const int BandMin = 20;
|
||||||
|
|
||||||
|
public const double BandWidth = 0.05;
|
||||||
|
|
||||||
|
/// <summary>What an example earned or lost in euro: the share it asked for, its return, the capital of its strategy.</summary>
|
||||||
|
public static double Gain(Example example, IReadOnlyDictionary<string, double> capital)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(example);
|
||||||
|
ArgumentNullException.ThrowIfNull(capital);
|
||||||
|
return (double)example.Weight * (example.Label?.Result ?? 0) * capital.GetValueOrDefault(example.Strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double LogLoss(bool win, double probability)
|
||||||
|
{
|
||||||
|
var p = Math.Clamp(probability, 1e-6, 1 - 1e-6);
|
||||||
|
return -Math.Log(win ? p : 1 - p);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The weights of SPEC 11.4: losses close before gains, so among what matured so far the losses are too many. In each
|
||||||
|
/// strategy wins and losses count in the proportion of its base rate. Without both in a strategy nothing can be weighed.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<Estimate> Weigh(IReadOnlyList<Estimate> estimates, IReadOnlyDictionary<string, double> baseRates)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(estimates);
|
||||||
|
ArgumentNullException.ThrowIfNull(baseRates);
|
||||||
|
var shares = estimates.GroupBy(e => e.Case.Strategy, StringComparer.Ordinal).ToDictionary(g => g.Key, g => (double)g.Count(e => e.Win) / g.Count(), StringComparer.Ordinal);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. estimates.Select(e =>
|
||||||
|
{
|
||||||
|
var seen = shares[e.Case.Strategy];
|
||||||
|
return seen is > 0 and < 1 && baseRates.TryGetValue(e.Case.Strategy, out var rate)
|
||||||
|
? e with { Weight = e.Win ? rate / seen : (1 - rate) / (1 - seen) }
|
||||||
|
: e with { Weight = 1 };
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The scores of weighed estimates. The gain counts only the <paramref name="funded"/> ones.</summary>
|
||||||
|
public static Scores Score(IReadOnlyList<Estimate> estimates, IReadOnlyDictionary<string, double> capital, Func<Example, bool>? funded = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(estimates);
|
||||||
|
ArgumentNullException.ThrowIfNull(capital);
|
||||||
|
if (estimates.Count == 0)
|
||||||
|
{
|
||||||
|
return new Scores();
|
||||||
|
}
|
||||||
|
|
||||||
|
var total = estimates.Sum(e => e.Weight);
|
||||||
|
var counted = estimates.Where(e => funded?.Invoke(e.Case) ?? true).ToList();
|
||||||
|
var proposals = counted.Sum(e => e.Weight);
|
||||||
|
var bands = Bands(estimates);
|
||||||
|
return new Scores
|
||||||
|
{
|
||||||
|
Cases = estimates.Count,
|
||||||
|
LogLoss = total > 0 ? estimates.Sum(e => e.Weight * LogLoss(e.Win, e.Probability)) / total : 0,
|
||||||
|
BaseLogLoss = total > 0 ? estimates.Sum(e => e.Weight * LogLoss(e.Win, e.BaseRate)) / total : 0,
|
||||||
|
Brier = total > 0 ? estimates.Sum(e => e.Weight * Math.Pow(e.Probability - (e.Win ? 1 : 0), 2)) / total : 0,
|
||||||
|
Precision = Precision(estimates),
|
||||||
|
GainWithout = proposals > 0 ? counted.Sum(e => e.Weight * Gain(e.Case, capital)) / proposals : 0,
|
||||||
|
GainWith = proposals > 0 ? counted.Sum(e => e.Weight * e.Multiplier * Gain(e.Case, capital)) / proposals : 0,
|
||||||
|
CalibrationError = ErrorOf(bands),
|
||||||
|
Bands = bands,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "Previsioni azzeccate" (SPEC 11.3): the mean of two shares, the winners it had estimated at the base rate or above
|
||||||
|
/// and the losers it had estimated below. Chance, or always the same answer, stays at 50%.
|
||||||
|
/// </summary>
|
||||||
|
public static double? Precision(IReadOnlyList<Estimate> estimates)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(estimates);
|
||||||
|
var wins = estimates.Where(e => e.Win).ToList();
|
||||||
|
var losses = estimates.Where(e => !e.Win).ToList();
|
||||||
|
return wins.Count == 0 || losses.Count == 0
|
||||||
|
? null
|
||||||
|
: (((double)wins.Count(e => e.SaysWin) / wins.Count) + ((double)losses.Count(e => !e.SaysWin) / losses.Count)) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<CalibrationBand> Bands(IReadOnlyList<Estimate> estimates)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(estimates);
|
||||||
|
var last = (int)Math.Round(1 / BandWidth) - 1;
|
||||||
|
var distinct = estimates.Select(e => e.Case).Distinct<object>(ReferenceEqualityComparer.Instance).Count();
|
||||||
|
var repeats = distinct > 0 ? (double)estimates.Count / distinct : 1;
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. estimates.GroupBy(e => Math.Clamp((int)Math.Floor((e.Probability / BandWidth) + 1e-9), 0, last)).OrderBy(g => g.Key).Select(g =>
|
||||||
|
{
|
||||||
|
var weight = g.Sum(e => e.Weight);
|
||||||
|
return new CalibrationBand(Math.Round(g.Key * BandWidth, 2), Math.Round((g.Key + 1) * BandWidth, 2), (int)Math.Round(g.Count() / repeats, MidpointRounding.AwayFromZero),
|
||||||
|
weight > 0 ? g.Sum(e => e.Weight * e.Probability) / weight : 0, weight > 0 ? g.Sum(e => e.Weight * (e.Win ? 1 : 0)) / weight : 0);
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The mean distance between estimated and observed on the bands that count; null with none.</summary>
|
||||||
|
public static double? ErrorOf(IReadOnlyList<CalibrationBand> bands)
|
||||||
|
{
|
||||||
|
var solid = bands.Where(b => b.Cases >= BandMin).ToList();
|
||||||
|
return solid.Count > 0 ? solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A bootstrap interval of the weighted mean of <paramref name="values"/> that keeps neighbours together: blocks of
|
||||||
|
/// <paramref name="block"/> in a row, because operations close in time win and lose together. With fewer than three
|
||||||
|
/// blocks nothing can be said: the interval is everything.
|
||||||
|
/// </summary>
|
||||||
|
public static (double Low, double High) Interval(IReadOnlyList<double> values, IReadOnlyList<double> weights, double confidence, int block = 10, int rounds = 2000, long seed = 20_261_201)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
|
ArgumentNullException.ThrowIfNull(weights);
|
||||||
|
var n = values.Count;
|
||||||
|
if (n == 0)
|
||||||
|
{
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
var size = Math.Max(block, 1);
|
||||||
|
if (n < 3 * size)
|
||||||
|
{
|
||||||
|
return (double.NegativeInfinity, double.PositiveInfinity);
|
||||||
|
}
|
||||||
|
|
||||||
|
var random = new FixedRandom(seed);
|
||||||
|
var means = new double[rounds];
|
||||||
|
for (var r = 0; r < rounds; r++)
|
||||||
|
{
|
||||||
|
double sum = 0, weight = 0;
|
||||||
|
for (var filled = 0; filled < n;)
|
||||||
|
{
|
||||||
|
var start = random.Next(n);
|
||||||
|
for (var k = 0; k < size && filled < n; k++, filled++)
|
||||||
|
{
|
||||||
|
var at = (start + k) % n;
|
||||||
|
sum += weights[at] * values[at];
|
||||||
|
weight += weights[at];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
means[r] = weight > 0 ? sum / weight : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Array.Sort(means);
|
||||||
|
var tail = (1 - confidence) / 2;
|
||||||
|
return (means[(int)Math.Floor(tail * (rounds - 1))], means[(int)Math.Ceiling((1 - tail) * (rounds - 1))]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A split of the examples: which train and which test, by position.</summary>
|
||||||
|
public sealed record Split(IReadOnlyList<int> Train, IReadOnlyList<int> Test);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Splits that never mix in time (SPEC 11.3): an example lives from its decision to the close of its operation, and one
|
||||||
|
/// that overlaps a test example, or starts within the embargo after one, never trains for it. The examples are in order of decision.
|
||||||
|
/// </summary>
|
||||||
|
public static class CaseSplits
|
||||||
|
{
|
||||||
|
/// <summary>Days after a test operation in which no training example may start.</summary>
|
||||||
|
public const int Embargo = 10;
|
||||||
|
|
||||||
|
/// <summary>Windows that go forward: the first part trains, the rest is verified in pieces, each on what was already over before it.</summary>
|
||||||
|
public static IReadOnlyList<Split> Forward(IReadOnlyList<Example> cases, int pieces = 5, double first = 0.4)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(cases);
|
||||||
|
var start = (int)(cases.Count * first);
|
||||||
|
var splits = new List<Split>();
|
||||||
|
for (var k = 0; k < pieces; k++)
|
||||||
|
{
|
||||||
|
var from = start + (int)((long)(cases.Count - start) * k / pieces);
|
||||||
|
var to = start + (int)((long)(cases.Count - start) * (k + 1) / pieces);
|
||||||
|
if (to > from)
|
||||||
|
{
|
||||||
|
var begins = cases[from].Day;
|
||||||
|
splits.Add(new Split([.. Enumerable.Range(0, from).Where(i => Closed(cases[i]) < begins)], [.. Enumerable.Range(from, to - from)]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return splits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every choice of <paramref name="tested"/> groups out of <paramref name="groups"/>, purged and with embargo.</summary>
|
||||||
|
public static IReadOnlyList<Split> Combinatorial(IReadOnlyList<Example> cases, int groups = 6, int tested = 2)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(cases);
|
||||||
|
var group = Enumerable.Range(0, cases.Count).Select(i => (int)((long)i * groups / cases.Count)).ToArray();
|
||||||
|
var splits = new List<Split>();
|
||||||
|
foreach (var chosen in Choices(groups, tested))
|
||||||
|
{
|
||||||
|
var test = Enumerable.Range(0, cases.Count).Where(i => chosen.Contains(group[i])).ToList();
|
||||||
|
splits.Add(new Split(Purge(cases, test), test));
|
||||||
|
}
|
||||||
|
|
||||||
|
return splits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Consecutive folds, purged: for the estimates the calibration is fitted on.</summary>
|
||||||
|
public static IReadOnlyList<Split> Folds(IReadOnlyList<Example> cases, int folds = 5) => Combinatorial(cases, folds, 1);
|
||||||
|
|
||||||
|
private static List<int> Purge(IReadOnlyList<Example> cases, List<int> test)
|
||||||
|
{
|
||||||
|
// The lives of the test examples, embargo included, joined where they touch.
|
||||||
|
var lives = new List<(DateOnly From, DateOnly To)>();
|
||||||
|
foreach (var (from, to) in test.Select(i => (From: cases[i].Day, To: Closed(cases[i]).AddDays(Embargo))).OrderBy(x => x.From))
|
||||||
|
{
|
||||||
|
if (lives.Count > 0 && from <= lives[^1].To)
|
||||||
|
{
|
||||||
|
lives[^1] = (lives[^1].From, to > lives[^1].To ? to : lives[^1].To);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
lives.Add((from, to));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var inTest = test.ToHashSet();
|
||||||
|
return [.. Enumerable.Range(0, cases.Count).Where(i => !inTest.Contains(i) && !lives.Any(l => cases[i].Day <= l.To && Closed(cases[i]) >= l.From))];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly Closed(Example example) => example.Label?.ClosedDay ?? DateOnly.MaxValue.AddDays(-Embargo);
|
||||||
|
|
||||||
|
private static IEnumerable<HashSet<int>> Choices(int groups, int tested)
|
||||||
|
{
|
||||||
|
var picks = Enumerable.Range(0, tested).ToArray();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
yield return [.. picks];
|
||||||
|
var at = tested - 1;
|
||||||
|
while (at >= 0 && picks[at] == groups - tested + at)
|
||||||
|
{
|
||||||
|
at--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (at < 0)
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
picks[at]++;
|
||||||
|
for (var k = at + 1; k < tested; k++)
|
||||||
|
{
|
||||||
|
picks[k] = picks[k - 1] + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,701 @@
|
|||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>Names of the learners (SPEC 11.3, ADR 0018): all written here.</summary>
|
||||||
|
public static class LearnerNames
|
||||||
|
{
|
||||||
|
/// <summary>Regularised logistic regression: the reference.</summary>
|
||||||
|
public const string Logistic = "logistic";
|
||||||
|
|
||||||
|
/// <summary>Boosted trees: the main one.</summary>
|
||||||
|
public const string Boosting = "boosting";
|
||||||
|
|
||||||
|
/// <summary>Random forest: it must beat the others at the same rules.</summary>
|
||||||
|
public const string Forest = "forest";
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> All = [Boosting, Logistic, Forest];
|
||||||
|
|
||||||
|
public static string Label(string learner) => learner switch
|
||||||
|
{
|
||||||
|
Logistic => "Regressione logistica",
|
||||||
|
Boosting => "Alberi potenziati",
|
||||||
|
Forest => "Foresta casuale",
|
||||||
|
_ => learner,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SplitMix64: the same sequence on every platform and version, so the same data always give the same model.</summary>
|
||||||
|
public sealed class FixedRandom(long seed)
|
||||||
|
{
|
||||||
|
private ulong _state = unchecked((ulong)seed);
|
||||||
|
|
||||||
|
public ulong NextBits()
|
||||||
|
{
|
||||||
|
var z = _state += 0x9E3779B97F4A7C15UL;
|
||||||
|
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||||||
|
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||||||
|
return z ^ (z >> 31);
|
||||||
|
}
|
||||||
|
|
||||||
|
public double NextDouble() => (NextBits() >> 11) * (1.0 / (1UL << 53));
|
||||||
|
|
||||||
|
public int Next(int below) => (int)(NextDouble() * below);
|
||||||
|
|
||||||
|
public void Shuffle<T>(IList<T> items)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(items);
|
||||||
|
for (var i = items.Count - 1; i > 0; i--)
|
||||||
|
{
|
||||||
|
var j = Next(i + 1);
|
||||||
|
(items[i], items[j]) = (items[j], items[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a learner has learned: a score in log-odds for a row of clues (NaN: the clue is missing).</summary>
|
||||||
|
public sealed record Learned
|
||||||
|
{
|
||||||
|
public string Learner { get; init; } = "";
|
||||||
|
|
||||||
|
public LinearBody? Linear { get; init; }
|
||||||
|
|
||||||
|
public TreesBody? Trees { get; init; }
|
||||||
|
|
||||||
|
public double Score(IReadOnlyList<double> row) => Linear?.Score(row) ?? Trees?.Score(row) ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A logistic regression on standardised clues: a missing clue counts as its mean.</summary>
|
||||||
|
public sealed record LinearBody(double Intercept, IReadOnlyList<double> Weights, IReadOnlyList<double> Means, IReadOnlyList<double> Scales)
|
||||||
|
{
|
||||||
|
public double Score(IReadOnlyList<double> row)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(row);
|
||||||
|
var score = Intercept;
|
||||||
|
for (var j = 0; j < Weights.Count; j++)
|
||||||
|
{
|
||||||
|
if (double.IsFinite(row[j]))
|
||||||
|
{
|
||||||
|
// A value far beyond what was studied must not carry the sum away.
|
||||||
|
score += Weights[j] * Math.Clamp((row[j] - Means[j]) / Scales[j], -5, 5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Trees: summed with a step (boosting) or averaged as probabilities (forest).</summary>
|
||||||
|
public sealed record TreesBody(double Start, double Rate, bool Average, IReadOnlyList<Tree> Trees)
|
||||||
|
{
|
||||||
|
public double Score(IReadOnlyList<double> row)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(row);
|
||||||
|
if (Trees.Count == 0)
|
||||||
|
{
|
||||||
|
return Start;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sum = 0.0;
|
||||||
|
foreach (var tree in Trees)
|
||||||
|
{
|
||||||
|
sum += tree.Value(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Average ? Odds.Logit(sum / Trees.Count) : Start + (Rate * sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A small tree as arrays: a node with no feature (-1) is a leaf.</summary>
|
||||||
|
public sealed record Tree(IReadOnlyList<int> Feature, IReadOnlyList<double> Threshold, IReadOnlyList<int> Left, IReadOnlyList<int> Right, IReadOnlyList<bool> MissingLeft, IReadOnlyList<double> Values)
|
||||||
|
{
|
||||||
|
public double Value(IReadOnlyList<double> row)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(row);
|
||||||
|
var node = 0;
|
||||||
|
while (Feature[node] >= 0)
|
||||||
|
{
|
||||||
|
var value = row[Feature[node]];
|
||||||
|
node = (double.IsFinite(value) ? value <= Threshold[node] : MissingLeft[node]) ? Left[node] : Right[node];
|
||||||
|
}
|
||||||
|
|
||||||
|
return Values[node];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Log-odds and probabilities.</summary>
|
||||||
|
public static class Odds
|
||||||
|
{
|
||||||
|
public const double Epsilon = 1e-4;
|
||||||
|
|
||||||
|
public static double Logit(double probability)
|
||||||
|
{
|
||||||
|
var p = Math.Clamp(probability, Epsilon, 1 - Epsilon);
|
||||||
|
return Math.Log(p / (1 - p));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double Probability(double score) => 1 / (1 + Math.Exp(-Math.Clamp(score, -35, 35)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Fits a learner on rows of clues and outcomes. The same input always gives the same result.</summary>
|
||||||
|
public static class Learners
|
||||||
|
{
|
||||||
|
private const int Bins = 32;
|
||||||
|
|
||||||
|
public static Learned Fit(string learner, IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(rows);
|
||||||
|
ArgumentNullException.ThrowIfNull(wins);
|
||||||
|
if (rows.Count == 0 || rows.Count != wins.Count)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Rows and outcomes must be as many, and not zero.", nameof(rows));
|
||||||
|
}
|
||||||
|
|
||||||
|
return learner switch
|
||||||
|
{
|
||||||
|
LearnerNames.Logistic => new Learned { Learner = learner, Linear = Logistic(rows, wins) },
|
||||||
|
LearnerNames.Boosting => new Learned { Learner = learner, Trees = Boosting(rows, wins, seed) },
|
||||||
|
LearnerNames.Forest => new Learned { Learner = learner, Trees = Forest(rows, wins, seed) },
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(learner), learner, "Unknown learner."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Logistic regression ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Strength of the L2 penalty, in examples' worth of information per clue.</summary>
|
||||||
|
private const double Ridge = 10;
|
||||||
|
|
||||||
|
private static LinearBody Logistic(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins)
|
||||||
|
{
|
||||||
|
var d = rows[0].Length;
|
||||||
|
var means = new double[d];
|
||||||
|
var scales = new double[d];
|
||||||
|
for (var j = 0; j < d; j++)
|
||||||
|
{
|
||||||
|
var values = rows.Select(r => r[j]).Where(double.IsFinite).ToList();
|
||||||
|
means[j] = values.Count > 0 ? values.Average() : 0;
|
||||||
|
var variance = values.Count > 1 ? values.Sum(v => (v - means[j]) * (v - means[j])) / values.Count : 0;
|
||||||
|
scales[j] = variance > 1e-18 ? Math.Sqrt(variance) : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var x = rows.Select(r => r.Select((v, j) => double.IsFinite(v) ? Math.Clamp((v - means[j]) / scales[j], -5, 5) : 0).ToArray()).ToList();
|
||||||
|
var beta = new double[d + 1];
|
||||||
|
beta[0] = Odds.Logit((double)wins.Count(w => w) / wins.Count);
|
||||||
|
for (var step = 0; step < 50; step++)
|
||||||
|
{
|
||||||
|
// One Newton step of the penalised likelihood: the intercept is not penalised.
|
||||||
|
var gradient = new double[d + 1];
|
||||||
|
var hessian = new double[d + 1, d + 1];
|
||||||
|
for (var i = 0; i < x.Count; i++)
|
||||||
|
{
|
||||||
|
var score = beta[0];
|
||||||
|
for (var j = 0; j < d; j++)
|
||||||
|
{
|
||||||
|
score += beta[j + 1] * x[i][j];
|
||||||
|
}
|
||||||
|
|
||||||
|
var p = Odds.Probability(score);
|
||||||
|
var error = (wins[i] ? 1 : 0) - p;
|
||||||
|
var weight = Math.Max(p * (1 - p), 1e-6);
|
||||||
|
for (var a = 0; a <= d; a++)
|
||||||
|
{
|
||||||
|
var xa = a == 0 ? 1 : x[i][a - 1];
|
||||||
|
gradient[a] += error * xa;
|
||||||
|
for (var b = 0; b <= a; b++)
|
||||||
|
{
|
||||||
|
hessian[a, b] += weight * xa * (b == 0 ? 1 : x[i][b - 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var a = 0; a <= d; a++)
|
||||||
|
{
|
||||||
|
if (a > 0)
|
||||||
|
{
|
||||||
|
gradient[a] -= Ridge * beta[a];
|
||||||
|
hessian[a, a] += Ridge;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var b = a + 1; b <= d; b++)
|
||||||
|
{
|
||||||
|
hessian[a, b] = hessian[b, a];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var delta = Solve(hessian, gradient);
|
||||||
|
var largest = 0.0;
|
||||||
|
for (var a = 0; a <= d; a++)
|
||||||
|
{
|
||||||
|
var change = Math.Clamp(delta[a], -2, 2);
|
||||||
|
beta[a] += change;
|
||||||
|
largest = Math.Max(largest, Math.Abs(change));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (largest < 1e-9)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LinearBody(beta[0], beta[1..], means, scales);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double[] Solve(double[,] matrix, double[] right)
|
||||||
|
{
|
||||||
|
var n = right.Length;
|
||||||
|
var a = (double[,])matrix.Clone();
|
||||||
|
var b = (double[])right.Clone();
|
||||||
|
for (var column = 0; column < n; column++)
|
||||||
|
{
|
||||||
|
var pivot = column;
|
||||||
|
for (var row = column + 1; row < n; row++)
|
||||||
|
{
|
||||||
|
if (Math.Abs(a[row, column]) > Math.Abs(a[pivot, column]))
|
||||||
|
{
|
||||||
|
pivot = row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Math.Abs(a[pivot, column]) < 1e-12)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pivot != column)
|
||||||
|
{
|
||||||
|
for (var k = 0; k < n; k++)
|
||||||
|
{
|
||||||
|
(a[column, k], a[pivot, k]) = (a[pivot, k], a[column, k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
(b[column], b[pivot]) = (b[pivot], b[column]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var row = column + 1; row < n; row++)
|
||||||
|
{
|
||||||
|
var factor = a[row, column] / a[column, column];
|
||||||
|
for (var k = column; k < n; k++)
|
||||||
|
{
|
||||||
|
a[row, k] -= factor * a[column, k];
|
||||||
|
}
|
||||||
|
|
||||||
|
b[row] -= factor * b[column];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var solution = new double[n];
|
||||||
|
for (var row = n - 1; row >= 0; row--)
|
||||||
|
{
|
||||||
|
var sum = b[row];
|
||||||
|
for (var k = row + 1; k < n; k++)
|
||||||
|
{
|
||||||
|
sum -= a[row, k] * solution[k];
|
||||||
|
}
|
||||||
|
|
||||||
|
solution[row] = Math.Abs(a[row, row]) < 1e-12 ? 0 : sum / a[row, row];
|
||||||
|
}
|
||||||
|
|
||||||
|
return solution;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Trees --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private sealed record Shape(int Depth, int MinLeaf, double Lambda, double MinGain, int Features);
|
||||||
|
|
||||||
|
private static TreesBody Boosting(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
|
||||||
|
{
|
||||||
|
const double rate = 0.05;
|
||||||
|
const int count = 150;
|
||||||
|
var n = rows.Count;
|
||||||
|
var random = new FixedRandom(seed);
|
||||||
|
var grid = new Grid(rows, Bins);
|
||||||
|
var start = Odds.Logit((double)wins.Count(w => w) / n);
|
||||||
|
var scores = Enumerable.Repeat(start, n).ToArray();
|
||||||
|
var gradient = new double[n];
|
||||||
|
var hessian = new double[n];
|
||||||
|
var shape = new Shape(3, MinLeaf(n), 10, 0.05, rows[0].Length);
|
||||||
|
var trees = new List<Tree>(count);
|
||||||
|
for (var t = 0; t < count; t++)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var p = Odds.Probability(scores[i]);
|
||||||
|
gradient[i] = (wins[i] ? 1 : 0) - p;
|
||||||
|
hessian[i] = Math.Max(p * (1 - p), 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every tree sees a random 70% of the examples: less noise learned by heart.
|
||||||
|
var members = Enumerable.Range(0, n).Where(_ => random.NextDouble() < 0.7).ToArray();
|
||||||
|
if (members.Length < 2)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tree = Grow(grid, members, gradient, hessian, shape, random);
|
||||||
|
if (tree.Feature[0] < 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
trees.Add(tree);
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
scores[i] += rate * tree.Value(rows[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TreesBody(start, rate, false, trees);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TreesBody Forest(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
|
||||||
|
{
|
||||||
|
const int count = 200;
|
||||||
|
var n = rows.Count;
|
||||||
|
var d = rows[0].Length;
|
||||||
|
var random = new FixedRandom(seed ^ 0x5DEECE66DL);
|
||||||
|
var grid = new Grid(rows, Bins);
|
||||||
|
var share = (double)wins.Count(w => w) / n;
|
||||||
|
|
||||||
|
// With the outcome as gradient and 1 as curvature a leaf is its share of wins, pulled a little towards the mean.
|
||||||
|
var gradient = wins.Select(w => (w ? 1 : 0) - share).ToArray();
|
||||||
|
var hessian = Enumerable.Repeat(1.0, n).ToArray();
|
||||||
|
var shape = new Shape(4, MinLeaf(n), 5, 0.02, Math.Max(2, (int)Math.Ceiling(Math.Sqrt(d))));
|
||||||
|
var trees = new List<Tree>(count);
|
||||||
|
for (var t = 0; t < count; t++)
|
||||||
|
{
|
||||||
|
var members = Enumerable.Range(0, n).Select(_ => random.Next(n)).Order().ToArray();
|
||||||
|
var tree = Grow(grid, members, gradient, hessian, shape, random);
|
||||||
|
trees.Add(tree with { Values = [.. tree.Values.Select(v => Math.Clamp(share + v, 0, 1))] });
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TreesBody(0, 1, true, trees);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Many examples per leaf (ADR 0018): 40, fewer only when there are not enough of them to split at all.</summary>
|
||||||
|
public static int MinLeaf(int examples) => Math.Clamp(examples / 8, 10, 40);
|
||||||
|
|
||||||
|
/// <summary>The values of each clue cut in a few bins of about the same number of examples.</summary>
|
||||||
|
private sealed class Grid
|
||||||
|
{
|
||||||
|
public const byte Missing = 255;
|
||||||
|
|
||||||
|
public Grid(IReadOnlyList<double[]> rows, int bins)
|
||||||
|
{
|
||||||
|
var d = rows[0].Length;
|
||||||
|
Cuts = new double[d][];
|
||||||
|
Bin = new byte[d][];
|
||||||
|
for (var j = 0; j < d; j++)
|
||||||
|
{
|
||||||
|
var values = rows.Select(r => r[j]).Where(double.IsFinite).Order().ToArray();
|
||||||
|
var cuts = new List<double>();
|
||||||
|
if (values.Length > 0)
|
||||||
|
{
|
||||||
|
for (var k = 1; k < bins; k++)
|
||||||
|
{
|
||||||
|
// A cut lies halfway between two different values.
|
||||||
|
var at = (int)((long)k * values.Length / bins);
|
||||||
|
if (at > 0 && values[at] > values[at - 1])
|
||||||
|
{
|
||||||
|
cuts.Add((values[at] + values[at - 1]) / 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Few different values: the jumps may fall between two quantiles.
|
||||||
|
var distinct = values.Distinct().ToList();
|
||||||
|
if (distinct.Count <= bins)
|
||||||
|
{
|
||||||
|
cuts = [.. distinct.Zip(distinct.Skip(1), (a, b) => (a + b) / 2)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Cuts[j] = [.. cuts.Distinct().Order()];
|
||||||
|
Bin[j] = [.. rows.Select(r => BinOf(Cuts[j], r[j]))];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public double[][] Cuts { get; }
|
||||||
|
|
||||||
|
public byte[][] Bin { get; }
|
||||||
|
|
||||||
|
private static byte BinOf(double[] cuts, double value)
|
||||||
|
{
|
||||||
|
if (!double.IsFinite(value))
|
||||||
|
{
|
||||||
|
return Missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
var bin = 0;
|
||||||
|
while (bin < cuts.Length && value > cuts[bin])
|
||||||
|
{
|
||||||
|
bin++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (byte)bin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Tree Grow(Grid grid, int[] members, double[] gradient, double[] hessian, Shape shape, FixedRandom random)
|
||||||
|
{
|
||||||
|
var feature = new List<int>();
|
||||||
|
var threshold = new List<double>();
|
||||||
|
var left = new List<int>();
|
||||||
|
var right = new List<int>();
|
||||||
|
var missingLeft = new List<bool>();
|
||||||
|
var values = new List<double>();
|
||||||
|
Add(members, 0);
|
||||||
|
return new Tree(feature, threshold, left, right, missingLeft, values);
|
||||||
|
|
||||||
|
int Add(int[] inside, int depth)
|
||||||
|
{
|
||||||
|
var node = feature.Count;
|
||||||
|
feature.Add(-1);
|
||||||
|
threshold.Add(0);
|
||||||
|
left.Add(-1);
|
||||||
|
right.Add(-1);
|
||||||
|
missingLeft.Add(true);
|
||||||
|
double g = 0, h = 0;
|
||||||
|
foreach (var i in inside)
|
||||||
|
{
|
||||||
|
g += gradient[i];
|
||||||
|
h += hessian[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
values.Add(g / (h + shape.Lambda));
|
||||||
|
if (depth >= shape.Depth || inside.Length < 2 * shape.MinLeaf || BestSplit(inside, g, h) is not { } best)
|
||||||
|
{
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
feature[node] = best.Feature;
|
||||||
|
threshold[node] = grid.Cuts[best.Feature][best.Cut];
|
||||||
|
missingLeft[node] = best.MissingLeft;
|
||||||
|
var bins = grid.Bin[best.Feature];
|
||||||
|
bool GoesLeft(int i) => bins[i] == Grid.Missing ? best.MissingLeft : bins[i] <= best.Cut;
|
||||||
|
left[node] = Add([.. inside.Where(GoesLeft)], depth + 1);
|
||||||
|
right[node] = Add([.. inside.Where(i => !GoesLeft(i))], depth + 1);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
(int Feature, int Cut, bool MissingLeft)? BestSplit(int[] inside, double g, double h)
|
||||||
|
{
|
||||||
|
var d = grid.Cuts.Length;
|
||||||
|
var candidates = Enumerable.Range(0, d).ToList();
|
||||||
|
if (shape.Features < d)
|
||||||
|
{
|
||||||
|
random.Shuffle(candidates);
|
||||||
|
candidates = [.. candidates.Take(shape.Features).Order()];
|
||||||
|
}
|
||||||
|
|
||||||
|
var parent = g * g / (h + shape.Lambda);
|
||||||
|
var bestGain = shape.MinGain;
|
||||||
|
(int, int, bool)? best = null;
|
||||||
|
Span<double> sumG = stackalloc double[Bins + 1];
|
||||||
|
Span<double> sumH = stackalloc double[Bins + 1];
|
||||||
|
Span<int> counts = stackalloc int[Bins + 1];
|
||||||
|
foreach (var j in candidates)
|
||||||
|
{
|
||||||
|
var cuts = grid.Cuts[j].Length;
|
||||||
|
if (cuts == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
sumG.Clear();
|
||||||
|
sumH.Clear();
|
||||||
|
counts.Clear();
|
||||||
|
double missingG = 0, missingH = 0;
|
||||||
|
var missing = 0;
|
||||||
|
var bins = grid.Bin[j];
|
||||||
|
foreach (var i in inside)
|
||||||
|
{
|
||||||
|
if (bins[i] == Grid.Missing)
|
||||||
|
{
|
||||||
|
missingG += gradient[i];
|
||||||
|
missingH += hessian[i];
|
||||||
|
missing++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sumG[bins[i]] += gradient[i];
|
||||||
|
sumH[bins[i]] += hessian[i];
|
||||||
|
counts[bins[i]]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
double leftG = 0, leftH = 0;
|
||||||
|
var leftN = 0;
|
||||||
|
for (var cut = 0; cut < cuts; cut++)
|
||||||
|
{
|
||||||
|
leftG += sumG[cut];
|
||||||
|
leftH += sumH[cut];
|
||||||
|
leftN += counts[cut];
|
||||||
|
for (var side = 0; side < (missing > 0 ? 2 : 1); side++)
|
||||||
|
{
|
||||||
|
var missingGoesLeft = side == 0;
|
||||||
|
var gl = leftG + (missingGoesLeft ? missingG : 0);
|
||||||
|
var hl = leftH + (missingGoesLeft ? missingH : 0);
|
||||||
|
var nl = leftN + (missingGoesLeft ? missing : 0);
|
||||||
|
var nr = inside.Length - nl;
|
||||||
|
if (nl < shape.MinLeaf || nr < shape.MinLeaf)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var gain = (gl * gl / (hl + shape.Lambda)) + ((g - gl) * (g - gl) / (h - hl + shape.Lambda)) - parent;
|
||||||
|
if (gain > bestGain + 1e-12)
|
||||||
|
{
|
||||||
|
bestGain = gain;
|
||||||
|
best = (j, cut, missingGoesLeft);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// From a score to a probability that can be trusted (SPEC 11.3), fitted on scores the learner had not studied: Platt with
|
||||||
|
/// few cases, isotonic with many. A score that tells nothing, or the opposite, becomes the plain share of wins.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record Calibration
|
||||||
|
{
|
||||||
|
public const string PlattKind = "platt";
|
||||||
|
public const string IsotonicKind = "isotonic";
|
||||||
|
|
||||||
|
/// <summary>Below this many cases the isotonic steps would follow the noise.</summary>
|
||||||
|
public const int IsotonicFrom = 1000;
|
||||||
|
|
||||||
|
public string Kind { get; init; } = PlattKind;
|
||||||
|
|
||||||
|
public double Slope { get; init; } = 1;
|
||||||
|
|
||||||
|
public double Offset { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<double> Scores { get; init; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<double> Values { get; init; } = [];
|
||||||
|
|
||||||
|
public double Probability(double score)
|
||||||
|
{
|
||||||
|
if (Kind != IsotonicKind || Scores.Count == 0)
|
||||||
|
{
|
||||||
|
return Odds.Probability((Slope * score) + Offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (score <= Scores[0])
|
||||||
|
{
|
||||||
|
return Values[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 1; i < Scores.Count; i++)
|
||||||
|
{
|
||||||
|
if (score <= Scores[i])
|
||||||
|
{
|
||||||
|
var share = (score - Scores[i - 1]) / (Scores[i] - Scores[i - 1]);
|
||||||
|
return Values[i - 1] + (share * (Values[i] - Values[i - 1]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Values[^1];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Calibration Fit(IReadOnlyList<double> scores, IReadOnlyList<bool> wins) =>
|
||||||
|
scores?.Count >= IsotonicFrom ? Isotonic(scores, wins) : Platt(scores ?? [], wins);
|
||||||
|
|
||||||
|
public static Calibration Platt(IReadOnlyList<double> scores, IReadOnlyList<bool> wins)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(scores);
|
||||||
|
ArgumentNullException.ThrowIfNull(wins);
|
||||||
|
var positives = wins.Count(w => w);
|
||||||
|
var flat = new Calibration { Slope = 0, Offset = Odds.Logit((positives + 1.0) / (wins.Count + 2)) };
|
||||||
|
if (positives == 0 || positives == wins.Count || scores.Distinct().Count() < 2)
|
||||||
|
{
|
||||||
|
return flat;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Platt's smoothed targets, then Newton on two numbers.
|
||||||
|
var high = (positives + 1.0) / (positives + 2);
|
||||||
|
var low = 1.0 / (wins.Count - positives + 2);
|
||||||
|
double slope = 0, offset = flat.Offset;
|
||||||
|
for (var step = 0; step < 100; step++)
|
||||||
|
{
|
||||||
|
double ga = 0, gb = 0, haa = 1e-9, hab = 0, hbb = 1e-9;
|
||||||
|
for (var i = 0; i < scores.Count; i++)
|
||||||
|
{
|
||||||
|
var p = Odds.Probability((slope * scores[i]) + offset);
|
||||||
|
var error = (wins[i] ? high : low) - p;
|
||||||
|
var weight = Math.Max(p * (1 - p), 1e-9);
|
||||||
|
ga += error * scores[i];
|
||||||
|
gb += error;
|
||||||
|
haa += weight * scores[i] * scores[i];
|
||||||
|
hab += weight * scores[i];
|
||||||
|
hbb += weight;
|
||||||
|
}
|
||||||
|
|
||||||
|
var determinant = (haa * hbb) - (hab * hab);
|
||||||
|
if (Math.Abs(determinant) < 1e-15)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var da = Math.Clamp(((ga * hbb) - (gb * hab)) / determinant, -5, 5);
|
||||||
|
var db = Math.Clamp(((gb * haa) - (ga * hab)) / determinant, -5, 5);
|
||||||
|
slope += da;
|
||||||
|
offset += db;
|
||||||
|
if (Math.Abs(da) < 1e-10 && Math.Abs(db) < 1e-10)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A negative slope says the learner was wrong more than right where it had not studied: it knows nothing.
|
||||||
|
return slope > 0 && double.IsFinite(slope) && double.IsFinite(offset) ? new Calibration { Slope = slope, Offset = offset } : flat;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pool adjacent violators, then a line through the middle of each step. A step of fewer than <paramref name="minPool"/>
|
||||||
|
/// cases joins its neighbour: two cases at the edge say nothing of a probability. Never exactly 0 or 1.
|
||||||
|
/// </summary>
|
||||||
|
public static Calibration Isotonic(IReadOnlyList<double> scores, IReadOnlyList<bool> wins, int minPool = Judge.BandMin)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(scores);
|
||||||
|
ArgumentNullException.ThrowIfNull(wins);
|
||||||
|
var blocks = new List<(double Score, double Wins, double Count)>();
|
||||||
|
foreach (var same in scores.Select((s, i) => (Score: s, Win: wins[i])).GroupBy(x => x.Score).OrderBy(g => g.Key))
|
||||||
|
{
|
||||||
|
blocks.Add((same.Key * same.Count(), same.Count(x => x.Win), same.Count()));
|
||||||
|
while (blocks.Count > 1 && blocks[^2].Wins / blocks[^2].Count >= blocks[^1].Wins / blocks[^1].Count)
|
||||||
|
{
|
||||||
|
var (a, b) = (blocks[^2], blocks[^1]);
|
||||||
|
blocks.RemoveAt(blocks.Count - 1);
|
||||||
|
blocks[^1] = (a.Score + b.Score, a.Wins + b.Wins, a.Count + b.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Neighbours joined keep the order: the share of the two together is between the shares of each.
|
||||||
|
for (var i = 0; i < blocks.Count && blocks.Count > 1;)
|
||||||
|
{
|
||||||
|
if (blocks[i].Count >= minPool)
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var left = i == blocks.Count - 1 ? i - 1 : i;
|
||||||
|
var (a, b) = (blocks[left], blocks[left + 1]);
|
||||||
|
blocks.RemoveAt(left + 1);
|
||||||
|
blocks[left] = (a.Score + b.Score, a.Wins + b.Wins, a.Count + b.Count);
|
||||||
|
i = left;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same bounds for every step, so the order stays: the most that the smallest step that counts could say.
|
||||||
|
var edge = 1.0 / (Math.Max(minPool, 1) + 2);
|
||||||
|
return new Calibration
|
||||||
|
{
|
||||||
|
Kind = IsotonicKind,
|
||||||
|
Scores = [.. blocks.Select(b => b.Score / b.Count)],
|
||||||
|
Values = [.. blocks.Select(b => Math.Clamp(b.Wins / b.Count, edge, 1 - edge))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Notifications;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>What the labels of a strategy need: the collected bars, through which closed day, its rules.</summary>
|
||||||
|
public sealed record LabelData(BacktestDataset Data, DateOnly Through, Func<IStrategy> Create);
|
||||||
|
|
||||||
|
/// <summary>Everything the models saw, put together once: the page and the nightly check read the same numbers.</summary>
|
||||||
|
public sealed record LearningSnapshot(IReadOnlyList<Example> Examples, IReadOnlyList<SeenEstimate> Labelled, IReadOnlyList<ModelRow> Models, CycleState State)
|
||||||
|
{
|
||||||
|
public ModelRow? Champion => Models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
|
||||||
|
|
||||||
|
public ModelRow? Challenger => Models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
|
||||||
|
|
||||||
|
/// <summary>The estimates that counted when each signal came, with their outcome, in the order the outcomes came.</summary>
|
||||||
|
public IReadOnlyList<Estimate> InCharge => [.. Labelled.Where(e => e.InCharge).Select(e => e.Estimate)];
|
||||||
|
|
||||||
|
public IReadOnlyList<Estimate> Of(Guid model) => [.. Labelled.Where(e => e.ModelId == model).Select(e => e.Estimate)];
|
||||||
|
|
||||||
|
public IReadOnlyList<(Estimate Champion, Estimate Challenger)> Pairs(Guid champion, Guid challenger)
|
||||||
|
{
|
||||||
|
var first = Labelled.Where(e => e.ModelId == champion).ToDictionary(e => e.Estimate.Case.Id, e => e.Estimate);
|
||||||
|
return [.. Labelled.Where(e => e.ModelId == challenger && first.ContainsKey(e.Estimate.Case.Id)).Select(e => (first[e.Estimate.Case.Id], e.Estimate))];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<LearningSnapshot> LoadAsync(LearningDesk desk, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(desk);
|
||||||
|
var examples = await desk.Store.AllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var byId = examples.Where(e => e.IsLabelled).ToDictionary(e => e.Id);
|
||||||
|
var predictions = await desk.Models.PredictionsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var labelled = predictions.Where(p => byId.ContainsKey(p.FeatureId))
|
||||||
|
.Select(p => new SeenEstimate(p.ModelId, p.InCharge, new Estimate(byId[p.FeatureId], p.Probability, p.BaseRate, p.Multiplier)))
|
||||||
|
.OrderBy(e => e.Estimate.Case.Label!.ClosedDay).ThenBy(e => e.Estimate.Case.At).ThenBy(e => e.Estimate.Case.Symbol, StringComparer.Ordinal).ToList();
|
||||||
|
return new LearningSnapshot(examples, labelled, await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false), await desk.CycleAsync(cancellationToken).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The continuous cycle of SPEC 11.4: every night the labels, the check of the model in charge and the criteria to start
|
||||||
|
/// counting; every Sunday the challenger, trained or judged. One run after an absence does everything that was due once
|
||||||
|
/// (SPEC 5.6). Every step can be repeated: a run cut short is made again whole.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, Func<string, IReadOnlyList<Example>, CancellationToken, Task<LabelData?>> dataOf)
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
public async Task RunAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await desk.PrepareHistoryAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// A label that cannot be made must never keep a model that counts from being checked.
|
||||||
|
var failed = new List<Exception>();
|
||||||
|
await LabelAsync(failed, cancellationToken).ConfigureAwait(false);
|
||||||
|
await CheckAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await SundayAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
if (failed.Count > 0)
|
||||||
|
{
|
||||||
|
throw new AggregateException("Some labels could not be made.", failed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Labels -------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The outcome of the examples whose simulated operation closed. Returns how many.</summary>
|
||||||
|
public async Task<int> LabelAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var failed = new List<Exception>();
|
||||||
|
var made = await LabelAsync(failed, cancellationToken).ConfigureAwait(false);
|
||||||
|
return failed.Count == 0 ? made : throw new AggregateException("Some labels could not be made.", failed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<int> LabelAsync(List<Exception> failed, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var made = 0;
|
||||||
|
foreach (var group in (await desk.Store.OpenAsync(cancellationToken).ConfigureAwait(false)).GroupBy(e => e.Strategy, StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
var open = group.ToList();
|
||||||
|
LabelData? source = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
source = await dataOf(group.Key, open, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
failed.Add(ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source is null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var example in open)
|
||||||
|
{
|
||||||
|
// Without the bar of its own day the operation would start from the wrong one.
|
||||||
|
if (source.Data[example.Symbol] is not { } instrument || instrument.IndexOf(example.Day) < 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (CaseLabels.Of(example, source.Create, source.Data, source.Through, earnings: Clues.ReportOf(example)) is { } label)
|
||||||
|
{
|
||||||
|
await desk.Store.AddLabelAsync(example.Id, label, cancellationToken).ConfigureAwait(false);
|
||||||
|
made++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
failed.Add(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Check --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The check of the model in charge: set aside or back, and whether it may start to count.</summary>
|
||||||
|
public async Task CheckAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (snapshot.Champion is not { } champion)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var today = Zones.DayIn(now, Zones.Rome);
|
||||||
|
var labelled = snapshot.Of(champion.Id);
|
||||||
|
var health = Health.Check(champion, labelled, [.. snapshot.Examples.Where(e => e.Source == CaseSources.Live)], now);
|
||||||
|
var activation = ActivationCheck.Of(snapshot.InCharge, desk.BaseRates, await CapitalsAsync(cancellationToken).ConfigureAwait(false));
|
||||||
|
var state = snapshot.State;
|
||||||
|
var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now };
|
||||||
|
if (state.ActivatedAt is null && activation.Passed)
|
||||||
|
{
|
||||||
|
next = next with { ActivatedAt = now };
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
if (health.Aside is { } reason && state.Aside is null)
|
||||||
|
{
|
||||||
|
var text = AsideText(reason, health) + " Lo metto da parte finché non rientra: le strategie proseguono senza di lui.";
|
||||||
|
await TellAsync(s, ModelEvents.SetAside, champion.Version, "Allarme: " + Lower(text), "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else if (health.Aside is null && state is { Aside: not null, AsideAt: { } since })
|
||||||
|
{
|
||||||
|
var days = Math.Max(1, (int)Math.Round((now - since).TotalDays));
|
||||||
|
var text = $"Anomalia rientrata dopo {(days == 1 ? "un giorno" : days.ToString(It) + " giorni")}: il modello non è più da parte.";
|
||||||
|
await TellAsync(s, ModelEvents.Back, champion.Version, text, "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else if (state.LastNight != today)
|
||||||
|
{
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_check",
|
||||||
|
health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health) : "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (next.ActivatedAt is not null && state.ActivatedAt is null)
|
||||||
|
{
|
||||||
|
var text = string.Create(It, $"Il modello comincia a contare: {activation.Evaluated} segnali valutati, probabilità ben tarate (errore medio {activation.CalibrationError * 100:0.0} punti), guadagno medio per operazione proposta da {activation.Scores.GainWithout:+0.00;-0.00} a {activation.Scores.GainWith:+0.00;-0.00} euro. Può solo rimpicciolire le operazioni.");
|
||||||
|
await TellAsync(s, ModelEvents.Activated, champion.Version, text, text, notify: true, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, next, cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string AsideText(string reason, HealthCheck health)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(health);
|
||||||
|
return reason switch
|
||||||
|
{
|
||||||
|
AsideCodes.Precision => string.Create(It, $"Precisione scesa al {Health.Shown(health.Precision ?? 0)}% su {health.Cases} casi."),
|
||||||
|
AsideCodes.ErrorDrift => "Gli errori del modello sono aumentati negli ultimi casi.",
|
||||||
|
AsideCodes.ClueDrift => "Il mercato è diverso da quello che ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(It) + ".",
|
||||||
|
_ => "Anomalia.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task TellAsync(DbSession s, string kind, int? version, string history, string diary, bool notify, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await ModelStore.AddEventAsync(s, clock, kind, version, history, cancellationToken).ConfigureAwait(false);
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_" + kind, diary, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (notify)
|
||||||
|
{
|
||||||
|
await NotificationSender.EnqueueAsync(s, clock, "model_" + kind, diary, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Sunday -------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The weekly part, once for each Sunday; a Sunday missed while the bot was off is done at the next run.</summary>
|
||||||
|
public async Task SundayAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var state = await desk.CycleAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var today = Zones.DayIn(clock.UtcNow, Zones.Rome);
|
||||||
|
var sunday = today.AddDays(-(int)today.DayOfWeek);
|
||||||
|
if (state.LastSunday is { } done ? done >= sunday : today != sunday)
|
||||||
|
{
|
||||||
|
if (state.LastSunday is null)
|
||||||
|
{
|
||||||
|
await SaveAsync(state with { LastSunday = sunday }, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (snapshot is { Champion: { } champion, Challenger: { } challenger })
|
||||||
|
{
|
||||||
|
await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await TrainAsync(snapshot, sunday, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task SaveAsync(CycleState state, CancellationToken cancellationToken) =>
|
||||||
|
db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The trial: a decision only when the cases have passed a new threshold (SPEC 11.4).</summary>
|
||||||
|
private async Task JudgeAsync(LearningSnapshot snapshot, ModelRow champion, ModelRow challenger, DateOnly sunday, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var check = TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), desk.BaseRates);
|
||||||
|
var state = snapshot.State with { LastSunday = sunday };
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
if (check.Threshold > challenger.ThresholdDone)
|
||||||
|
{
|
||||||
|
await ModelStore.SetThresholdAsync(s, clock, challenger.Id, check.Threshold, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (check.Wins)
|
||||||
|
{
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Retired, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ModelStore.SetReplacedAsync(s, clock, challenger.Id, champion.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
var text = string.Create(It, $"La versione {challenger.Version} prende il posto della {champion.Version}: stime migliori su {check.Pairs} casi di confronto, un vantaggio che non si spiega con il caso.");
|
||||||
|
await TellAsync(s, ModelEvents.Promoted, challenger.Version, text, text + " Puoi annullare la promozione dalla pagina Apprendimento.", notify: true, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else if (check.Threshold >= TrialCheck.Thresholds[^1])
|
||||||
|
{
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Discarded, cancellationToken).ConfigureAwait(false);
|
||||||
|
var text = string.Create(It, $"Scartata la versione {challenger.Version}: dopo {check.Pairs} casi di confronto non fa meglio della {champion.Version}.");
|
||||||
|
await TellAsync(s, ModelEvents.Discarded, challenger.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// A strategy without a base rate is not estimated, so it does not train either (ADR 0018).
|
||||||
|
var rates = desk.BaseRates;
|
||||||
|
var examples = snapshot.Examples.Where(e => e.IsLabelled && rates.ContainsKey(e.Strategy)).ToList();
|
||||||
|
var state = snapshot.State with { LastSunday = sunday };
|
||||||
|
var seen = state.TrainedOn > 0 ? state.TrainedOn : snapshot.Champion?.Examples ?? 0;
|
||||||
|
var champion = snapshot.Champion;
|
||||||
|
TrainingResult? result = null;
|
||||||
|
if (examples.Count != seen && (champion is not null || examples.Count >= ActivationCheck.Needed))
|
||||||
|
{
|
||||||
|
var input = new TrainingInput(examples)
|
||||||
|
{
|
||||||
|
BaseRates = rates,
|
||||||
|
Capital = await CapitalsAsync(cancellationToken).ConfigureAwait(false),
|
||||||
|
Funded = await FundedAsync(cancellationToken).ConfigureAwait(false),
|
||||||
|
Rule = (await desk.GateAsync(cancellationToken).ConfigureAwait(false)).Rule,
|
||||||
|
};
|
||||||
|
result = await Task.Run(() => Trainer.Train(input, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
state = state with { TrainedOn = examples.Count };
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
if (result is { } trained)
|
||||||
|
{
|
||||||
|
// The state may have changed while it trained (an undo): never two challengers, never two in charge.
|
||||||
|
var status = await ModelStore.FindAsync(s, ModelStatuses.Champion).ConfigureAwait(false) is null ? ModelStatuses.Champion : ModelStatuses.Challenger;
|
||||||
|
if (await ModelStore.FindAsync(s, status).ConfigureAwait(false) is null)
|
||||||
|
{
|
||||||
|
var row = await ModelStore.RegisterAsync(s, clock, trained.Model, trained.Report, status, "weekly", clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||||
|
var what = status == ModelStatuses.Champion ? "È il primo modello: parte in osservazione." : "È in prova come sfidante.";
|
||||||
|
var text = string.Create(It, $"Addestrata la versione {row.Version} su {row.Examples} casi ({LearnerNames.Label(row.Learner).ToLower(It)}). {what}");
|
||||||
|
await TellAsync(s, ModelEvents.Trained, row.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Undo ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Takes back the last promotion (SPEC 11.4): the model it replaced is in charge again. False when there is nothing to take back.</summary>
|
||||||
|
public Task<bool> UndoPromotionAsync(CancellationToken cancellationToken) => UndoPromotionAsync(db, clock, cancellationToken);
|
||||||
|
|
||||||
|
public static Task<bool> UndoPromotionAsync(Database db, IClock clock, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(db);
|
||||||
|
return db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
if (await ModelStore.FindAsync(s, ModelStatuses.Champion).ConfigureAwait(false) is not { ReplacedId: { } previous } champion
|
||||||
|
|| (await s.FirstOrDefaultAsync("SELECT version FROM ml_models WHERE id = @id AND status = @st", r => (Version: (int)r.Number("version"), Found: true), ("id", previous), ("st", ModelStatuses.Retired))
|
||||||
|
.ConfigureAwait(false)) is not { Found: true } back)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Undone, cancellationToken).ConfigureAwait(false);
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, previous, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// The one on trial starts again: its cases of comparison were against the model just taken away.
|
||||||
|
if (await ModelStore.FindAsync(s, ModelStatuses.Challenger).ConfigureAwait(false) is { } trial)
|
||||||
|
{
|
||||||
|
await ModelStore.SetThresholdAsync(s, clock, trial.Id, 0, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = $"Promozione annullata da te: torna in carica la versione {back.Version} al posto della {champion.Version}.";
|
||||||
|
await ModelStore.AddEventAsync(s, clock, ModelEvents.Undone, back.Version, text, cancellationToken).ConfigureAwait(false);
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_undone", text, null, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Money --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The capital of each strategy in euro; the reference one (SPEC 8.6) for a strategy that has none yet.</summary>
|
||||||
|
public Task<IReadOnlyDictionary<string, double>> CapitalsAsync(CancellationToken cancellationToken) => CapitalsAsync(db, clock, cancellationToken);
|
||||||
|
|
||||||
|
public static async Task<IReadOnlyDictionary<string, double>> CapitalsAsync(Database db, IClock clock, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var capitals = new Dictionary<string, double>(FirstModel.ReferenceCapitals, StringComparer.Ordinal);
|
||||||
|
var rate = (await new FxStore(db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
|
||||||
|
foreach (var (strategy, capital) in await CapitalRowsAsync(db, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
var euro = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(strategy)) == "USD" ? (rate > 0m ? capital / rate : 0m) : capital;
|
||||||
|
if (euro > 0m)
|
||||||
|
{
|
||||||
|
capitals[strategy] = (double)euro;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return capitals;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<IReadOnlyList<(string Strategy, decimal Capital)>> CapitalRowsAsync(Database db, CancellationToken cancellationToken) =>
|
||||||
|
[.. (await db.ReadAsync(s => s.QueryAsync("SELECT strategy, capital FROM strategy_state", r => (r.Text("strategy"), r.Money("capital"))), cancellationToken).ConfigureAwait(false))
|
||||||
|
.Where(r => StrategyPipeline.IsBase(r.Item1))];
|
||||||
|
|
||||||
|
private async Task<IReadOnlySet<string>> FundedAsync(CancellationToken cancellationToken) =>
|
||||||
|
(await db.ReadAsync(s => s.QueryAsync("SELECT strategy FROM strategy_state WHERE stage <> @o", r => r.Text("strategy"), ("o", StrategyStages.Observation)), cancellationToken)
|
||||||
|
.ConfigureAwait(false)).ToHashSet(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
private static string Lower(string text) => text.Length == 0 ? text : char.ToLower(text[0], It) + text[1..];
|
||||||
|
}
|
||||||
@@ -0,0 +1,412 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>Where the learning cycle is: whether the model counts, whether it is set aside and why, what ran last.</summary>
|
||||||
|
public sealed record CycleState
|
||||||
|
{
|
||||||
|
public const string Key = "cycle";
|
||||||
|
|
||||||
|
/// <summary>When the criteria of SPEC 11.5 were met: from then on the model shrinks operations. Null: in observation.</summary>
|
||||||
|
public DateTimeOffset? ActivatedAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Why the model is set aside on its own (<see cref="AsideCodes"/>); null when it is not.</summary>
|
||||||
|
public string? Aside { get; init; }
|
||||||
|
|
||||||
|
public DateTimeOffset? AsideAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The last night checked and the last Sunday done, as dates in Rome.</summary>
|
||||||
|
public DateOnly? LastNight { get; init; }
|
||||||
|
|
||||||
|
public DateOnly? LastSunday { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The labelled examples the last training saw.</summary>
|
||||||
|
public int TrainedOn { get; init; }
|
||||||
|
|
||||||
|
public HealthCheck? Health { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Why a model is set aside on its own (SPEC 11.4).</summary>
|
||||||
|
public static class AsideCodes
|
||||||
|
{
|
||||||
|
public const string Precision = "precision";
|
||||||
|
public const string ErrorDrift = "error_drift";
|
||||||
|
public const string ClueDrift = "clue_drift";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a model says of a new example. <see cref="Multiplier"/> is what it would apply; it counts only when the gate says so.</summary>
|
||||||
|
public sealed record ModelEstimate(ModelRow Row, double Probability, double BaseRate, double Multiplier, bool InCharge);
|
||||||
|
|
||||||
|
/// <summary>What decides about the operations at a decision: the model in charge, the one on trial, and whether it counts.</summary>
|
||||||
|
public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, MultiplierRule Rule, IReadOnlyDictionary<string, double> BaseRates, bool Counts)
|
||||||
|
{
|
||||||
|
/// <summary>It would count, but it is set aside: by an alarm or by the user.</summary>
|
||||||
|
public bool Aside { get; init; }
|
||||||
|
|
||||||
|
public static readonly ModelGate None = new(null, null, MultiplierRule.Standard, new Dictionary<string, double>(), false);
|
||||||
|
|
||||||
|
/// <summary>Without a base rate for the strategy, or a model that studied it, there is no estimate (ADR 0018).</summary>
|
||||||
|
public IReadOnlyList<ModelEstimate> Estimate(Example example)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(example);
|
||||||
|
if (!BaseRates.TryGetValue(example.Strategy, out var rate))
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var estimates = new List<ModelEstimate>();
|
||||||
|
foreach (var (row, inCharge) in new[] { (Champion, true), (Challenger, false) })
|
||||||
|
{
|
||||||
|
if (row?.Model is { } model && model.Strategies.Contains(example.Strategy, StringComparer.Ordinal) && model.Probability(example.Features) is var probability && double.IsFinite(probability))
|
||||||
|
{
|
||||||
|
var p = Math.Round(probability, 6);
|
||||||
|
estimates.Add(new ModelEstimate(row, p, rate, Rule.Of(p, rate), inCharge));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return estimates;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Learning as the live engine sees it (SPEC 11): for each decision it gives the steps that note the examples and apply
|
||||||
|
/// the multiplier, then saves them with the decision. A failure here never stops a decision: the strategy goes on as if
|
||||||
|
/// there were no model.
|
||||||
|
/// </summary>
|
||||||
|
public sealed partial class LearningDesk(Database db, IClock clock, SettingsStore? settings = null, ILogger? logger = null)
|
||||||
|
{
|
||||||
|
private readonly ILogger _logger = logger ?? NullLogger.Instance;
|
||||||
|
private readonly OutsideReader _outside = new(db, clock, settings);
|
||||||
|
|
||||||
|
public LearningStore Store { get; } = new(db, clock);
|
||||||
|
|
||||||
|
public ModelStore Models { get; } = new(db);
|
||||||
|
|
||||||
|
/// <summary>The file of the first model; the one built into the program unless a test gives another.</summary>
|
||||||
|
public FirstModelFile? First { get; init; } = FirstModel.Embedded;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, double> BaseRates => First?.BaseRates ?? new Dictionary<string, double>();
|
||||||
|
|
||||||
|
private const string HistoryKey = "history";
|
||||||
|
|
||||||
|
private sealed record HistoryState(string Fingerprint);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// At the start (SPEC 11.2): the examples of the history in the program, when they changed, take the place of the old
|
||||||
|
/// ones; with no model at all the first one takes charge, in observation.
|
||||||
|
/// </summary>
|
||||||
|
public async Task PrepareHistoryAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (First is not { } file)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var fingerprint = FirstModel.Fingerprint(file);
|
||||||
|
if (await Store.StateAsync<HistoryState>(HistoryKey, cancellationToken).ConfigureAwait(false) is { } state && state.Fingerprint == fingerprint)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var live = new List<Example>();
|
||||||
|
foreach (var strategy in file.Examples.Select(e => e.Strategy).Distinct(StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
live.AddRange(await Store.LiveAsync(strategy, cancellationToken).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("DELETE FROM ml_labels WHERE feature_id IN (SELECT id FROM ml_features WHERE source = @h)", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("DELETE FROM ml_features WHERE source = @h", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false);
|
||||||
|
foreach (var example in file.Examples.Where(e => !live.Any(l => SameOperation(l, e))))
|
||||||
|
{
|
||||||
|
await LearningStore.AddAsync(s, clock, example, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.Model is { } model && file.Report is { } report && await s.CountAsync("SELECT COUNT(*) FROM ml_models").ConfigureAwait(false) == 0)
|
||||||
|
{
|
||||||
|
var row = await ModelStore.RegisterAsync(s, clock, model, report, ModelStatuses.Champion, CaseSources.History, new DateTimeOffset(file.Through.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
await ModelStore.AddEventAsync(s, clock, ModelEvents.First, row.Version,
|
||||||
|
$"Primo modello: versione {row.Version}, {LearnerNames.Label(row.Learner).ToLower(CultureInfo.GetCultureInfo("it-IT"))}, addestrata su {row.Examples} esempi ricostruiti dallo storico. Parte in osservazione.",
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, HistoryKey, new HistoryState(fingerprint), cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A newer history may reach the days already lived: an operation is one example, the live one (SPEC 11.2).
|
||||||
|
private static bool SameOperation(Example live, Example past)
|
||||||
|
{
|
||||||
|
static string Plain(string symbol) => symbol.Replace("-", "", StringComparison.Ordinal);
|
||||||
|
return live.Strategy == past.Strategy && Plain(live.Symbol) == Plain(past.Symbol) && past.IsOpenAfter(live.Day) && (past.Day <= live.Day || live.IsOpenAfter(past.Day));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<CycleState> CycleAsync(CancellationToken cancellationToken) => await Store.StateAsync<CycleState>(CycleState.Key, cancellationToken).ConfigureAwait(false) ?? new CycleState();
|
||||||
|
|
||||||
|
public async Task<ModelGate> GateAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var (rule, aside) = await LearningSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
var state = await CycleAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return new ModelGate(await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false),
|
||||||
|
await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, BaseRates, state is { ActivatedAt: not null, Aside: null } && !aside)
|
||||||
|
{
|
||||||
|
Aside = state.Aside is not null || aside,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the decision of <paramref name="day"/> needs from learning; null when not even the archive can be read. The
|
||||||
|
/// world outside the bars is the one of <paramref name="at"/>, when the decision was due: one recovered hours later must
|
||||||
|
/// not know more than the operation that started on time. Each part that fails is left out alone, because the
|
||||||
|
/// multiplier an operation was born with holds whatever happens (SPEC 11.1).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<LearningTurn?> PrepareAsync(string strategy, string stage, DateOnly day, DateTimeOffset at, BacktestDataset data, Func<IStrategy> create,
|
||||||
|
IReadOnlyDictionary<string, DateOnly>? earnings, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(data);
|
||||||
|
ArgumentNullException.ThrowIfNull(create);
|
||||||
|
if (!StrategyPipeline.IsBase(strategy))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task<T> OrAsync<T>(Func<Task<T>> read, Func<Task<T>> otherwise)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await read().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
LogFailed(_logger, ex, strategy);
|
||||||
|
return await otherwise().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var live = await OrAsync<IReadOnlyList<Example>?>(async () => await Store.LiveAsync(strategy, cancellationToken).ConfigureAwait(false),
|
||||||
|
() => OrAsync<IReadOnlyList<Example>?>(async () => await Store.BornAsync(strategy, cancellationToken).ConfigureAwait(false), () => Task.FromResult<IReadOnlyList<Example>?>(null)))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
if (live is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var known = new List<Example>(live.Count);
|
||||||
|
foreach (var example in live)
|
||||||
|
{
|
||||||
|
// The operation of the example may have closed with the bars of today, before the nightly labels.
|
||||||
|
known.Add(example.Label is not null || SingleOperation.NeedsUniverse(strategy) || data[example.Symbol] is not { } instrument || instrument.IndexOf(example.Day) < 0
|
||||||
|
? example
|
||||||
|
: await OrAsync(() => Task.FromResult(CaseLabels.Of(example, create, data, day, earnings: Clues.ReportOf(example)) is { } label ? example with { Label = label } : example),
|
||||||
|
() => Task.FromResult(example)).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||||
|
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
|
||||||
|
var gate = await OrAsync(() => GateAsync(cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
|
||||||
|
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy));
|
||||||
|
}
|
||||||
|
|
||||||
|
[LoggerMessage(Level = LogLevel.Error, Message = "Learning left out of the decision of {Strategy}")]
|
||||||
|
private static partial void LogFailed(ILogger logger, Exception exception, string strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The last corrective (SPEC 8.5): the multiplier of the model on entries and increases, never on exits nor decreases. A
|
||||||
|
/// new operation gets the one of its estimate; one already born keeps its own until it closes, increases included (11.1).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ModelFilter(Func<StrategyContext, string, double> multiplierOf) : IIntentStage
|
||||||
|
{
|
||||||
|
/// <summary>An increase smaller than this share of the reduced size is not made: it would be chasing the rounding every day.</summary>
|
||||||
|
public const decimal Band = 0.20m;
|
||||||
|
|
||||||
|
public string Name => "model_filter";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
ArgumentNullException.ThrowIfNull(intents);
|
||||||
|
return [.. intents.Select(i => i.TargetWeight is > 0m ? Filter(context, i) : i)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private Intent Filter(StrategyContext context, Intent intent)
|
||||||
|
{
|
||||||
|
// Whatever an estimate says, an operation is never made bigger: the multiplier stays between 0 and 1.
|
||||||
|
var multiplier = multiplierOf(context, intent.Symbol);
|
||||||
|
if (!double.IsFinite(multiplier) || multiplier >= 1)
|
||||||
|
{
|
||||||
|
return intent;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filtered = BookWeights.Reduce(context, intent, (decimal)Math.Max(0, multiplier), CorrectiveReasons.ModelFilter);
|
||||||
|
var current = BookWeights.Current(context, intent.Symbol);
|
||||||
|
return current > 0m && filtered.TargetWeight is { } target && target > current && target - current <= Band * target ? filtered with { TargetWeight = null } : filtered;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A step of learning that, when it fails, changes nothing (SPEC 11: the strategies go on without the model).</summary>
|
||||||
|
internal sealed class SafeStage(IIntentStage inner, Action<Exception> failed) : IIntentStage
|
||||||
|
{
|
||||||
|
public string Name => inner.Name;
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return inner.Apply(context, intents);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
failed(ex);
|
||||||
|
return intents;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The learning side of one decision: the steps it adds and what it saves.</summary>
|
||||||
|
public sealed class LearningTurn
|
||||||
|
{
|
||||||
|
private readonly string _strategy;
|
||||||
|
private readonly string _stage;
|
||||||
|
private readonly DateOnly _day;
|
||||||
|
private readonly ILookup<string, Example> _live;
|
||||||
|
private readonly ModelGate _gate;
|
||||||
|
private readonly IClock _clock;
|
||||||
|
private readonly Action<Exception> _failed;
|
||||||
|
private readonly CaseCollector _collector;
|
||||||
|
private readonly Dictionary<string, IReadOnlyList<ModelEstimate>> _estimates = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyList<Example> live, OutsideView outside, ModelGate gate, IClock clock, Action<Exception> failed)
|
||||||
|
{
|
||||||
|
_strategy = strategy;
|
||||||
|
_stage = stage;
|
||||||
|
_day = day;
|
||||||
|
_live = live.ToLookup(e => e.Symbol, StringComparer.Ordinal);
|
||||||
|
_gate = gate;
|
||||||
|
_clock = clock;
|
||||||
|
_failed = failed;
|
||||||
|
_collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The correctives with the steps of learning around them: the examples are noted on what the strategy proposed, the
|
||||||
|
/// multiplier comes after every other corrective and before risk.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<IIntentStage> Around(IReadOnlyList<IIntentStage> correctives)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(correctives);
|
||||||
|
return [new SafeStage(_collector, _failed), .. correctives, new SafeStage(new ModelFilter(MultiplierOf), _failed)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsNew(string symbol) => _live[symbol].LastOrDefault() is not { } previous || !previous.IsOpenAfter(_day);
|
||||||
|
|
||||||
|
private double MultiplierOf(StrategyContext context, string symbol)
|
||||||
|
{
|
||||||
|
if (context.Day == _day && _collector.Cases.FirstOrDefault(c => c.Symbol == symbol) is { } made)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return AppliedTo(made);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
// Only the new operation goes on as without a model: those already born keep their multiplier.
|
||||||
|
_failed(ex);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The operation was born with the latest example before this day: without one, or with nothing held of one already
|
||||||
|
// over, the model had nothing to say.
|
||||||
|
var born = _live[symbol].LastOrDefault(e => e.Day <= context.Day);
|
||||||
|
return born is not null && (context.Portfolio.Holds(symbol) || born.IsOpenAfter(context.Day)) ? born.Multiplier : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private IReadOnlyList<ModelEstimate> EstimatesOf(Example example)
|
||||||
|
{
|
||||||
|
if (!_estimates.TryGetValue(example.Symbol, out var estimates))
|
||||||
|
{
|
||||||
|
_estimates[example.Symbol] = estimates = _gate.Estimate(example);
|
||||||
|
}
|
||||||
|
|
||||||
|
return estimates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double AppliedTo(Example example) => _gate.Counts && EstimatesOf(example).FirstOrDefault(e => e.InCharge) is { } estimate ? estimate.Multiplier : 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Saves the examples, their estimates and the row of the decision, in the transaction of the decision. A failure takes
|
||||||
|
/// back only this part: the decision, with its exits, is written all the same.
|
||||||
|
/// </summary>
|
||||||
|
public async Task WriteAsync(DbSession s, Guid decisionId, Guid? account, DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
await s.ExecuteAsync("SAVEPOINT learning", cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await WriteCasesAsync(s, decisionId, account, now, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_failed(ex);
|
||||||
|
await s.ExecuteAsync("ROLLBACK TO SAVEPOINT learning", cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await s.ExecuteAsync("RELEASE SAVEPOINT learning", cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task WriteCasesAsync(DbSession s, Guid decisionId, Guid? account, DateTimeOffset now, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
foreach (var made in _collector.Cases)
|
||||||
|
{
|
||||||
|
var applied = 1.0;
|
||||||
|
IReadOnlyList<ModelEstimate> estimates = [];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
estimates = EstimatesOf(made);
|
||||||
|
applied = AppliedTo(made);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_failed(ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
var example = made with { Source = CaseSources.Live, At = _clock.UtcNow, Stage = _stage, DecisionId = decisionId, Multiplier = applied };
|
||||||
|
if (await LearningStore.AddAsync(s, _clock, example, cancellationToken).ConfigureAwait(false) is not { } id)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var estimate in estimates)
|
||||||
|
{
|
||||||
|
await ModelStore.AddPredictionAsync(s, _clock, new PredictionRow(id, estimate.Row.Id, estimate.Probability, estimate.BaseRate, estimate.Multiplier, estimate.InCharge), cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
if (estimate.InCharge)
|
||||||
|
{
|
||||||
|
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, _strategy, account, made.Symbol, DecisionStages.Model,
|
||||||
|
applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [],
|
||||||
|
new Dictionary<string, object?>
|
||||||
|
{
|
||||||
|
["probability"] = estimate.Probability,
|
||||||
|
["base_rate"] = estimate.BaseRate,
|
||||||
|
["multiplier"] = estimate.Multiplier,
|
||||||
|
["applied"] = applied,
|
||||||
|
["version"] = estimate.Row.Version,
|
||||||
|
["counts"] = _gate.Counts,
|
||||||
|
["aside"] = _gate.Aside,
|
||||||
|
}, now), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>The settings of the model (SPEC 13.5): the thresholds of the multiplier and the manual set-aside.</summary>
|
||||||
|
public static class LearningSettings
|
||||||
|
{
|
||||||
|
public static readonly SettingDefinition Full = new("learning.full_points", "Taglia piena fino a", "0", ["0", "2", "5"]);
|
||||||
|
|
||||||
|
public static readonly SettingDefinition Zero = new("learning.zero_points", "Niente acquisto da", "10", ["8", "10", "15", "20"]);
|
||||||
|
|
||||||
|
public static readonly SettingDefinition Aside = new("learning.aside", "Modello messo da parte", "off", ["off", "on"]);
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<SettingDefinition> All = [Full, Zero, Aside];
|
||||||
|
|
||||||
|
/// <summary>True when the new values can leave operations bigger than before: the model shrinks less, or not at all.</summary>
|
||||||
|
public static bool Raised(Func<string, string> before, Func<string, string> after)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(before);
|
||||||
|
ArgumentNullException.ThrowIfNull(after);
|
||||||
|
static int Points(string value) => int.Parse(value, CultureInfo.InvariantCulture);
|
||||||
|
return Points(after(Full.Key)) > Points(before(Full.Key)) || Points(after(Zero.Key)) > Points(before(Zero.Key)) || (after(Aside.Key) == "on" && before(Aside.Key) != "on");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<(MultiplierRule Rule, bool Aside)> LoadAsync(SettingsStore? settings, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (settings is null)
|
||||||
|
{
|
||||||
|
return (MultiplierRule.Standard, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var full = (await settings.GetAsync(Full.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||||
|
var zero = (await settings.GetAsync(Zero.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||||
|
var aside = (await settings.GetAsync(Aside.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||||
|
return (new MultiplierRule(double.Parse(full, CultureInfo.InvariantCulture) / 100, double.Parse(zero, CultureInfo.InvariantCulture) / 100), aside == "on");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>The archive of the examples and of their labels (SPEC 11.2), and the small state of the learning cycle.</summary>
|
||||||
|
public sealed class LearningStore(Database db, IClock clock)
|
||||||
|
{
|
||||||
|
private const string Columns =
|
||||||
|
"f.id, f.strategy, f.symbol, f.source, f.decided_day, f.decided_at, f.decision_id, f.stage, f.reason, f.weight, f.stop, f.stop_offset, f.features, f.multiplier, " +
|
||||||
|
"l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
|
||||||
|
|
||||||
|
/// <summary>Saves an example as part of the decision that made it. One already there (same day) stays as it is: null.</summary>
|
||||||
|
public static async Task<Guid?> AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(example);
|
||||||
|
var id = example.Id == Guid.Empty ? Ids.NewId(clock) : example.Id;
|
||||||
|
var added = await s.ExecuteAsync(
|
||||||
|
"INSERT INTO ml_features (id, strategy, symbol, source, decided_day, decided_at, decision_id, stage, reason, weight, stop, stop_offset, features, multiplier, created_at) " +
|
||||||
|
"VALUES (@id, @s, @sym, @src, @day, @at, @dec, @st, @r, @w, @stop, @off, @f, @m, @now) ON CONFLICT (strategy, symbol, decided_day, source) DO NOTHING", cancellationToken,
|
||||||
|
("id", id), ("s", example.Strategy), ("sym", example.Symbol), ("src", example.Source), ("day", BarStore.DayText(example.Day)), ("at", example.At),
|
||||||
|
("dec", example.DecisionId), ("st", example.Stage), ("r", example.Reason), ("w", DbValues.Money(example.Weight)), ("stop", example.Stop), ("off", example.StopOffset),
|
||||||
|
("f", new DbJson(JsonSerializer.Serialize(example.Features))), ("m", example.Multiplier), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||||
|
if (added == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (example.Label is { } label)
|
||||||
|
{
|
||||||
|
await AddLabelAsync(s, clock, id, label, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label of an example, once and for all: a label never changes.</summary>
|
||||||
|
public static Task<int> AddLabelAsync(DbSession s, IClock clock, Guid example, CaseLabel label, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
ArgumentNullException.ThrowIfNull(label);
|
||||||
|
return s.ExecuteAsync(
|
||||||
|
"INSERT INTO ml_labels (id, feature_id, label, result, opened_day, closed_day, exit_reason, created_at) VALUES (@id, @f, @l, @r, @o, @c, @e, @now) ON CONFLICT (feature_id) DO NOTHING",
|
||||||
|
cancellationToken, ("id", Ids.NewId(clock)), ("f", example), ("l", label.Win is { } win ? (win ? 1 : 0) : null), ("r", label.Result),
|
||||||
|
("o", label.OpenedDay is { } opened ? BarStore.DayText(opened) : null), ("c", label.ClosedDay is { } closed ? BarStore.DayText(closed) : null), ("e", label.ExitReason),
|
||||||
|
("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task AddLabelAsync(Guid example, CaseLabel label, CancellationToken cancellationToken) =>
|
||||||
|
db.WriteAsync(s => AddLabelAsync(s, clock, example, label, cancellationToken), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The whole archive, oldest first.</summary>
|
||||||
|
public Task<List<Example>> AllAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " ORDER BY f.decided_at, f.strategy, f.symbol", Read), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The live examples whose simulated operation is still open, oldest first.</summary>
|
||||||
|
public Task<List<Example>> OpenAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND l.id IS NULL ORDER BY f.decided_at, f.strategy, f.symbol", Read, ("l", CaseSources.Live)), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The live examples of a strategy, oldest first.</summary>
|
||||||
|
public Task<List<Example>> LiveAsync(string strategy, CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_day, f.decided_at", Read, ("l", CaseSources.Live), ("s", strategy)), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>The same without reading the clues: what the multipliers of the operations already born need.</summary>
|
||||||
|
public Task<List<Example>> BornAsync(string strategy, CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT f.symbol, f.decided_day, f.multiplier, l.id AS label_id, l.closed_day FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id "
|
||||||
|
+ "WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_day, f.decided_at",
|
||||||
|
r => new Example(Guid.Empty, strategy, r.Text("symbol"), CaseSources.Live, BarStore.ParseDay(r.Text("decided_day")), DateTimeOffset.MinValue, "", 0m, null, null, new Dictionary<string, double>())
|
||||||
|
{
|
||||||
|
Multiplier = r.Measure("multiplier"),
|
||||||
|
Label = r.IsNull("label_id") ? null : new CaseLabel(null, null, null, Day(r, "closed_day"), ""),
|
||||||
|
}, ("l", CaseSources.Live), ("s", strategy)), cancellationToken);
|
||||||
|
|
||||||
|
public Task<long> CountAsync(string source, CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l", ("l", source)), cancellationToken);
|
||||||
|
|
||||||
|
// ---- State --------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public async Task<T?> StateAsync<T>(string key, CancellationToken cancellationToken)
|
||||||
|
where T : class
|
||||||
|
{
|
||||||
|
var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)), cancellationToken).ConfigureAwait(false);
|
||||||
|
return json is null ? null : JsonSerializer.Deserialize<T>(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task SaveStateAsync<T>(DbSession s, IClock clock, string key, T value, CancellationToken cancellationToken)
|
||||||
|
where T : class
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
await s.ExecuteAsync(
|
||||||
|
"INSERT INTO ml_state (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @now, @now) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
|
||||||
|
cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", new DbJson(JsonSerializer.Serialize(value))), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Example Read(DbRow r)
|
||||||
|
{
|
||||||
|
var label = r.IsNull("label_id")
|
||||||
|
? null
|
||||||
|
: new CaseLabel(r.IsNull("label") ? null : r.Number("label") == 1, r.IsNull("result") ? null : r.Measure("result"), Day(r, "opened_day"), Day(r, "closed_day"), r.Text("exit_reason"));
|
||||||
|
return new Example(r.Id("id"), r.Text("strategy"), r.Text("symbol"), r.Text("source"), BarStore.ParseDay(r.Text("decided_day")), r.Moment("decided_at"), r.Text("reason"),
|
||||||
|
r.Money("weight"), r.MoneyOrNull("stop"), r.MoneyOrNull("stop_offset"), JsonSerializer.Deserialize<Dictionary<string, double>>(r.Json("features").Text) ?? [])
|
||||||
|
{
|
||||||
|
Stage = r.TextOrNull("stage"),
|
||||||
|
DecisionId = r.IdOrNull("decision_id"),
|
||||||
|
Multiplier = r.Measure("multiplier"),
|
||||||
|
Label = label,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateOnly? Day(DbRow r, string column) => r.TextOrNull(column) is { } text ? BarStore.ParseDay(text) : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>What became of a model.</summary>
|
||||||
|
public static class ModelStatuses
|
||||||
|
{
|
||||||
|
/// <summary>In charge: its estimates count (or are only noted, in observation).</summary>
|
||||||
|
public const string Champion = "champion";
|
||||||
|
|
||||||
|
/// <summary>On trial beside the one in charge.</summary>
|
||||||
|
public const string Challenger = "challenger";
|
||||||
|
|
||||||
|
/// <summary>Replaced by a promotion.</summary>
|
||||||
|
public const string Retired = "retired";
|
||||||
|
|
||||||
|
/// <summary>A challenger that did not do better in time.</summary>
|
||||||
|
public const string Discarded = "discarded";
|
||||||
|
|
||||||
|
/// <summary>Promoted, then the user took the promotion back.</summary>
|
||||||
|
public const string Undone = "undone";
|
||||||
|
|
||||||
|
/// <summary>Tried while choosing and not chosen: it is in the register because the number of attempts counts.</summary>
|
||||||
|
public const string Tried = "tried";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A row of the register of the models (SPEC 11.3).</summary>
|
||||||
|
public sealed record ModelRow(Guid Id, int? Version, string Learner, string Status, string Source, DateTimeOffset TrainedAt, int Examples, int ThresholdDone, Guid? ReplacedId, TrainedModel? Model,
|
||||||
|
ModelReport Report);
|
||||||
|
|
||||||
|
/// <summary>An estimate on an example as it was saved when the example was born (SPEC 11.5).</summary>
|
||||||
|
public sealed record PredictionRow(Guid FeatureId, Guid ModelId, double Probability, double BaseRate, double Multiplier, bool InCharge);
|
||||||
|
|
||||||
|
/// <summary>An entry of the history of the model: what the user reads in "Storia".</summary>
|
||||||
|
public sealed record ModelEvent(string Kind, int? Version, string Text, DateTimeOffset At);
|
||||||
|
|
||||||
|
/// <summary>Kinds of the events of the model.</summary>
|
||||||
|
public static class ModelEvents
|
||||||
|
{
|
||||||
|
public const string First = "first";
|
||||||
|
public const string Trained = "trained";
|
||||||
|
public const string Promoted = "promoted";
|
||||||
|
public const string Discarded = "discarded";
|
||||||
|
public const string Undone = "undone";
|
||||||
|
public const string Activated = "activated";
|
||||||
|
public const string SetAside = "set_aside";
|
||||||
|
public const string Back = "back";
|
||||||
|
public const string Drift = "drift";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The register of the models, their estimates and their history (SPEC 11.3–11.5).</summary>
|
||||||
|
public sealed class ModelStore(Database db)
|
||||||
|
{
|
||||||
|
private const string Columns = "id, version, learner, status, source, trained_at, examples, threshold_done, replaced_id, model, report FROM ml_models";
|
||||||
|
|
||||||
|
public Task<List<ModelRow>> AllAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " ORDER BY trained_at, id", Read), cancellationToken);
|
||||||
|
|
||||||
|
public Task<ModelRow?> FindAsync(string status, CancellationToken cancellationToken) => db.ReadAsync(s => FindAsync(s, status), cancellationToken);
|
||||||
|
|
||||||
|
public static Task<ModelRow?> FindAsync(DbSession s, string status)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
return s.FirstOrDefaultAsync("SELECT " + Columns + " WHERE status = @s ORDER BY trained_at DESC, id DESC", Read, ("s", status));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The version that would come back if the last promotion were taken back; null when there is nothing to take back.</summary>
|
||||||
|
public async Task<int?> UndoToAsync(CancellationToken cancellationToken) =>
|
||||||
|
await FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false) is { ReplacedId: { } replaced }
|
||||||
|
? (await AllAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version
|
||||||
|
: null;
|
||||||
|
|
||||||
|
public Task<long> CountAsync(CancellationToken cancellationToken) => db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_models"), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Writes the result of a training in the register: the chosen model with its version, the others as attempts.</summary>
|
||||||
|
public static async Task<ModelRow> RegisterAsync(DbSession s, IClock clock, TrainedModel model, ModelReport report, string status, string source, DateTimeOffset trainedAt,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
ArgumentNullException.ThrowIfNull(model);
|
||||||
|
ArgumentNullException.ThrowIfNull(report);
|
||||||
|
var version = (int)await s.CountAsync("SELECT COALESCE(MAX(version), 0) FROM ml_models").ConfigureAwait(false) + 1;
|
||||||
|
var row = new ModelRow(Ids.NewId(clock), version, model.Learned.Learner, status, source, trainedAt, report.Examples, 0, null, model, report);
|
||||||
|
await AddAsync(s, clock, row, cancellationToken).ConfigureAwait(false);
|
||||||
|
foreach (var attempt in report.Attempts.Where(a => !a.Chosen))
|
||||||
|
{
|
||||||
|
await AddAsync(s, clock, new ModelRow(Ids.NewId(clock), null, attempt.Learner, ModelStatuses.Tried, source, trainedAt, report.Examples, 0, row.Id, null,
|
||||||
|
new ModelReport { Examples = report.Examples, Live = report.Live, Attempts = [attempt] }), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<int> AddAsync(DbSession s, IClock clock, ModelRow row, CancellationToken cancellationToken) =>
|
||||||
|
s.ExecuteAsync(
|
||||||
|
"INSERT INTO ml_models (id, version, learner, status, source, trained_at, examples, threshold_done, replaced_id, model, report, created_at, updated_at) " +
|
||||||
|
"VALUES (@id, @v, @l, @st, @src, @at, @n, 0, @r, @m, @rep, @now, @now)", cancellationToken,
|
||||||
|
("id", row.Id), ("v", row.Version), ("l", row.Learner), ("st", row.Status), ("src", row.Source), ("at", row.TrainedAt), ("n", row.Examples), ("r", row.ReplacedId),
|
||||||
|
("m", row.Model is { } model ? new DbJson(JsonSerializer.Serialize(model)) : null), ("rep", new DbJson(JsonSerializer.Serialize(row.Report))), ("now", clock.UtcNow));
|
||||||
|
|
||||||
|
public static Task<int> SetStatusAsync(DbSession s, IClock clock, Guid id, string status, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
return s.ExecuteAsync("UPDATE ml_models SET status = @st, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("st", status), ("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The model a promotion replaced, so the promotion can be taken back.</summary>
|
||||||
|
public static Task<int> SetReplacedAsync(DbSession s, IClock clock, Guid id, Guid? replaced, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
return s.ExecuteAsync("UPDATE ml_models SET replaced_id = @r, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("r", replaced), ("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task<int> SetThresholdAsync(DbSession s, IClock clock, Guid id, int threshold, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
return s.ExecuteAsync("UPDATE ml_models SET threshold_done = @t, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("t", threshold), ("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Estimates ----------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static Task<int> AddPredictionAsync(DbSession s, IClock clock, PredictionRow p, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
ArgumentNullException.ThrowIfNull(p);
|
||||||
|
return s.ExecuteAsync(
|
||||||
|
"INSERT INTO ml_predictions (id, feature_id, model_id, probability, base_rate, multiplier, in_charge, created_at) VALUES (@id, @f, @m, @p, @b, @mu, @c, @now) " +
|
||||||
|
"ON CONFLICT (feature_id, model_id) DO NOTHING", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("f", p.FeatureId), ("m", p.ModelId), ("p", p.Probability), ("b", p.BaseRate), ("mu", p.Multiplier), ("c", p.InCharge), ("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<List<PredictionRow>> PredictionsAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT feature_id, model_id, probability, base_rate, multiplier, in_charge FROM ml_predictions ORDER BY created_at, id",
|
||||||
|
r => new PredictionRow(r.Id("feature_id"), r.Id("model_id"), r.Measure("probability"), r.Measure("base_rate"), r.Measure("multiplier"), r.Bool("in_charge"))), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>How many live signals got an estimate in charge and then an outcome: the count towards the 300 of SPEC 11.5.</summary>
|
||||||
|
public Task<long> EvaluatedAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_predictions p JOIN ml_labels l ON l.feature_id = p.feature_id WHERE p.in_charge = @c AND l.label IS NOT NULL AND l.closed_day IS NOT NULL",
|
||||||
|
("c", true)), cancellationToken);
|
||||||
|
|
||||||
|
// ---- History ------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static Task<int> AddEventAsync(DbSession s, IClock clock, string kind, int? version, string text, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
return s.ExecuteAsync("INSERT INTO ml_events (id, kind, version, text, data, created_at) VALUES (@id, @k, @v, @t, NULL, @now)", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("k", kind), ("v", version), ("t", text), ("now", clock.UtcNow));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<List<ModelEvent>> EventsAsync(CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.QueryAsync("SELECT kind, version, text, created_at FROM ml_events ORDER BY created_at, id",
|
||||||
|
r => new ModelEvent(r.Text("kind"), r.IsNull("version") ? null : (int)r.Number("version"), r.Text("text"), r.Moment("created_at"))), cancellationToken);
|
||||||
|
|
||||||
|
private static ModelRow Read(DbRow r) => new(r.Id("id"), r.IsNull("version") ? null : (int)r.Number("version"), r.Text("learner"), r.Text("status"), r.Text("source"), r.Moment("trained_at"),
|
||||||
|
(int)r.Number("examples"), (int)r.Number("threshold_done"), r.IdOrNull("replaced_id"), r.IsNull("model") ? null : JsonSerializer.Deserialize<TrainedModel>(r.Json("model").Text),
|
||||||
|
JsonSerializer.Deserialize<ModelReport>(r.Json("report").Text) ?? new ModelReport());
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
|
||||||
|
namespace Anubis.Learning;
|
||||||
|
|
||||||
|
/// <summary>The values of a clue the model studied: below the 1% or above the 99% it has hardly ever seen it.</summary>
|
||||||
|
public sealed record ClueRange(double Low, double High, int Cases);
|
||||||
|
|
||||||
|
/// <summary>A model ready to estimate: the clues it uses, what it learned, how its score becomes a probability.</summary>
|
||||||
|
public sealed record TrainedModel
|
||||||
|
{
|
||||||
|
public IReadOnlyList<string> Clues { get; init; } = [];
|
||||||
|
|
||||||
|
public Learned Learned { get; init; } = new();
|
||||||
|
|
||||||
|
public Calibration Calibration { get; init; } = new();
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, ClueRange> Ranges { get; init; } = new Dictionary<string, ClueRange>();
|
||||||
|
|
||||||
|
/// <summary>The strategies whose examples trained it.</summary>
|
||||||
|
public IReadOnlyList<string> Strategies { get; init; } = [];
|
||||||
|
|
||||||
|
public double Probability(IReadOnlyDictionary<string, double> features) => Calibration.Probability(Learned.Score(Trainer.Row(Clues, features)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How much a group of clues weighs, out of 100.</summary>
|
||||||
|
public sealed record ClueWeight(string Group, decimal Share);
|
||||||
|
|
||||||
|
/// <summary>What one learner did in the validation: the register keeps every attempt (SPEC 11.3).</summary>
|
||||||
|
public sealed record Attempt(string Learner, Scores Forward, Scores Combined, bool Chosen);
|
||||||
|
|
||||||
|
/// <summary>The validation of a model: how many examples, every attempt, why this one, what it looks at.</summary>
|
||||||
|
public sealed record ModelReport
|
||||||
|
{
|
||||||
|
public int Examples { get; init; }
|
||||||
|
|
||||||
|
public int Live { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, int> ByStrategy { get; init; } = new Dictionary<string, int>();
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
|
||||||
|
|
||||||
|
public DateOnly? FirstDay { get; init; }
|
||||||
|
|
||||||
|
public DateOnly? LastDay { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<Attempt> Attempts { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>The whole reason of the choice, in Italian.</summary>
|
||||||
|
public string Reason { get; init; } = "";
|
||||||
|
|
||||||
|
/// <summary>True when no strategy with capital had examples, so the gain was measured on all of them.</summary>
|
||||||
|
public bool AllStrategiesCounted { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyList<ClueWeight> Weights { get; init; } = [];
|
||||||
|
|
||||||
|
public int Splits { get; init; }
|
||||||
|
|
||||||
|
public Attempt? Chosen => Attempts.FirstOrDefault(a => a.Chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a training starts from.</summary>
|
||||||
|
public sealed record TrainingInput(IReadOnlyList<Example> Examples)
|
||||||
|
{
|
||||||
|
/// <summary>The share of winners of each strategy in its backtest (SPEC 11.1).</summary>
|
||||||
|
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
|
||||||
|
|
||||||
|
/// <summary>The capital of each strategy in euro.</summary>
|
||||||
|
public IReadOnlyDictionary<string, double> Capital { get; init; } = new Dictionary<string, double>();
|
||||||
|
|
||||||
|
/// <summary>The strategies with capital: the only ones the gain is measured on (SPEC 11.3).</summary>
|
||||||
|
public IReadOnlySet<string> Funded { get; init; } = new HashSet<string>();
|
||||||
|
|
||||||
|
public MultiplierRule Rule { get; init; } = MultiplierRule.Standard;
|
||||||
|
|
||||||
|
public long Seed { get; init; } = 11;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record TrainingResult(TrainedModel Model, ModelReport Report);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Trains and chooses (SPEC 11.3, ADR 0018). The rule is fixed before looking: the winner is the learner with the best mean
|
||||||
|
/// gain per proposed operation on examples it had not studied; at equal gain the smaller log-loss. The forest must beat the
|
||||||
|
/// others on both, or it stays out.
|
||||||
|
/// </summary>
|
||||||
|
public static class Trainer
|
||||||
|
{
|
||||||
|
/// <summary>With fewer examples nothing can be verified.</summary>
|
||||||
|
public const int MinExamples = 100;
|
||||||
|
|
||||||
|
private const int MinTrain = 40;
|
||||||
|
|
||||||
|
public static double[] Row(IReadOnlyList<string> clues, IReadOnlyDictionary<string, double> features)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(clues);
|
||||||
|
ArgumentNullException.ThrowIfNull(features);
|
||||||
|
return [.. clues.Select(c => features.TryGetValue(c, out var value) ? value : double.NaN)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The share of winners by strategy: what a model that knows nothing would answer.</summary>
|
||||||
|
public static IReadOnlyDictionary<string, double> SharesOf(IEnumerable<Example> examples) =>
|
||||||
|
examples.Where(e => e.IsLabelled).GroupBy(e => e.Strategy, StringComparer.Ordinal)
|
||||||
|
.ToDictionary(g => g.Key, g => (double)g.Count(e => e.Label!.Win == true) / g.Count(), StringComparer.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The clues that enter (SPEC 11.2): those rebuilt from the history, and those without one only when at least
|
||||||
|
/// <see cref="Clues.MinLive"/> live examples contain them. A clue that never changes tells nothing.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<string> CluesOf(IReadOnlyList<Example> examples)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(examples);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Clues.All.Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive)
|
||||||
|
.Select(c => c.Key)
|
||||||
|
.Where(key => examples.Where(e => e.Features.ContainsKey(key)).Select(e => e.Features[key]).Distinct().Take(2).Count() > 1),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Null when there are too few examples, or only winners or only losers.</summary>
|
||||||
|
public static TrainingResult? Train(TrainingInput input, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(input);
|
||||||
|
var cases = input.Examples.Where(e => e.IsLabelled).OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal).ToList();
|
||||||
|
var clues = CluesOf(cases);
|
||||||
|
if (cases.Count < MinExamples || clues.Count == 0 || !BothOutcomes(cases))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsFunded(Example e) => input.Funded.Contains(e.Strategy);
|
||||||
|
var all = !cases.Any(IsFunded);
|
||||||
|
var forward = CaseSplits.Forward(cases);
|
||||||
|
var combined = CaseSplits.Combinatorial(cases);
|
||||||
|
var attempts = new List<Attempt>();
|
||||||
|
var fitted = new Dictionary<string, List<(TrainedModel Model, Split Split, IReadOnlyDictionary<string, double> Rates)>>(StringComparer.Ordinal);
|
||||||
|
foreach (var learner in LearnerNames.All)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
var folds = new List<(TrainedModel, Split, IReadOnlyDictionary<string, double>)>();
|
||||||
|
var ahead = Verify(learner, cases, forward, clues, input, null, cancellationToken);
|
||||||
|
var mixed = Verify(learner, cases, combined, clues, input, folds, cancellationToken);
|
||||||
|
fitted[learner] = folds;
|
||||||
|
attempts.Add(new Attempt(learner, ScoresOf(ahead, input, all ? null : IsFunded), ScoresOf(mixed, input, all ? null : IsFunded), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
var (chosen, reason) = Choose(attempts);
|
||||||
|
var model = Fit(chosen, cases, clues, input.Seed, cancellationToken);
|
||||||
|
var report = new ModelReport
|
||||||
|
{
|
||||||
|
Examples = cases.Count,
|
||||||
|
Live = cases.Count(e => e.Source == CaseSources.Live),
|
||||||
|
ByStrategy = cases.GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
|
||||||
|
BaseRates = input.BaseRates,
|
||||||
|
FirstDay = cases[0].Day,
|
||||||
|
LastDay = cases[^1].Day,
|
||||||
|
Attempts = [.. attempts.Select(a => a with { Chosen = a.Learner == chosen })],
|
||||||
|
Reason = reason,
|
||||||
|
AllStrategiesCounted = all,
|
||||||
|
Weights = WeightsOf(fitted[chosen], cases, clues, input.Seed),
|
||||||
|
Splits = combined.Count,
|
||||||
|
};
|
||||||
|
return new TrainingResult(model, report);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rule of the choice, fixed before looking at the numbers.</summary>
|
||||||
|
public static (string Learner, string Reason) Choose(IReadOnlyList<Attempt> attempts)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(attempts);
|
||||||
|
|
||||||
|
// Gains that differ by less than a tenth of a cent are the same gain.
|
||||||
|
static double Gain(Attempt a) => Math.Round(a.Combined.Improvement, 3);
|
||||||
|
var best = attempts.Where(a => a.Learner != LearnerNames.Forest).OrderByDescending(Gain).ThenBy(a => a.Combined.LogLoss).ThenBy(a => a.Learner == LearnerNames.Boosting ? 0 : 1).First();
|
||||||
|
var forest = attempts.FirstOrDefault(a => a.Learner == LearnerNames.Forest);
|
||||||
|
if (forest is not null && attempts.Where(a => a != forest).All(a => Gain(forest) > Gain(a) && forest.Combined.LogLoss < a.Combined.LogLoss))
|
||||||
|
{
|
||||||
|
return (forest.Learner, "La foresta casuale ha battuto gli altri due sia sul guadagno medio per operazione proposta sia sulle probabilità.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var others = attempts.Where(a => a.Learner != LearnerNames.Forest && a != best).ToList();
|
||||||
|
return (best.Learner, others.All(a => Gain(best) > Gain(a))
|
||||||
|
? $"{LearnerNames.Label(best.Learner)}: il miglior guadagno medio per operazione proposta su esempi mai visti."
|
||||||
|
: $"{LearnerNames.Label(best.Learner)}: a parità di guadagno, probabilità più vicine al vero su esempi mai visti.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A model on all the given examples: the calibration is fitted on estimates of examples each fit had not studied.</summary>
|
||||||
|
public static TrainedModel Fit(string learner, IReadOnlyList<Example> cases, IReadOnlyList<string> clues, long seed, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(cases);
|
||||||
|
ArgumentNullException.ThrowIfNull(clues);
|
||||||
|
var scores = new List<double>();
|
||||||
|
var wins = new List<bool>();
|
||||||
|
foreach (var fold in CaseSplits.Folds(cases))
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
var train = fold.Train.Select(i => cases[i]).ToList();
|
||||||
|
if (train.Count < MinTrain || !BothOutcomes(train))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var inner = Learners.Fit(learner, Rows(train, clues), Wins(train), seed);
|
||||||
|
scores.AddRange(fold.Test.Select(i => inner.Score(Row(clues, cases[i].Features))));
|
||||||
|
wins.AddRange(fold.Test.Select(i => cases[i].Label!.Win == true));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TrainedModel
|
||||||
|
{
|
||||||
|
Clues = clues,
|
||||||
|
Learned = Learners.Fit(learner, Rows(cases, clues), Wins(cases), seed),
|
||||||
|
Calibration = wins.Count > 0 ? Calibration.Fit(scores, wins) : Calibration.Platt([], Wins(cases)),
|
||||||
|
Ranges = clues.ToDictionary(c => c, c => RangeOf(cases, c), StringComparer.Ordinal),
|
||||||
|
Strategies = [.. cases.Select(c => c.Strategy).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Estimate> Verify(string learner, List<Example> cases, IReadOnlyList<Split> splits, IReadOnlyList<string> clues, TrainingInput input,
|
||||||
|
List<(TrainedModel, Split, IReadOnlyDictionary<string, double>)>? folds, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var estimates = new List<Estimate>();
|
||||||
|
foreach (var split in splits)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
var train = split.Train.Select(i => cases[i]).ToList();
|
||||||
|
if (train.Count < MinTrain || !BothOutcomes(train))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The base rate too is what the training examples knew: the one of the whole history would look ahead.
|
||||||
|
var model = Fit(learner, train, clues, input.Seed, cancellationToken);
|
||||||
|
var rates = SharesOf(train);
|
||||||
|
folds?.Add((model, split, rates));
|
||||||
|
foreach (var example in split.Test.Select(i => cases[i]).Where(e => rates.ContainsKey(e.Strategy)))
|
||||||
|
{
|
||||||
|
var probability = model.Probability(example.Features);
|
||||||
|
var rate = rates[example.Strategy];
|
||||||
|
estimates.Add(new Estimate(example, probability, rate, input.Rule.Of(probability, rate)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return estimates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scores ScoresOf(IReadOnlyList<Estimate> estimates, TrainingInput input, Func<Example, bool>? funded) =>
|
||||||
|
Judge.Score(Judge.Weigh(estimates, input.BaseRates), input.Capital, funded);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the model looks at: how much worse its estimates get, on examples it had not studied, when the values of a
|
||||||
|
/// group of clues are shuffled among them. Out of 100 with the largest remainder; all zero when nothing helps.
|
||||||
|
/// </summary>
|
||||||
|
private static List<ClueWeight> WeightsOf(IReadOnlyList<(TrainedModel Model, Split Split, IReadOnlyDictionary<string, double> Rates)> folds, List<Example> cases,
|
||||||
|
IReadOnlyList<string> clues, long seed)
|
||||||
|
{
|
||||||
|
var groups = clues.GroupBy(c => Clues.Find(c)!.Group, StringComparer.Ordinal).Select(g => (Name: g.Key, Columns: g.Select(c => IndexOf(clues, c)).ToArray())).ToList();
|
||||||
|
var losses = new double[groups.Count];
|
||||||
|
foreach (var (model, split, _) in folds)
|
||||||
|
{
|
||||||
|
var rows = split.Test.Select(i => Row(clues, cases[i].Features)).ToList();
|
||||||
|
var wins = split.Test.Select(i => cases[i].Label!.Win == true).ToList();
|
||||||
|
double Loss(IEnumerable<double[]> x) => x.Select((r, i) => Judge.LogLoss(wins[i], model.Calibration.Probability(model.Learned.Score(r)))).Sum();
|
||||||
|
var whole = Loss(rows);
|
||||||
|
for (var g = 0; g < groups.Count; g++)
|
||||||
|
{
|
||||||
|
var order = Enumerable.Range(0, rows.Count).ToArray();
|
||||||
|
new FixedRandom(seed + g).Shuffle(order);
|
||||||
|
losses[g] += Loss(rows.Select((r, i) =>
|
||||||
|
{
|
||||||
|
var mixed = (double[])r.Clone();
|
||||||
|
foreach (var column in groups[g].Columns)
|
||||||
|
{
|
||||||
|
mixed[column] = rows[order[i]][column];
|
||||||
|
}
|
||||||
|
|
||||||
|
return mixed;
|
||||||
|
})) - whole;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var shares = Format.Shares([.. losses.Select(l => (decimal)Math.Round(Math.Max(0, l), 9))], 0);
|
||||||
|
return [.. groups.Select((g, i) => new ClueWeight(g.Name, shares[i])).OrderByDescending(w => w.Share).ThenBy(w => w.Group, StringComparer.Ordinal)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int IndexOf(IReadOnlyList<string> clues, string key)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < clues.Count; i++)
|
||||||
|
{
|
||||||
|
if (clues[i] == key)
|
||||||
|
{
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClueRange RangeOf(IReadOnlyList<Example> cases, string clue)
|
||||||
|
{
|
||||||
|
var values = cases.Where(c => c.Features.ContainsKey(clue)).Select(c => c.Features[clue]).Order().ToList();
|
||||||
|
return values.Count == 0 ? new ClueRange(0, 0, 0) : new ClueRange(values[(int)(0.01 * (values.Count - 1))], values[(int)Math.Ceiling(0.99 * (values.Count - 1))], values.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<double[]> Rows(IReadOnlyList<Example> cases, IReadOnlyList<string> clues) => [.. cases.Select(c => Row(clues, c.Features))];
|
||||||
|
|
||||||
|
private static List<bool> Wins(IReadOnlyList<Example> cases) => [.. cases.Select(c => c.Label!.Win == true)];
|
||||||
|
|
||||||
|
private static bool BothOutcomes(IReadOnlyList<Example> cases) => cases.Any(c => c.Label!.Win == true) && cases.Any(c => c.Label!.Win != true);
|
||||||
|
}
|
||||||
@@ -31,6 +31,26 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
|
|||||||
"WHERE l.scope = @scope AND l.target = @t AND st.last_seen_at >= @since ORDER BY st.published_at, st.id",
|
"WHERE l.scope = @scope AND l.target = @t AND st.last_seen_at >= @since ORDER BY st.published_at, st.id",
|
||||||
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since)), cancellationToken).ConfigureAwait(false);
|
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since)), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The stories as they were at <paramref name="at"/>: only the articles, the links and the verdicts saved by then. A
|
||||||
|
/// story keeps growing after it is first read, and a decision recovered hours later must not see it grown (11.2).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IReadOnlyList<StoryFact>> StoriesAtAsync(string target, DateTimeOffset since, DateTimeOffset at, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
const string Then = "FROM news_items i WHERE i.story_id = st.id AND i.created_at <= @at";
|
||||||
|
const string Highest = "(SELECT MAX(x.importance) FROM news_items x WHERE x.story_id = st.id AND x.created_at <= @at)";
|
||||||
|
return await db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT st.id, st.title, st.published_at, st.first_seen_at, (SELECT COUNT(DISTINCT i.publisher) " + Then + ") AS sources, " +
|
||||||
|
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = st.id AND i.created_at <= @at AND so.trusted = @yes) > 0 AS trusted, " +
|
||||||
|
"(SELECT AVG(i.score) " + Then + ") AS score, (SELECT i.severe " + Then + " AND i.severe IS NOT NULL ORDER BY " + NewsStore.SevereOrder + ", i.id LIMIT 1) AS severe, " +
|
||||||
|
Highest + " AS importance, (SELECT MIN(i.published_at) " + Then + " AND i.importance = " + Highest + ") AS raised_at, " +
|
||||||
|
"v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, " +
|
||||||
|
"(SELECT i.publisher " + Then + " ORDER BY i.created_at, i.id LIMIT 1) AS publisher " +
|
||||||
|
"FROM news_stories st JOIN news_links l ON l.story_id = st.id LEFT JOIN news_verdicts v ON v.id = st.verdict_id AND v.created_at <= @at " +
|
||||||
|
"WHERE l.scope = @scope AND l.target = @t AND l.created_at <= @at AND st.last_seen_at >= @since AND EXISTS (SELECT 1 " + Then + ") ORDER BY st.published_at, st.id",
|
||||||
|
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since), ("at", at), ("yes", true)), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The state of 10.2 point 6 of one instrument now.</summary>
|
/// <summary>The state of 10.2 point 6 of one instrument now.</summary>
|
||||||
public async Task<InstrumentNewsState> StateAsync(string target, CancellationToken cancellationToken)
|
public async Task<InstrumentNewsState> StateAsync(string target, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -259,7 +259,7 @@ public sealed class NewsStore(Database db, IClock clock)
|
|||||||
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0";
|
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0";
|
||||||
|
|
||||||
// The serious cases in the order of 10.2.
|
// The serious cases in the order of 10.2.
|
||||||
private const string SevereOrder =
|
internal const string SevereOrder =
|
||||||
"CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" +
|
"CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" +
|
||||||
SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END";
|
SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END";
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ public static class CorrectiveReasons
|
|||||||
public const string CryptoRegimeAverage = "crypto_regime_below_average";
|
public const string CryptoRegimeAverage = "crypto_regime_below_average";
|
||||||
public const string CryptoRegimeVolatility = "crypto_regime_high_volatility";
|
public const string CryptoRegimeVolatility = "crypto_regime_high_volatility";
|
||||||
public const string CalendarEvent = "calendar_event";
|
public const string CalendarEvent = "calendar_event";
|
||||||
|
|
||||||
|
/// <summary>The learning model made the operation smaller (SPEC 11.1).</summary>
|
||||||
|
public const string ModelFilter = "model_filter";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them.</summary>
|
/// <summary>Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them.</summary>
|
||||||
|
|||||||
@@ -203,7 +203,7 @@ public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrateg
|
|||||||
{
|
{
|
||||||
if (target > _settings.RebalanceMinimum)
|
if (target > _settings.RebalanceMinimum)
|
||||||
{
|
{
|
||||||
intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop });
|
intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop, Strength = r.Tracker.Ensemble });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (held)
|
else if (held)
|
||||||
|
|||||||
@@ -144,7 +144,8 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var ranking = scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal).Select(s => s.Symbol).ToList();
|
scores = [.. scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal)];
|
||||||
|
var ranking = scores.Select(s => s.Symbol).ToList();
|
||||||
var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal);
|
var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal);
|
||||||
bool AboveTrend(string symbol)
|
bool AboveTrend(string symbol)
|
||||||
{
|
{
|
||||||
@@ -195,7 +196,11 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
|
|||||||
{
|
{
|
||||||
if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr)
|
if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr)
|
||||||
{
|
{
|
||||||
intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8) };
|
intents[symbol] = new Intent(symbol, weight, Reasons.Entry)
|
||||||
|
{
|
||||||
|
StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8),
|
||||||
|
Strength = scores[rank[symbol]].Score,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,7 +457,11 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
|
|||||||
continue; // Not enough free capital for this candidate: it is dropped.
|
continue; // Not enough free capital for this candidate: it is dropped.
|
||||||
}
|
}
|
||||||
|
|
||||||
intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = distance });
|
intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry)
|
||||||
|
{
|
||||||
|
StopOffset = distance,
|
||||||
|
Strength = (_settings.EntryRsi - c.Rsi) / _settings.EntryRsi,
|
||||||
|
});
|
||||||
freeCash -= value;
|
freeCash -= value;
|
||||||
slots--;
|
slots--;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,12 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason)
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool AtClose { get; init; }
|
public bool AtClose { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For a new entry: how strong the signal is, on the strategy's own scale (0 to 1 for <c>crypto_trend</c> and
|
||||||
|
/// <c>equity_meanrev</c>, the mean return of the lookbacks for <c>equity_momentum</c>). A clue of SPEC 11.2: no rule reads it.
|
||||||
|
/// </summary>
|
||||||
|
public double? Strength { get; init; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Reason codes of the correctives and of the risk engine that changed this intent after the strategy (SPEC 5.2):
|
/// Reason codes of the correctives and of the risk engine that changed this intent after the strategy (SPEC 5.2):
|
||||||
/// empty when it passed as the strategy proposed it.
|
/// empty when it passed as the strategy proposed it.
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ public static class DecisionStages
|
|||||||
{
|
{
|
||||||
public const string Strategy = "strategy";
|
public const string Strategy = "strategy";
|
||||||
public const string Correctives = "correctives";
|
public const string Correctives = "correctives";
|
||||||
|
|
||||||
|
/// <summary>What the learning model estimated of an entry (SPEC 11.5), whether it counts or not.</summary>
|
||||||
|
public const string Model = "model";
|
||||||
public const string Sizing = "sizing";
|
public const string Sizing = "sizing";
|
||||||
public const string Risk = "risk";
|
public const string Risk = "risk";
|
||||||
public const string Order = "order";
|
public const string Order = "order";
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Anubis.Backtest;
|
using Anubis.Backtest;
|
||||||
@@ -154,6 +155,9 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Func<DateOnly, CancellationToken, Task<EarningsView?>>? Earnings { get; init; }
|
public Func<DateOnly, CancellationToken, Task<EarningsView?>>? Earnings { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Learning (SPEC 11): notes the examples of each decision. Null in tests that do not look at it.</summary>
|
||||||
|
public Anubis.Learning.LearningDesk? Learning { get; init; }
|
||||||
|
|
||||||
/// <summary>The time zone of the diary's times: Italian time.</summary>
|
/// <summary>The time zone of the diary's times: Italian time.</summary>
|
||||||
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
|
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
|
||||||
|
|
||||||
@@ -493,6 +497,15 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters);
|
var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters);
|
||||||
var data = loaded.Data;
|
var data = loaded.Data;
|
||||||
var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false);
|
var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false);
|
||||||
|
var turn = Learning is null
|
||||||
|
? null
|
||||||
|
: await Learning.PrepareAsync(m.Strategy, stage.Stage, m.Day, m.Due, data, () => CreateStrategy(m.Strategy, stage.Qualification?.Parameters), await EarningsOfAsync(m, cancellationToken)
|
||||||
|
.ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (turn is not null)
|
||||||
|
{
|
||||||
|
options = options with { Correctives = turn.Around(options.Correctives) };
|
||||||
|
}
|
||||||
|
|
||||||
DecisionRecord record;
|
DecisionRecord record;
|
||||||
if (observation)
|
if (observation)
|
||||||
{
|
{
|
||||||
@@ -519,9 +532,12 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false);
|
plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false);
|
||||||
var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false);
|
var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false);
|
||||||
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||||
await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false);
|
await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, turn, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<IReadOnlyDictionary<string, DateOnly>?> EarningsOfAsync(Moment m, CancellationToken cancellationToken) =>
|
||||||
|
Earnings is null || m.Strategy == StrategyNames.CryptoTrend ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next;
|
||||||
|
|
||||||
private DateTimeOffset LateSince(string key, DateTimeOffset now)
|
private DateTimeOffset LateSince(string key, DateTimeOffset now)
|
||||||
{
|
{
|
||||||
if (!_lateSince.TryGetValue(key, out var since))
|
if (!_lateSince.TryGetValue(key, out var since))
|
||||||
@@ -780,7 +796,8 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
|
|
||||||
private Guid InstrumentIdOf(BacktestDataset data, string symbol) => _instrumentIds.TryGetValue(symbol, out var id) ? id : Guid.Empty;
|
private Guid InstrumentIdOf(BacktestDataset data, string symbol) => _instrumentIds.TryGetValue(symbol, out var id) ? id : Guid.Empty;
|
||||||
|
|
||||||
private readonly Dictionary<string, Guid> _instrumentIds = new(StringComparer.Ordinal);
|
// Also written by the labels of the night, which run beside the decisions.
|
||||||
|
private readonly ConcurrentDictionary<string, Guid> _instrumentIds = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
private static decimal? Close(BacktestInstrument instrument, DateOnly day)
|
private static decimal? Close(BacktestInstrument instrument, DateOnly day)
|
||||||
{
|
{
|
||||||
@@ -793,7 +810,8 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
r => r.Id("instrument_id"), ("a", account), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false)).ToHashSet();
|
r => r.Id("instrument_id"), ("a", account), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false)).ToHashSet();
|
||||||
|
|
||||||
private async Task WriteDecisionAsync(Moment m, StrategyStage stage, Guid account, string mode, DecisionRecord record, PlanResult plan, Book book,
|
private async Task WriteDecisionAsync(Moment m, StrategyStage stage, Guid account, string mode, DecisionRecord record, PlanResult plan, Book book,
|
||||||
IReadOnlyDictionary<string, InstrumentSpec> specs, (Guid DecisionId, bool Same, IReadOnlyList<string> Different)? oneStep, CancellationToken cancellationToken)
|
IReadOnlyDictionary<string, InstrumentSpec> specs, (Guid DecisionId, bool Same, IReadOnlyList<string> Different)? oneStep, Anubis.Learning.LearningTurn? turn,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var decisionId = Ids.NewId(_clock);
|
var decisionId = Ids.NewId(_clock);
|
||||||
var now = m.Now;
|
var now = m.Now;
|
||||||
@@ -839,6 +857,11 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (turn is not null)
|
||||||
|
{
|
||||||
|
await turn.WriteAsync(s, decisionId, account, now, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var (symbol, hold, dropped) in plan.Holds)
|
foreach (var (symbol, hold, dropped) in plan.Holds)
|
||||||
{
|
{
|
||||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Correctives,
|
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Correctives,
|
||||||
@@ -947,7 +970,8 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent;
|
private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent
|
||||||
|
or CorrectiveReasons.ModelFilter;
|
||||||
|
|
||||||
// The news rows go with the news in the diary, the calendar ones with the decisions.
|
// The news rows go with the news in the diary, the calendar ones with the decisions.
|
||||||
private static string DiaryKind(string code) => code is NewsReasons.Severe or NewsReasons.Negative ? DiaryKinds.News : DiaryKinds.Decisions;
|
private static string DiaryKind(string code) => code is NewsReasons.Severe or NewsReasons.Negative ? DiaryKinds.News : DiaryKinds.Decisions;
|
||||||
@@ -1301,7 +1325,38 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
/// <summary>The bars of a decision, its universe and what is missing on the day of the close.</summary>
|
/// <summary>The bars of a decision, its universe and what is missing on the day of the close.</summary>
|
||||||
private sealed record Loaded(BacktestDataset? Data, IReadOnlySet<string> Missing, bool MarketMissing);
|
private sealed record Loaded(BacktestDataset? Data, IReadOnlySet<string> Missing, bool MarketMissing);
|
||||||
|
|
||||||
private async Task<Loaded> LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken)
|
/// <summary>
|
||||||
|
/// What the nightly labels of learning need (SPEC 11.4): the bars through the last closed day, the instruments of the
|
||||||
|
/// open examples included even when they left the universe, from far enough before the oldest of them.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<Anubis.Learning.LabelData?> LabelDataAsync(string strategy, IReadOnlyList<Anubis.Learning.Example> open, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(open);
|
||||||
|
if (open.Count == 0 || await _stages.GetAsync(strategy, cancellationToken).ConfigureAwait(false) is not { } stage || LastClosed(strategy) is not { } through)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var loaded = await LoadAsync(strategy, through, Book.Empty, provisional: false, cancellationToken, [.. open.Select(e => e.Symbol)], open.Min(e => e.Day).AddDays(-Options.WarmupDays))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return loaded.Data is null ? null : new Anubis.Learning.LabelData(loaded.Data, through, () => CreateStrategy(strategy, stage.Qualification?.Parameters));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The last day whose bar is final: yesterday in UTC for crypto, the last session closed for a quarter of an hour for stocks.
|
||||||
|
private DateOnly? LastClosed(string strategy)
|
||||||
|
{
|
||||||
|
var now = _clock.UtcNow;
|
||||||
|
if (strategy == StrategyNames.CryptoTrend)
|
||||||
|
{
|
||||||
|
return DateOnly.FromDateTime(now.UtcDateTime).AddDays(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var today = Zones.DayIn(now, Zones.NewYork);
|
||||||
|
return _calendar is null ? null : Enumerable.Range(0, 14).Select(i => today.AddDays(-i)).Where(d => _calendar.SessionOn(d) is { } s && s.CloseUtc.AddMinutes(15) <= now).Cast<DateOnly?>().FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Loaded> LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken, IReadOnlyList<string>? extra = null,
|
||||||
|
DateOnly? since = null)
|
||||||
{
|
{
|
||||||
var crypto = strategy == StrategyNames.CryptoTrend;
|
var crypto = strategy == StrategyNames.CryptoTrend;
|
||||||
var venue = crypto ? Venues.Okx : Venues.Alpaca;
|
var venue = crypto ? Venues.Okx : Venues.Alpaca;
|
||||||
@@ -1313,6 +1368,7 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
symbols.UnionWith(book.Holdings.Keys);
|
symbols.UnionWith(book.Holdings.Keys);
|
||||||
|
symbols.UnionWith(extra ?? []);
|
||||||
var market = crypto ? NoBot.BitcoinSymbol : StrategyNames.MarketSymbol;
|
var market = crypto ? NoBot.BitcoinSymbol : StrategyNames.MarketSymbol;
|
||||||
var dataOnly = new HashSet<string>(StringComparer.Ordinal);
|
var dataOnly = new HashSet<string>(StringComparer.Ordinal);
|
||||||
if (symbols.Add(market) && !crypto)
|
if (symbols.Add(market) && !crypto)
|
||||||
@@ -1323,6 +1379,7 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
// The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The
|
// The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The
|
||||||
// stock strategies read windows: the warm-up of a trial is enough.
|
// stock strategies read windows: the warm-up of a trial is enough.
|
||||||
var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
|
var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
|
||||||
|
from = since < from ? since.Value : from;
|
||||||
var instruments = new List<BacktestInstrument>();
|
var instruments = new List<BacktestInstrument>();
|
||||||
var missing = new HashSet<string>(StringComparer.Ordinal);
|
var missing = new HashSet<string>(StringComparer.Ordinal);
|
||||||
var currency = crypto ? "EUR" : "USD";
|
var currency = crypto ? "EUR" : "USD";
|
||||||
|
|||||||
@@ -199,16 +199,10 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
|||||||
public PaperOptions Options => _options;
|
public PaperOptions Options => _options;
|
||||||
|
|
||||||
/// <summary>Slippage by liquidity tier (SPEC 7.3): 5 bp for stocks and BTC, ETH, SOL; 15 bp for other coins.</summary>
|
/// <summary>Slippage by liquidity tier (SPEC 7.3): 5 bp for stocks and BTC, ETH, SOL; 15 bp for other coins.</summary>
|
||||||
public static decimal SlippageBp(InstrumentSpec? spec)
|
public static decimal SlippageBp(InstrumentSpec? spec) => SlippageTable.Standard.Bp(spec);
|
||||||
{
|
|
||||||
if (spec is null || spec.AssetClass == AssetClasses.Equity)
|
|
||||||
{
|
|
||||||
return 5m;
|
|
||||||
}
|
|
||||||
|
|
||||||
var coin = spec.BaseCurrency ?? spec.Symbol.Split('-', '/')[0];
|
/// <summary>The slippage in force (SPEC 11.6): the standard one until the executions of a broker say otherwise.</summary>
|
||||||
return coin is "BTC" or "ETH" or "SOL" ? 5m : 15m;
|
public Func<SlippageTable> Slippage { get; init; } = () => SlippageTable.Standard;
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Puts money on the simulated account: the bot's capital lives in its ledger, this is only the balance.</summary>
|
/// <summary>Puts money on the simulated account: the bot's capital lives in its ledger, this is only the balance.</summary>
|
||||||
public async Task DepositAsync(decimal amount, string? currency, CancellationToken cancellationToken)
|
public async Task DepositAsync(decimal amount, string? currency, CancellationToken cancellationToken)
|
||||||
@@ -487,7 +481,7 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
|||||||
var open = (decimal)bar.Open;
|
var open = (decimal)bar.Open;
|
||||||
var high = (decimal)bar.High;
|
var high = (decimal)bar.High;
|
||||||
var low = (decimal)bar.Low;
|
var low = (decimal)bar.Low;
|
||||||
var slip = SlippageBp(_instruments(order.Request.Symbol)) / 10_000m;
|
var slip = Slippage().Bp(_instruments(order.Request.Symbol)) / 10_000m;
|
||||||
decimal? price = order.Request.Kind switch
|
decimal? price = order.Request.Kind switch
|
||||||
{
|
{
|
||||||
OrderKind.Market => open * (1m - slip),
|
OrderKind.Market => open * (1m - slip),
|
||||||
@@ -517,7 +511,7 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
|||||||
{
|
{
|
||||||
var request = order.Request;
|
var request = order.Request;
|
||||||
var spec = _instruments(request.Symbol);
|
var spec = _instruments(request.Symbol);
|
||||||
var slip = SlippageBp(spec) / 10_000m;
|
var slip = Slippage().Bp(spec) / 10_000m;
|
||||||
var remaining = request.Quantity - order.Filled;
|
var remaining = request.Quantity - order.Filled;
|
||||||
var firstLook = !order.Evaluated;
|
var firstLook = !order.Evaluated;
|
||||||
order.Evaluated = true;
|
order.Evaluated = true;
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ public static class ReasonCatalog
|
|||||||
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
|
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
|
||||||
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
|
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
|
||||||
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
|
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
|
||||||
|
["model_filter"] = "Il modello dava a questa operazione meno probabilità del solito: acquisto rimpicciolito o non fatto.",
|
||||||
// News and calendar (SPEC 10.5).
|
// News and calendar (SPEC 10.5).
|
||||||
["news_severe"] = "Un evento grave e negativo su questo strumento: niente nuovi acquisti per 72 ore.",
|
["news_severe"] = "Un evento grave e negativo su questo strumento: niente nuovi acquisti per 72 ore.",
|
||||||
["news_negative"] = "Una notizia negativa importante su questo strumento: niente acquisti né aumenti per 24 ore.",
|
["news_negative"] = "Una notizia negativa importante su questo strumento: niente acquisti né aumenti per 24 ore.",
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using Anubis.Data;
|
||||||
|
|
||||||
|
namespace Anubis.Trading;
|
||||||
|
|
||||||
|
/// <summary>The tiers of liquidity of SPEC 7.3.</summary>
|
||||||
|
public static class SlippageTiers
|
||||||
|
{
|
||||||
|
public const string Equity = "equity";
|
||||||
|
|
||||||
|
public const string Major = "crypto_major";
|
||||||
|
|
||||||
|
public const string Minor = "crypto_minor";
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> All = [Equity, Major, Minor];
|
||||||
|
|
||||||
|
public static string Of(InstrumentSpec? spec) => spec is null ? Equity : Of(spec.AssetClass, spec.BaseCurrency, spec.Symbol);
|
||||||
|
|
||||||
|
public static string Of(string assetClass, string? baseCurrency, string symbol)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(symbol);
|
||||||
|
if (assetClass == AssetClasses.Equity)
|
||||||
|
{
|
||||||
|
return Equity;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (baseCurrency ?? symbol.Split('-', '/')[0]) is "BTC" or "ETH" or "SOL" ? Major : Minor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Label(string tier) => tier switch
|
||||||
|
{
|
||||||
|
Equity => "azioni",
|
||||||
|
Major => "Bitcoin, Ethereum e Solana",
|
||||||
|
_ => "altre crypto",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The slippage the simulator and the backtest apply, in basis points by tier (SPEC 7.3, 11.6).</summary>
|
||||||
|
public sealed record SlippageTable(decimal Equity, decimal Major, decimal Minor)
|
||||||
|
{
|
||||||
|
public static SlippageTable Standard { get; } = new(5m, 5m, 15m);
|
||||||
|
|
||||||
|
public decimal Bp(InstrumentSpec? spec) => Of(SlippageTiers.Of(spec));
|
||||||
|
|
||||||
|
public decimal Of(string tier) => tier switch
|
||||||
|
{
|
||||||
|
SlippageTiers.Equity => Equity,
|
||||||
|
SlippageTiers.Major => Major,
|
||||||
|
SlippageTiers.Minor => Minor,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(tier), tier, "Unknown tier"),
|
||||||
|
};
|
||||||
|
|
||||||
|
public SlippageTable With(string tier, decimal bp) => tier switch
|
||||||
|
{
|
||||||
|
SlippageTiers.Equity => this with { Equity = bp },
|
||||||
|
SlippageTiers.Major => this with { Major = bp },
|
||||||
|
SlippageTiers.Minor => this with { Minor = bp },
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(tier), tier, "Unknown tier"),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -154,6 +154,7 @@ public sealed partial class TradingService : IDisposable
|
|||||||
private readonly BarStore _bars;
|
private readonly BarStore _bars;
|
||||||
private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new();
|
private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new();
|
||||||
private readonly ConcurrentDictionary<Guid, OrderManager> _managers = new();
|
private readonly ConcurrentDictionary<Guid, OrderManager> _managers = new();
|
||||||
|
private volatile SlippageTable _slippage = SlippageTable.Standard;
|
||||||
private RiskLimits _limits = RiskLimits.Default;
|
private RiskLimits _limits = RiskLimits.Default;
|
||||||
|
|
||||||
public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId,
|
public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId,
|
||||||
@@ -184,6 +185,7 @@ public sealed partial class TradingService : IDisposable
|
|||||||
Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false)));
|
Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false)));
|
||||||
Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile };
|
Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile };
|
||||||
_settings = settings;
|
_settings = settings;
|
||||||
|
Learning = new Anubis.Learning.LearningDesk(db, clock, settings, _logger);
|
||||||
Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger)
|
Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger)
|
||||||
{
|
{
|
||||||
WantData = market is null ? null : _ => market.WakeWorker(),
|
WantData = market is null ? null : _ => market.WakeWorker(),
|
||||||
@@ -191,7 +193,11 @@ public sealed partial class TradingService : IDisposable
|
|||||||
Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct),
|
Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct),
|
||||||
Ready = () => _started,
|
Ready = () => _started,
|
||||||
AccountReady = AccountReady,
|
AccountReady = AccountReady,
|
||||||
|
Learning = Learning,
|
||||||
};
|
};
|
||||||
|
Cycle = new Anubis.Learning.LearningCycle(db, clock, Learning, Engine.LabelDataAsync);
|
||||||
|
Costs = new Anubis.Learning.CostBook(db, clock);
|
||||||
|
Discoveries = new Anubis.Learning.DiscoveryDesk(db, clock, Learning.Store);
|
||||||
}
|
}
|
||||||
|
|
||||||
private volatile bool _started;
|
private volatile bool _started;
|
||||||
@@ -214,8 +220,20 @@ public sealed partial class TradingService : IDisposable
|
|||||||
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
|
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
|
||||||
public LiveEngine Engine { get; }
|
public LiveEngine Engine { get; }
|
||||||
|
|
||||||
|
/// <summary>The nightly and weekly cycle of the model (SPEC 11.4).</summary>
|
||||||
|
public Anubis.Learning.LearningCycle Cycle { get; }
|
||||||
|
|
||||||
|
/// <summary>The slippage estimates (SPEC 11.6).</summary>
|
||||||
|
public Anubis.Learning.CostBook Costs { get; }
|
||||||
|
|
||||||
|
/// <summary>The discoveries in plain words (SPEC 11.6).</summary>
|
||||||
|
public Anubis.Learning.DiscoveryDesk Discoveries { get; }
|
||||||
|
|
||||||
private readonly SettingsStore? _settings;
|
private readonly SettingsStore? _settings;
|
||||||
|
|
||||||
|
/// <summary>Learning beside the decisions (SPEC 11).</summary>
|
||||||
|
public Anubis.Learning.LearningDesk Learning { get; }
|
||||||
|
|
||||||
public StageBook Stages { get; }
|
public StageBook Stages { get; }
|
||||||
|
|
||||||
/// <summary>The risk engine every intent crosses (SPEC 9). Null only without settings, in tests of the order manager alone.</summary>
|
/// <summary>The risk engine every intent crosses (SPEC 9). Null only without settings, in tests of the order manager alone.</summary>
|
||||||
@@ -327,6 +345,8 @@ public sealed partial class TradingService : IDisposable
|
|||||||
|
|
||||||
_accountsRetryAt = _clock.UtcNow + AccountRetry;
|
_accountsRetryAt = _clock.UtcNow + AccountRetry;
|
||||||
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
await GuardAsync("modello", () => Learning.PrepareHistoryAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
await GuardAsync("stime di costo", () => RefreshCostsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false);
|
await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
_started = true;
|
_started = true;
|
||||||
@@ -508,6 +528,60 @@ public sealed partial class TradingService : IDisposable
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The slippage in force, from the next fill of the simulator on.</summary>
|
||||||
|
public async Task RefreshCostsAsync(CancellationToken cancellationToken) => _slippage = await Costs.TableAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
/// <summary>The longest the night waits for the bars: without a network it goes on with those it has.</summary>
|
||||||
|
public static readonly TimeSpan BarsWait = TimeSpan.FromMinutes(30);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Waits until the bars through the last closed day are downloaded: after an absence the night starts with the process,
|
||||||
|
/// and labels made on the bars of before would see nothing of what happened meanwhile (SPEC 5.6, 9.4).
|
||||||
|
/// </summary>
|
||||||
|
public static async Task BarsReadyAsync(IClock clock, Func<DateTimeOffset?> lastRound, Func<Task> ask, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
ArgumentNullException.ThrowIfNull(lastRound);
|
||||||
|
ArgumentNullException.ThrowIfNull(ask);
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var midnight = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
|
||||||
|
if (lastRound() >= midnight)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await ask().ConfigureAwait(false);
|
||||||
|
while (!(lastRound() >= midnight) && clock.UtcNow < now + BarsWait)
|
||||||
|
{
|
||||||
|
await clock.WaitUntilAsync(clock.UtcNow + TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A part of the night that fails never stops the others.
|
||||||
|
private async Task NightAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_market is { } market)
|
||||||
|
{
|
||||||
|
await BarsReadyAsync(_clock, () => market.LastHistoryRun, market.WakeWorker, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Cycle.RunAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await GuardAsync("stime di costo", () => Costs.MonthAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
await GuardAsync("stime di costo", () => RefreshCostsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
await GuardAsync("scoperte", () => Discoveries.RefreshAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The night of the model: once, however long the absence or the sleep of the computer (SPEC 5.6), and beside the others because it is long.</summary>
|
||||||
|
public static ScheduledJob ModelJob(Func<CancellationToken, Task> run) =>
|
||||||
|
new("modello", "Etichette e controllo del modello", Schedule.Daily(new TimeOnly(3, 0), Zones.Rome), run)
|
||||||
|
{ MaxLateness = TimeSpan.FromDays(3650), CatchUpWithin = TimeSpan.FromDays(3650), Beside = true };
|
||||||
|
|
||||||
public IReadOnlyList<ScheduledJob> Jobs() =>
|
public IReadOnlyList<ScheduledJob> Jobs() =>
|
||||||
[
|
[
|
||||||
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
|
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
|
||||||
@@ -515,6 +589,7 @@ public sealed partial class TradingService : IDisposable
|
|||||||
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
||||||
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
|
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
|
||||||
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
|
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
|
||||||
|
ModelJob(NightAsync),
|
||||||
.. Engine.Jobs(),
|
.. Engine.Jobs(),
|
||||||
.. _market is null ? Array.Empty<ScheduledJob>() :
|
.. _market is null ? Array.Empty<ScheduledJob>() :
|
||||||
[
|
[
|
||||||
@@ -875,7 +950,8 @@ public sealed partial class TradingService : IDisposable
|
|||||||
case TradingEnvironments.Simulation:
|
case TradingEnvironments.Simulation:
|
||||||
var options = account.Broker == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(account.Currency);
|
var options = account.Broker == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(account.Currency);
|
||||||
return new PaperBroker(options, _clock, Quotes.GetAsync, symbol => _specs.GetValueOrDefault((account.Broker, symbol)),
|
return new PaperBroker(options, _clock, Quotes.GetAsync, symbol => _specs.GetValueOrDefault((account.Broker, symbol)),
|
||||||
new PaperBookStore(_db, _clock, account.AccountId));
|
new PaperBookStore(_db, _clock, account.AccountId))
|
||||||
|
{ Slippage = () => _slippage };
|
||||||
case TradingEnvironments.Demo when account.Broker == Venues.Alpaca && alpaca is not null:
|
case TradingEnvironments.Demo when account.Broker == Venues.Alpaca && alpaca is not null:
|
||||||
return new AlpacaTrading(_http, _clock, alpaca, new AlpacaTradingOptions { Environment = account.Environment }, _consent, _sockets);
|
return new AlpacaTrading(_http, _clock, alpaca, new AlpacaTradingOptions { Environment = account.Environment }, _consent, _sockets);
|
||||||
case TradingEnvironments.Demo when account.Broker == Venues.Okx && okx is not null:
|
case TradingEnvironments.Demo when account.Broker == Venues.Okx && okx is not null:
|
||||||
|
|||||||
@@ -68,6 +68,59 @@ public sealed class LaboratoryScreenTests
|
|||||||
StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato.");
|
StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.6: a lower slippage waits in the Laboratorio for the confirmation of the user.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ALowerCostIsConfirmedFromTheLaboratory()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
var db = server.Host.Services!.Db;
|
||||||
|
async Task<Guid> PendingAsync(decimal bp)
|
||||||
|
{
|
||||||
|
var id = Ids.NewId(SystemClock.Instance);
|
||||||
|
await db.WriteAsync(s => s.ExecuteAsync(
|
||||||
|
"INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, 'crypto_minor', 'pending', @p, @b, @b, @b, @b, 40, @now, @now)",
|
||||||
|
CancellationToken.None, ("id", id), ("p", 15m), ("b", bp), ("now", DateTimeOffset.UtcNow)));
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
var refused = await PendingAsync(9m);
|
||||||
|
StringAssert.Contains(await server.TextAsync("/laboratorio"), "Altre crypto: da 15 punti base a 9 punti base.");
|
||||||
|
using (var no = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/rifiuta", []))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(no));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var late = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/conferma", []))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/laboratorio?errore=stima#stime", ServerHarness.Location(late));
|
||||||
|
}
|
||||||
|
|
||||||
|
var confirmed = await PendingAsync(8m);
|
||||||
|
|
||||||
|
// Without the token of the page nothing is decided.
|
||||||
|
using (var forged = await server.Http.PostAsync(new Uri($"/azioni/stime-di-costo/{confirmed}/conferma", UriKind.Relative), new FormUrlEncodedContent([])))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, forged.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var seen = await server.Http.PostAsync(new Uri($"/azioni/assenza/{confirmed}/vista", UriKind.Relative), new FormUrlEncodedContent([])))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, seen.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var yes = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{confirmed}/conferma", []))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(yes));
|
||||||
|
}
|
||||||
|
|
||||||
|
var page = await server.TextAsync("/laboratorio");
|
||||||
|
StringAssert.Contains(page, "altre crypto 8 punti base");
|
||||||
|
StringAssert.Contains(page, "Confermata da te");
|
||||||
|
StringAssert.Contains(page, "Rifiutata da te");
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
[TestCategory(Category.Integration)]
|
[TestCategory(Category.Integration)]
|
||||||
public async Task TheDemoRunsNoTests()
|
public async Task TheDemoRunsNoTests()
|
||||||
|
|||||||
@@ -0,0 +1,287 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The archive of the examples and their labels (SPEC 11.2, issue #62).</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class LearningCasesTests
|
||||||
|
{
|
||||||
|
private static readonly DateOnly First = new(2023, 1, 1);
|
||||||
|
|
||||||
|
internal static BacktestDataset Coins(int days = 900, int coins = 3)
|
||||||
|
{
|
||||||
|
var names = new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR", "ADA-EUR", "XRP-EUR" };
|
||||||
|
return new BacktestDataset(Enumerable.Range(0, coins).Select(i =>
|
||||||
|
new BacktestInstrument(MarketDataStoreTests.Okx(names[i]) with { ListedAt = null }, LiveRig.Synthetic(First, days, 100 * (i + 1), (uint)(7 + i)))), "EUR");
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static IReadOnlyList<Example> History(BacktestDataset data) =>
|
||||||
|
HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data,
|
||||||
|
StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = First.AddDays(420) }));
|
||||||
|
|
||||||
|
/// <summary>Criterion of the phase: no clue changes when data after the decision is added.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void NoClueUsesDataAfterTheDecision()
|
||||||
|
{
|
||||||
|
var data = Coins();
|
||||||
|
var full = History(data);
|
||||||
|
Assert.IsGreaterThan(20, full.Count);
|
||||||
|
foreach (var cut in new[] { 500, 600, 700, 800, 890 }.Select(d => First.AddDays(d)))
|
||||||
|
{
|
||||||
|
var known = History(data.Through(cut));
|
||||||
|
var before = full.Where(e => e.Day <= cut).ToList();
|
||||||
|
Assert.HasCount(before.Count, known, $"cut {cut}");
|
||||||
|
foreach (var (a, b) in before.Zip(known))
|
||||||
|
{
|
||||||
|
Assert.AreEqual((a.Symbol, a.Day, a.Weight, a.Stop), (b.Symbol, b.Day, b.Weight, b.Stop));
|
||||||
|
Assert.AreEqual(Text(a), Text(b), $"{a.Symbol} {a.Day}");
|
||||||
|
|
||||||
|
// The outcome is known only once the operation is closed, and then it is the final one.
|
||||||
|
Assert.AreEqual(a.Label is { ClosedDay: { } closed } && closed <= cut ? a.Label : null, b.Label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Text(Example e) => string.Join(';', e.Features.Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
|
||||||
|
|
||||||
|
/// <summary>The same for what comes from outside the bars: only values already dated, saved and read.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task NothingSavedOrDatedAfterTheDecisionIsRead()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var none = CancellationToken.None;
|
||||||
|
var at = rig.Clock.UtcNow;
|
||||||
|
var mood = new MoodStore(rig.Db, rig.Clock);
|
||||||
|
var reader = new OutsideReader(rig.Db, rig.Clock);
|
||||||
|
var specs = new Dictionary<string, InstrumentSpec> { ["BTC-EUR"] = TradingRig.Btc };
|
||||||
|
await mood.UpsertAsync([new(MoodIndicators.FearGreed, at.AddHours(-20), 30, null, "t"), new(MoodIndicators.Vix, at.AddDays(-1), 18, null, "t"),
|
||||||
|
new(MoodIndicators.BtcFunding, at.AddHours(-3), 0.0001, null, "t"), .. Enumerable.Range(1, 10).Select(i => new MoodReading(MoodIndicators.BtcOpenInterest, at.AddDays(-i), 100, null, "t")),
|
||||||
|
new(MoodIndicators.FearGreed, at.AddHours(1), 99, null, "t")], none).ConfigureAwait(false);
|
||||||
|
await StoryAsync(rig, "Nota prima", at.AddHours(-5), at.AddHours(-4), 0.5).ConfigureAwait(false);
|
||||||
|
var before = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(30d, before.FearGreed);
|
||||||
|
Assert.AreEqual(18d, before.Vix);
|
||||||
|
Assert.AreEqual(1d, before.BtcOpenInterest);
|
||||||
|
Assert.AreEqual(1, before.Stories3Days["BTC-EUR"]);
|
||||||
|
Assert.AreEqual(0.5, before.News["BTC-EUR"].Tone1Day);
|
||||||
|
|
||||||
|
// Later: values dated before the decision but saved after it (published late), and a story published before and
|
||||||
|
// read after. The past must look the same.
|
||||||
|
rig.Clock.Advance(TimeSpan.FromHours(6));
|
||||||
|
await mood.UpsertAsync([new(MoodIndicators.Vix, at.AddHours(-2), 44, null, "t"), new(MoodIndicators.FearGreed, at.AddHours(-1), 5, null, "t"),
|
||||||
|
new(MoodIndicators.BtcFunding, at.AddMinutes(-1), 0.9, null, "t"), new(MoodIndicators.BtcOpenInterest, at.AddMinutes(-1), 900, null, "t")], none).ConfigureAwait(false);
|
||||||
|
await StoryAsync(rig, "Letta dopo", at.AddHours(-1), at.AddHours(2), -0.9).ConfigureAwait(false);
|
||||||
|
var again = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual((before.FearGreed, before.Vix, before.BtcFunding, before.BtcOpenInterest), (again.FearGreed, again.Vix, again.BtcFunding, again.BtcOpenInterest));
|
||||||
|
Assert.AreEqual(before.Stories3Days["BTC-EUR"], again.Stories3Days["BTC-EUR"]);
|
||||||
|
Assert.AreEqual(before.News["BTC-EUR"].Tone3Days, again.News["BTC-EUR"].Tone3Days);
|
||||||
|
|
||||||
|
// A value too old is no value: the source stopped.
|
||||||
|
rig.Clock.Advance(TimeSpan.FromDays(40));
|
||||||
|
var late = await reader.ReadAsync(rig.Clock.UtcNow, specs, null, none).ConfigureAwait(false);
|
||||||
|
Assert.IsNull(late.FearGreed);
|
||||||
|
Assert.IsNull(late.Vix);
|
||||||
|
Assert.IsNull(late.BtcOpenInterest);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task StoryAsync(TradingRig rig, string title, DateTimeOffset published, DateTimeOffset seen, double score)
|
||||||
|
{
|
||||||
|
var id = Ids.NewId(rig.Clock);
|
||||||
|
await rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync(
|
||||||
|
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " +
|
||||||
|
"VALUES (@id, @t, @t, @p, @f, @f, 1, @yes, @s, 1, @f, @f)", ("id", id), ("t", title), ("p", published), ("f", seen), ("yes", true), ("s", score)).ConfigureAwait(false);
|
||||||
|
await ArticleAsync(s, rig, id, title, published, seen, score).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', 'okx:BTC-EUR', 'name', @f)",
|
||||||
|
("id", Ids.NewId(rig.Clock)), ("st", id), ("f", seen)).ConfigureAwait(false);
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An article of a story, saved at a moment, from a source of its own.</summary>
|
||||||
|
internal static async Task ArticleAsync(DbSession s, TradingRig rig, Guid story, string title, DateTimeOffset published, DateTimeOffset saved, double score, int importance = 1)
|
||||||
|
{
|
||||||
|
var (source, item) = (Ids.NewId(rig.Clock), Ids.NewId(rig.Clock));
|
||||||
|
await s.ExecuteAsync("INSERT INTO news_sources (id, url, name, kind, trusted, enabled, failures, created_at, updated_at) VALUES (@id, @u, @u, 'rss', @yes, @yes, 0, @f, @f)",
|
||||||
|
("id", source), ("u", "https://t/" + source), ("yes", true), ("f", saved)).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, language, published_at, score, importance, created_at) " +
|
||||||
|
"VALUES (@id, @st, @so, @u, @u, @pub, @t, 'en', @p, @s, @i, @f)", ("id", item), ("st", story), ("so", source), ("u", "https://t/a/" + item), ("pub", "t" + source), ("t", title), ("p", published), ("s", score),
|
||||||
|
("i", importance), ("f", saved)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Enters while not held, on a fixed day leaves; every day proposes again what it does not hold.</summary>
|
||||||
|
private sealed class Stubborn(DateOnly from, DateOnly exit, decimal weight = 0.3m, decimal? stop = null) : IStrategy
|
||||||
|
{
|
||||||
|
public string Id => StrategyNames.CryptoTrend;
|
||||||
|
|
||||||
|
public string Version => "t";
|
||||||
|
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||||
|
{
|
||||||
|
if (context.Day < from)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.Portfolio.Holds("BTC-EUR"))
|
||||||
|
{
|
||||||
|
return context.Day == exit ? [new Intent("BTC-EUR", 0m, "trend_exit")] : [new Intent("BTC-EUR", weight * 2, "trend_increase")];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [new Intent("BTC-EUR", weight, "trend_entry") { Strength = 0.5, Stop = stop }];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RefuseAll : IIntentStage
|
||||||
|
{
|
||||||
|
public string Name => "refuse";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => [.. intents.Where(i => i.TargetWeight is 0m)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class HalveAll : IIntentStage
|
||||||
|
{
|
||||||
|
public string Name => "halve";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => [.. intents.Select(i => i with { TargetWeight = i.TargetWeight / 2 })];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One example for the first entry, even refused: proposals repeated and increases make none until it closes.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void OneExampleForEachFirstEntryEvenWhenNothingIsBought()
|
||||||
|
{
|
||||||
|
var data = Coins(400, 1);
|
||||||
|
var (from, exit) = (First.AddDays(100), First.AddDays(130));
|
||||||
|
IReadOnlyList<Example> Build(params IIntentStage[] stages) =>
|
||||||
|
HistoryCases.Build(StrategyNames.CryptoTrend, () => new Stubborn(from, exit), data, new BacktestOptions { To = First.AddDays(140), Correctives = stages });
|
||||||
|
|
||||||
|
var executed = Build();
|
||||||
|
var refused = Build(new RefuseAll());
|
||||||
|
var halved = Build(new HalveAll());
|
||||||
|
Assert.AreEqual(from, executed[0].Day);
|
||||||
|
Assert.AreEqual(exit.AddDays(1), executed[0].Label!.ClosedDay, "sold at the open after the exit");
|
||||||
|
|
||||||
|
// After the exit the strategy enters again: a second example, still open at the end.
|
||||||
|
Assert.HasCount(2, executed);
|
||||||
|
Assert.IsNull(executed[1].Label);
|
||||||
|
foreach (var other in new[] { refused, halved })
|
||||||
|
{
|
||||||
|
// The same examples and the same label whatever the bot did with the signal.
|
||||||
|
Assert.HasCount(2, other);
|
||||||
|
Assert.AreEqual((executed[0].Day, executed[0].Weight), (other[0].Day, other[0].Weight));
|
||||||
|
Assert.AreEqual(executed[0].Label, other[0].Label);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(0.5, executed[0].Features[Clues.Strength]);
|
||||||
|
Assert.AreEqual(1d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.CryptoTrend]);
|
||||||
|
Assert.AreEqual(0d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.EquityMeanrev]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label: the result of the operation alone, net of every cost, with the exits and the stop of its strategy.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheLabelIsTheOperationAloneNetOfCosts()
|
||||||
|
{
|
||||||
|
var spec = MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null };
|
||||||
|
DailyBar Bar(int i, double open, double low, double close) => new(First.AddDays(i), open, Math.Max(open, close), low, close, 1e6);
|
||||||
|
var bars = new List<DailyBar> { Bar(0, 100, 99, 100), Bar(1, 100, 99, 100), Bar(2, 100, 99, 100), Bar(3, 100.4, 99, 100.4), Bar(4, 100.4, 99, 100.4), Bar(5, 100, 80, 85), Bar(6, 85, 84, 85) };
|
||||||
|
var data = new BacktestDataset([new BacktestInstrument(spec, bars)], "EUR");
|
||||||
|
var example = new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.History, First.AddDays(1), default, "trend_entry", 0.2m, null, null, new Dictionary<string, double>());
|
||||||
|
|
||||||
|
// Bought at the open of day 2, sold at the open of day 4: +0.4% gross, a loss once fees and slippage are paid.
|
||||||
|
var label = CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6))!;
|
||||||
|
Assert.AreEqual((First.AddDays(2), First.AddDays(4), "trend_exit"), (label.OpenedDay, label.ClosedDay, label.ExitReason));
|
||||||
|
Assert.IsFalse(label.Win);
|
||||||
|
Assert.IsLessThan(0d, label.Result!.Value);
|
||||||
|
Assert.IsTrue(CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6), new CostModel(0m))!.Win);
|
||||||
|
|
||||||
|
// The stop of the intent closes it on day 5, and before that day the label is not known.
|
||||||
|
var stopped = example with { Stop = 90m };
|
||||||
|
var never = () => (IStrategy)new Stubborn(First.AddDays(1), DateOnly.MaxValue);
|
||||||
|
Assert.AreEqual(First.AddDays(5), CaseLabels.Of(stopped, never, data, First.AddDays(6))!.ClosedDay);
|
||||||
|
Assert.IsNull(CaseLabels.Of(stopped, never, data, First.AddDays(4)));
|
||||||
|
Assert.IsNull(CaseLabels.Of(example, never, data, First.AddDays(6)), "an operation still open has no label");
|
||||||
|
|
||||||
|
// One that can never start (below the minimum of the market) has no outcome and never trains.
|
||||||
|
var tooBig = new BacktestDataset([new BacktestInstrument(spec with { MinSize = 1_000_000m }, bars)], "EUR");
|
||||||
|
var empty = CaseLabels.Of(example, never, tooBig, First.AddDays(6))!;
|
||||||
|
Assert.IsNull(empty.Win);
|
||||||
|
Assert.IsFalse((example with { Label = empty }).IsLabelled);
|
||||||
|
Assert.IsTrue((example with { Label = label }).IsLabelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Saved and read back the same on both engines; a label is written once.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheArchiveReadsBackTheSame()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var none = CancellationToken.None;
|
||||||
|
var store = new LearningStore(rig.Db, rig.Clock);
|
||||||
|
var example = new Example(Guid.Empty, StrategyNames.EquityMeanrev, "AAPL", CaseSources.Live, First, rig.Clock.UtcNow, "meanrev_entry", 0.123456m, null, 4.25m,
|
||||||
|
new Dictionary<string, double> { [Clues.Strength] = 0.1 + 0.2, [Clues.Breadth] = 1 })
|
||||||
|
{ Stage = StrategyStages.Observation, DecisionId = Ids.NewId(rig.Clock), Multiplier = 0.4 };
|
||||||
|
var id = (await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false))!.Value;
|
||||||
|
Assert.IsNull(await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false), "the same example again");
|
||||||
|
var read = (await store.AllAsync(none).ConfigureAwait(false)).Single();
|
||||||
|
Assert.AreEqual((id, example.Symbol, example.Weight, example.Stop, example.StopOffset, example.Stage, example.DecisionId, example.Multiplier),
|
||||||
|
(read.Id, read.Symbol, read.Weight, read.Stop, read.StopOffset, read.Stage, read.DecisionId, read.Multiplier));
|
||||||
|
CollectionAssert.AreEqual(example.Features.ToList(), read.Features.OrderBy(f => f.Key, StringComparer.Ordinal).Reverse().ToList());
|
||||||
|
Assert.HasCount(1, await store.OpenAsync(none).ConfigureAwait(false));
|
||||||
|
|
||||||
|
var label = new CaseLabel(true, 0.0123, First.AddDays(1), First.AddDays(4), "meanrev_exit_rsi");
|
||||||
|
await store.AddLabelAsync(id, label, none).ConfigureAwait(false);
|
||||||
|
await store.AddLabelAsync(id, label with { Win = false }, none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(label, (await store.AllAsync(none).ConfigureAwait(false)).Single().Label);
|
||||||
|
Assert.HasCount(0, await store.OpenAsync(none).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Live: the examples are those of the history on the same days, with the same clues, both for a strategy that trades
|
||||||
|
/// and for one in observation; a restart in the middle adds none.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
[DataRow(StrategyStages.Simulation)]
|
||||||
|
[DataRow(StrategyStages.Observation)]
|
||||||
|
public async Task TheLiveEngineSavesTheSameExamplesAsTheHistory(string stage)
|
||||||
|
{
|
||||||
|
var from = new DateOnly(2026, 6, 1);
|
||||||
|
var last = from.AddDays(40);
|
||||||
|
await using var rig = await LiveRig.CreateAsync(from, last, stage: stage).ConfigureAwait(false);
|
||||||
|
for (var day = from; day <= last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await rig.DayAsync(day, morning: 6).ConfigureAwait(false);
|
||||||
|
if (day == from.AddDays(17))
|
||||||
|
{
|
||||||
|
await rig.RestartAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR");
|
||||||
|
var expected = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data,
|
||||||
|
StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = from.AddDays(-1) }));
|
||||||
|
var live = await new LearningStore(rig.Rig.Db, rig.Rig.Clock).AllAsync(CancellationToken.None).ConfigureAwait(false);
|
||||||
|
Assert.IsGreaterThan(1, expected.Count);
|
||||||
|
Assert.AreEqual(string.Join(", ", expected.Select(e => $"{e.Symbol} {e.Day:MM-dd}")), string.Join(", ", live.Select(e => $"{e.Symbol} {e.Day:MM-dd}")));
|
||||||
|
foreach (var (a, b) in expected.Zip(live))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(stage, b.Stage);
|
||||||
|
Assert.AreEqual(Text(a), string.Join(';', b.Features.Where(f => a.Features.ContainsKey(f.Key)).OrderBy(f => f.Key, StringComparer.Ordinal)
|
||||||
|
.Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,646 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The model in the decisions and its cycle: shadow, promotion, drift, set-aside, start (SPEC 11.1, 11.4, 11.5; issue #64).</summary>
|
||||||
|
[TestClass]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public sealed class LearningCycleTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
|
||||||
|
internal static readonly DateOnly From = new(2026, 6, 1);
|
||||||
|
|
||||||
|
/// <summary>A model that always answers <paramref name="probability"/>.</summary>
|
||||||
|
internal static TrainedModel Always(double probability) => new()
|
||||||
|
{
|
||||||
|
Clues = [Clues.Strength],
|
||||||
|
Learned = new Learned { Learner = LearnerNames.Logistic, Linear = new LinearBody(Odds.Logit(probability), [0], [0], [1]) },
|
||||||
|
Ranges = new Dictionary<string, ClueRange> { [Clues.Strength] = new(0, 1, 100) },
|
||||||
|
Strategies = [StrategyNames.CryptoTrend],
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 } };
|
||||||
|
|
||||||
|
internal static Task<ModelRow> AddModelAsync(Database db, IClock clock, TrainedModel model, string status, int examples = 500) =>
|
||||||
|
db.WriteAsync(s => ModelStore.RegisterAsync(s, clock, model, new ModelReport { Examples = examples, Attempts = [new Attempt(LearnerNames.Logistic, new Scores(), new Scores(), true)] }, status, "test", clock.UtcNow, _none), _none);
|
||||||
|
|
||||||
|
private static Task StateAsync(Database db, IClock clock, CycleState state) => db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, _none), _none);
|
||||||
|
|
||||||
|
// ---- In the decisions -------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private sealed record Run(IReadOnlyList<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> Fills, IReadOnlyList<Example> Examples, IReadOnlyList<PredictionRow> Predictions,
|
||||||
|
IReadOnlyList<DecisionRow> Rows, int Failures);
|
||||||
|
|
||||||
|
private static async Task<Run> LiveAsync(TrainedModel? champion, bool active, TrainedModel? challenger = null, FirstModelFile? rates = null, string stage = StrategyStages.Simulation, int days = 20,
|
||||||
|
Func<LiveRig, DateOnly, Task>? before = null)
|
||||||
|
{
|
||||||
|
var last = From.AddDays(days);
|
||||||
|
await using var rig = await LiveRig.CreateAsync(From, last, stage: stage).ConfigureAwait(false);
|
||||||
|
rig.UseFirst(rates ?? Rates);
|
||||||
|
if (champion is not null)
|
||||||
|
{
|
||||||
|
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, champion, ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (challenger is not null)
|
||||||
|
{
|
||||||
|
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, challenger, ModelStatuses.Challenger).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (active)
|
||||||
|
{
|
||||||
|
await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var day = From; day <= last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
if (before is not null)
|
||||||
|
{
|
||||||
|
await before(rig, day).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var fills = await rig.Rig.QueryAsync("SELECT i.symbol, f.side, f.quantity, f.executed_at FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, i.symbol",
|
||||||
|
r => (r.Text("symbol"), r.Text("side"), r.Money("quantity"), r.Moment("executed_at"))).ConfigureAwait(false);
|
||||||
|
var rows = await rig.Rig.QueryAsync("SELECT symbol, stage, outcome, data FROM decisions WHERE stage = 'model' ORDER BY created_at",
|
||||||
|
r => new DecisionRow(Guid.Empty, "", null, r.TextOrNull("symbol"), r.Text("stage"), r.Text("outcome"), [], new Dictionary<string, object?> { ["json"] = r.TextOrNull("data") }, default)).ConfigureAwait(false);
|
||||||
|
return new Run([.. fills], await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false), await rig.Learning.Models.PredictionsAsync(_none).ConfigureAwait(false), [.. rows], rig.Failures);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Text(IEnumerable<(string Symbol, string Side, decimal Quantity, DateTimeOffset At)> fills) => string.Join('\n', fills.Select(f => $"{f.Symbol} {f.Side} {f.Quantity} {f.At:MM-dd HH:mm}"));
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.5: until it counts, the model notes its estimates beside each operation and changes nothing.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(StrategyStages.Simulation)]
|
||||||
|
[DataRow(StrategyStages.Observation)]
|
||||||
|
public async Task InObservationItNotesItsEstimatesAndChangesNothing(string stage)
|
||||||
|
{
|
||||||
|
var without = await LiveAsync(null, active: false, stage: stage).ConfigureAwait(false);
|
||||||
|
var with = await LiveAsync(Always(0.1), active: false, Always(0.6), stage: stage).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(Text(without.Fills), Text(with.Fills));
|
||||||
|
Assert.IsGreaterThan(1, with.Examples.Count);
|
||||||
|
Assert.IsTrue(with.Examples.All(e => e.Multiplier == 1));
|
||||||
|
|
||||||
|
// Two estimates for each signal: the one in charge, with the multiplier it would apply, and the one on trial.
|
||||||
|
Assert.HasCount(2 * with.Examples.Count, with.Predictions);
|
||||||
|
Assert.IsTrue(with.Predictions.Where(p => p.InCharge).All(p => p is { Multiplier: 0, BaseRate: 0.4 } && Math.Abs(p.Probability - 0.1) < 1e-6));
|
||||||
|
Assert.IsTrue(with.Predictions.Where(p => !p.InCharge).All(p => p.Multiplier == 1));
|
||||||
|
Assert.HasCount(with.Examples.Count, with.Rows);
|
||||||
|
Assert.IsTrue(with.Rows.All(r => r.Outcome == DecisionOutcomes.Passed));
|
||||||
|
Assert.Contains("solo osservazione, non ha cambiato la dimensione", Anubis.Server.ReasonTexts.Model((string)with.Rows[0].Data!["json"]!)!);
|
||||||
|
Assert.HasCount(0, without.Predictions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>When it counts: nothing is ever bigger, exits are the same, the multiplier of birth holds for the increases.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task WhenItCountsItOnlyMakesOperationsSmaller()
|
||||||
|
{
|
||||||
|
var full = await LiveAsync(Always(0.4), active: true).ConfigureAwait(false);
|
||||||
|
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(Text(none.Fills), Text(full.Fills), "who always answers the base rate leaves everything as it is");
|
||||||
|
|
||||||
|
var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
|
||||||
|
Assert.IsTrue(half.Examples.All(e => Math.Abs(e.Multiplier - 0.5) < 1e-3));
|
||||||
|
Assert.IsTrue(half.Rows.All(r => r.Outcome == DecisionOutcomes.Reduced));
|
||||||
|
Assert.Contains("acquisto ridotto al 50%", Anubis.Server.ReasonTexts.Model((string)half.Rows[0].Data!["json"]!)!);
|
||||||
|
decimal Bought(Run run, string symbol) => run.Fills.Where(f => f.Symbol == symbol && f.Side == "buy").Sum(f => f.Quantity);
|
||||||
|
foreach (var symbol in full.Fills.Select(f => f.Symbol).Distinct())
|
||||||
|
{
|
||||||
|
// The first purchase is half, or more where the limits had already cut the whole one.
|
||||||
|
Assert.IsInRange(0.47, 1, (double)(half.Fills.First(f => f.Symbol == symbol).Quantity / full.Fills.First(f => f.Symbol == symbol).Quantity), symbol);
|
||||||
|
Assert.IsLessThanOrEqualTo(Bought(full, symbol), Bought(half, symbol), symbol);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(0.5, (double)(half.Fills[0].Quantity / full.Fills[0].Quantity), 0.01, "where no limit cuts");
|
||||||
|
|
||||||
|
// The full exits come on the same days.
|
||||||
|
string Exits(Run run) => string.Join(' ', run.Fills.Where(f => f.Side == "sell").Select(f => f.Symbol + DateOnly.FromDateTime(f.At.UtcDateTime)).Distinct().Order());
|
||||||
|
Assert.Contains(Exits(half), Exits(full), StringComparison.Ordinal);
|
||||||
|
|
||||||
|
var zero = await LiveAsync(Always(0.2), active: true).ConfigureAwait(false);
|
||||||
|
Assert.HasCount(0, zero.Fills);
|
||||||
|
Assert.AreEqual(string.Join(',', full.Examples.Select(e => e.Symbol + e.Day)), string.Join(',', zero.Examples.Select(e => e.Symbol + e.Day)), "the examples do not depend on the model");
|
||||||
|
Assert.IsTrue(zero.Rows.All(r => r.Outcome == DecisionOutcomes.Refused));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The multiplier is fixed at birth: a model that changes its mind, or is set aside, does not touch an operation already open.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheMultiplierIsFixedAtBirth()
|
||||||
|
{
|
||||||
|
async Task Swap(LiveRig rig, DateOnly day)
|
||||||
|
{
|
||||||
|
// After 10 days the model is set aside: new operations are whole again, the ones already born are not.
|
||||||
|
if (day == From.AddDays(10))
|
||||||
|
{
|
||||||
|
await StateAsync(rig.Rig.Db, rig.Rig.Clock, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow, Aside = AsideCodes.Precision }).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var half = await LiveAsync(Always(0.35), active: true).ConfigureAwait(false);
|
||||||
|
var swapped = await LiveAsync(Always(0.35), active: true, before: Swap).ConfigureAwait(false);
|
||||||
|
Assert.IsTrue(swapped.Examples.Any(e => e.Day >= From.AddDays(9)) && swapped.Fills.Count > 0 && swapped.Examples.Any(e => e.Day < From.AddDays(9)));
|
||||||
|
foreach (var example in swapped.Examples)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(example.Day < From.AddDays(9) ? 0.5 : 1, example.Multiplier, 1e-3, $"{example.Symbol} {example.Day}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The operations born halved trade exactly as if the model were still there, increases included.
|
||||||
|
foreach (var symbol in swapped.Examples.GroupBy(e => e.Symbol).Where(g => g.All(e => e.Day < From.AddDays(9))).Select(g => g.Key))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(Text(half.Fills.Where(f => f.Symbol == symbol)), Text(swapped.Fills.Where(f => f.Symbol == symbol)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Set aside by the user, or without a base rate for the strategy: multiplier 1, and without a base rate not even an estimate.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task WithoutABaseRateThereIsNoEstimate()
|
||||||
|
{
|
||||||
|
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
|
||||||
|
var run = await LiveAsync(Always(0.1), active: true, rates: new FirstModelFile()).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(Text(none.Fills), Text(run.Fills));
|
||||||
|
Assert.HasCount(0, run.Predictions);
|
||||||
|
Assert.IsTrue(run.Examples.All(e => e.Multiplier == 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A model that breaks never stops a decision: the strategy goes on as if there were none.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ABrokenModelNeverStopsADecision()
|
||||||
|
{
|
||||||
|
var none = await LiveAsync(null, active: false).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// A tree that points outside itself throws at every estimate.
|
||||||
|
var broken = Always(0.1) with
|
||||||
|
{
|
||||||
|
Learned = new Learned { Learner = LearnerNames.Boosting, Trees = new TreesBody(0, 1, false, [new Tree([0], [0.5], [7], [9], [true], [0])]) },
|
||||||
|
};
|
||||||
|
var run = await LiveAsync(broken, active: true).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(Text(none.Fills), Text(run.Fills));
|
||||||
|
Assert.AreEqual(0, run.Failures);
|
||||||
|
Assert.HasCount(0, run.Predictions);
|
||||||
|
Assert.HasCount(none.Examples.Count, run.Examples);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The filter on its own: never bigger, exits and decreases untouched, no chasing of the rounding.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheFilterNeverMakesAnOrderBigger() => Property.ForAll(
|
||||||
|
gen => (Target: gen.Bool() ? (decimal?)gen.Decimal(0m, 0.5m, 4) : null, Multiplier: gen.Pick([double.NaN, -3, 0, 0.2, 0.5, 0.99, 1, 1.7, 50, double.PositiveInfinity])),
|
||||||
|
x =>
|
||||||
|
{
|
||||||
|
var data = LearningCasesTests.Coins(300, 1);
|
||||||
|
var seen = new List<(Intent Before, Intent After)>();
|
||||||
|
var strategy = new Fixed(x.Target);
|
||||||
|
BacktestEngine.Run(strategy, data, new BacktestOptions
|
||||||
|
{
|
||||||
|
From = data.Sessions[250],
|
||||||
|
To = data.Sessions[256],
|
||||||
|
Correctives = [new Spy(i => seen.Add((i, i))), new ModelFilter((_, _) => x.Multiplier), new Spy(i => seen[^1] = (seen[^1].Before, i))],
|
||||||
|
});
|
||||||
|
foreach (var (before, after) in seen)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(after.TargetWeight is null || after.TargetWeight <= before.TargetWeight, $"{before.TargetWeight} -> {after.TargetWeight}");
|
||||||
|
if (before.TargetWeight is null or 0m || x.Multiplier >= 1 || double.IsNaN(x.Multiplier))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(before.TargetWeight, after.TargetWeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 60);
|
||||||
|
|
||||||
|
private sealed class Fixed(decimal? target) : IStrategy
|
||||||
|
{
|
||||||
|
public string Id => "fixed";
|
||||||
|
|
||||||
|
public string Version => "t";
|
||||||
|
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(StrategyContext context) => [new Intent("BTC-EUR", target, "x")];
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Spy(Action<Intent> seen) : IIntentStage
|
||||||
|
{
|
||||||
|
public string Name => "spy";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents)
|
||||||
|
{
|
||||||
|
foreach (var intent in intents)
|
||||||
|
{
|
||||||
|
seen(intent);
|
||||||
|
}
|
||||||
|
|
||||||
|
return intents;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The nightly cycle ------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>An archive with a model in charge, and what the cycle needs to run on it.</summary>
|
||||||
|
private sealed class Night : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private int _count;
|
||||||
|
|
||||||
|
public TradingRig Rig { get; private set; } = null!;
|
||||||
|
|
||||||
|
public LearningDesk Desk { get; private set; } = null!;
|
||||||
|
|
||||||
|
public LearningCycle Cycle { get; private set; } = null!;
|
||||||
|
|
||||||
|
public ModelRow Champion { get; private set; } = null!;
|
||||||
|
|
||||||
|
public static async Task<Night> CreateAsync()
|
||||||
|
{
|
||||||
|
var night = new Night { Rig = await TradingRig.CreateAsync().ConfigureAwait(false) };
|
||||||
|
night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero)); // A Wednesday, 03:00 in Rome.
|
||||||
|
night.Desk = new LearningDesk(night.Rig.Db, night.Rig.Clock) { First = Rates };
|
||||||
|
night.Cycle = new LearningCycle(night.Rig.Db, night.Rig.Clock, night.Desk, (_, _, _) => Task.FromResult<LabelData?>(null));
|
||||||
|
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { LastSunday = new DateOnly(2027, 2, 28) }).ConfigureAwait(false);
|
||||||
|
night.Champion = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
return night;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A closed signal with what each model said when it was born, the first one in charge.</summary>
|
||||||
|
public async Task CaseAsync(bool win, double result = 0.02, string stage = StrategyStages.Simulation, IReadOnlyDictionary<string, double>? features = null, params (ModelRow Model, double P)[] said)
|
||||||
|
{
|
||||||
|
var day = new DateOnly(2025, 1, 1).AddDays(_count++);
|
||||||
|
await Rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
var id = (await LearningStore.AddAsync(s, Rig.Clock, new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
|
||||||
|
"trend_entry", 0.2m, null, null, features ?? new Dictionary<string, double> { [Clues.Strength] = 0.5 })
|
||||||
|
{ Stage = stage, Label = new CaseLabel(win, win ? result : -result, day.AddDays(1), day.AddDays(1), "x") }, _none).ConfigureAwait(false))!.Value;
|
||||||
|
foreach (var (model, p) in said)
|
||||||
|
{
|
||||||
|
await ModelStore.AddPredictionAsync(s, Rig.Clock, new PredictionRow(id, model.Id, p, 0.4, MultiplierRule.Standard.Of(p, 0.4), model.Id == Champion.Id), _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string> RunAsync()
|
||||||
|
{
|
||||||
|
await Cycle.RunAsync(_none).ConfigureAwait(false);
|
||||||
|
return (await DiaryAsync().ConfigureAwait(false)).LastOrDefault() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ToSunday() => Rig.Clock.Set(new DateTimeOffset(2027, 3, 7, 2, 0, 0, TimeSpan.Zero));
|
||||||
|
|
||||||
|
public Task<List<string>> DiaryAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE kind = 'Apprendimento' ORDER BY occurred_at, id", r => r.Text("message")), _none);
|
||||||
|
|
||||||
|
public Task<List<string>> NotificationsAsync() => Rig.Db.ReadAsync(s => s.QueryAsync("SELECT kind FROM notifications ORDER BY created_at, id", r => r.Text("kind")), _none);
|
||||||
|
|
||||||
|
public async Task<string> StatusAsync(Guid id) => (await Desk.Models.AllAsync(_none).ConfigureAwait(false)).Single(m => m.Id == id).Status;
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync() => Rig.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.4, 5.6: one run labels what matured and says once that nothing is wrong.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheNightLabelsWhatMaturedAndSaysItOnce()
|
||||||
|
{
|
||||||
|
var last = From.AddDays(24);
|
||||||
|
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
|
||||||
|
rig.UseFirst(Rates);
|
||||||
|
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
for (var day = From; day <= last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
|
||||||
|
var open = (await rig.Learning.Store.OpenAsync(_none).ConfigureAwait(false)).Count;
|
||||||
|
await cycle.RunAsync(_none).ConfigureAwait(false);
|
||||||
|
await cycle.RunAsync(_none).ConfigureAwait(false);
|
||||||
|
var after = await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.IsGreaterThan(0, open - after.Count(e => e.Label is null));
|
||||||
|
|
||||||
|
// The labels are those of the history on the same bars.
|
||||||
|
var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR");
|
||||||
|
foreach (var example in after)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(CaseLabels.Of(example, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, last.AddDays(-1)), example.Label);
|
||||||
|
}
|
||||||
|
|
||||||
|
var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual("Controllo del modello: nessuna anomalia.", diary.Single());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 5.6: off for three nights, the job of the model runs once at the return, labels what matured meanwhile and says one line.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AfterThreeDaysOffLabelsAndCheckAreMadeOnce()
|
||||||
|
{
|
||||||
|
var off = From.AddDays(14);
|
||||||
|
var last = From.AddDays(24);
|
||||||
|
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
|
||||||
|
rig.UseFirst(Rates);
|
||||||
|
await AddModelAsync(rig.Rig.Db, rig.Rig.Clock, Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
for (var day = From; day <= off; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var cycle = new LearningCycle(rig.Rig.Db, rig.Rig.Clock, rig.Learning, rig.Engine.LabelDataAsync);
|
||||||
|
await cycle.RunAsync(_none).ConfigureAwait(false);
|
||||||
|
var labelled = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null);
|
||||||
|
var went = rig.Rig.Clock.UtcNow;
|
||||||
|
|
||||||
|
// Back on the fourth day, with the bars of the meantime already there: the real job of the engine, as it is registered.
|
||||||
|
for (var day = off; day < last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await rig.StoreBarAsync(day).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
rig.Rig.Clock.Set(new DateTimeOffset(last.ToDateTime(new TimeOnly(9, 0)), TimeSpan.Zero));
|
||||||
|
var runs = 0;
|
||||||
|
var scheduler = new Scheduler(rig.Rig.Clock, new EventBus());
|
||||||
|
scheduler.Add(TradingService.ModelJob(async ct =>
|
||||||
|
{
|
||||||
|
await cycle.RunAsync(ct).ConfigureAwait(false);
|
||||||
|
runs++;
|
||||||
|
}), went);
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 600 && runs == 0; i++)
|
||||||
|
{
|
||||||
|
await Task.Delay(50, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1, runs, "one run for all the missed nights");
|
||||||
|
var diary = await rig.Rig.QueryAsync("SELECT message FROM journal WHERE code = 'model_check'", r => r.Text("message")).ConfigureAwait(false);
|
||||||
|
Assert.HasCount(2, diary, "one line before and one at the return");
|
||||||
|
Assert.IsGreaterThan(labelled, (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).Count(e => e.Label is not null), "what matured meanwhile has its label");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The challenger replaces the one in charge only at a threshold and only when the advantage is not chance; one click takes it back.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AChallengerThatIsReallyBetterIsPromotedAtAThreshold()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
|
||||||
|
var gen = new Gen(3);
|
||||||
|
for (var i = 0; i < 99; i++)
|
||||||
|
{
|
||||||
|
var win = gen.Double() < 0.4;
|
||||||
|
await night.CaseAsync(win, said: [(night.Champion, 0.4), (challenger, win ? 0.6 : 0.25)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
night.ToSunday();
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "99 cases: no decision yet");
|
||||||
|
|
||||||
|
await night.CaseAsync(true, said: [(night.Champion, 0.4), (challenger, 0.6)]).ConfigureAwait(false);
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(3));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(ModelStatuses.Challenger, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "100 cases but not a Sunday");
|
||||||
|
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(4));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(ModelStatuses.Retired, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
|
||||||
|
CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_promoted");
|
||||||
|
|
||||||
|
Assert.IsTrue(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
|
||||||
|
Assert.IsFalse(await night.Cycle.UndoPromotionAsync(_none).ConfigureAwait(false), "only once");
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(ModelStatuses.Undone, await night.StatusAsync(challenger.Id).ConfigureAwait(false), "what the user took back does not come back");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An advantage that is chance never promotes; after 300 cases the challenger is discarded. Between thresholds nothing is decided.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
var challenger = await AddModelAsync(night.Rig.Db, night.Rig.Clock, Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
|
||||||
|
var gen = new Gen(8);
|
||||||
|
night.ToSunday();
|
||||||
|
for (var i = 0; i < 300; i++)
|
||||||
|
{
|
||||||
|
await night.CaseAsync(gen.Double() < 0.4, said: [(night.Champion, 0.4), (challenger, 0.4 + (gen.Double() * 0.1) - 0.05)]).ConfigureAwait(false);
|
||||||
|
if (i is 99 or 120 or 260)
|
||||||
|
{
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
var row = (await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false))!;
|
||||||
|
Assert.AreEqual(i switch { 99 or 120 => 100, _ => 250 }, row.ThresholdDone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(ModelStatuses.Discarded, await night.StatusAsync(challenger.Id).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(ModelStatuses.Champion, await night.StatusAsync(night.Champion.Id).ConfigureAwait(false));
|
||||||
|
Assert.IsTrue((await night.DiaryAsync().ConfigureAwait(false)).Any(d => d.StartsWith("Scartata la versione", StringComparison.Ordinal)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>On Sunday, without a challenger and with new outcomes, one is trained; a Sunday missed while off is done at the next run, once.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task OnSundayAChallengerIsTrainedOnce()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
await night.Rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
foreach (var example in LearningModelTests.Cases(300, x => Odds.Probability(x[1]), source: CaseSources.Live))
|
||||||
|
{
|
||||||
|
await LearningStore.AddAsync(s, night.Rig.Clock, example, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, _none).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNull(await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false), "a Wednesday");
|
||||||
|
|
||||||
|
// Off from Wednesday to the Tuesday after two Sundays: one training at the return.
|
||||||
|
night.Rig.Clock.Set(new DateTimeOffset(2027, 3, 16, 9, 0, 0, TimeSpan.Zero));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
var challenger = await night.Desk.Models.FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual((2, 300), (challenger!.Version, challenger.Examples));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
var all = await night.Desk.Models.AllAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.HasCount(4, all, "champion, challenger and its two attempts");
|
||||||
|
Assert.HasCount(1, all.Where(m => m.Status == ModelStatuses.Challenger));
|
||||||
|
|
||||||
|
// On trial it is never retrained, and without new outcomes the next one is not trained either.
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
await night.Rig.Db.WriteAsync(s => ModelStore.SetStatusAsync(s, night.Rig.Clock, challenger.Id, ModelStatuses.Discarded, _none), _none).ConfigureAwait(false);
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(7));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.HasCount(4, await night.Desk.Models.AllAsync(_none).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Precision under 50% on at least 40 cases: set aside, said once, until it comes back.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 39; i++)
|
||||||
|
{
|
||||||
|
// Always wrong: what it says is likely loses.
|
||||||
|
await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.35 : 0.42)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
|
||||||
|
await night.CaseAsync(false, said: [(night.Champion, 0.42)]).ConfigureAwait(false);
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
Assert.Contains("lo metto da parte", (await night.RunAsync().ConfigureAwait(false)).ToLowerInvariant());
|
||||||
|
Assert.AreEqual(AsideCodes.Precision, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
Assert.Contains("resta da parte", await night.RunAsync().ConfigureAwait(false));
|
||||||
|
for (var i = 0; i < 60; i++)
|
||||||
|
{
|
||||||
|
await night.CaseAsync(i % 5 < 2, said: [(night.Champion, i % 5 < 2 ? 0.45 : 0.35)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
Assert.Contains("rientrata dopo 2 giorni", await night.RunAsync().ConfigureAwait(false));
|
||||||
|
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
|
||||||
|
CollectionAssert.AreEqual(new[] { "model_set_aside", "model_back" }, await night.NotificationsAsync().ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>While it is set aside, by itself or by the user, the gate lets everything through.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task SetAsideMeansMultiplierOne()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
var settings = new SettingsStore(night.Rig.Db, night.Rig.Clock, new EventBus());
|
||||||
|
var desk = new LearningDesk(night.Rig.Db, night.Rig.Clock, settings) { First = Rates };
|
||||||
|
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "in observation");
|
||||||
|
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow }).ConfigureAwait(false);
|
||||||
|
Assert.IsTrue((await desk.GateAsync(_none).ConfigureAwait(false)).Counts);
|
||||||
|
await settings.SetAsync(LearningSettings.Aside.Key, "on", "test", _none).ConfigureAwait(false);
|
||||||
|
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by the user");
|
||||||
|
await settings.SetAsync(LearningSettings.Aside.Key, "off", "test", _none).ConfigureAwait(false);
|
||||||
|
await settings.SetAsync(LearningSettings.Zero.Key, "20", "test", _none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(new MultiplierRule(0, 0.20), (await desk.GateAsync(_none).ConfigureAwait(false)).Rule);
|
||||||
|
await StateAsync(night.Rig.Db, night.Rig.Clock, new CycleState { ActivatedAt = night.Rig.Clock.UtcNow, Aside = AsideCodes.ClueDrift }).ConfigureAwait(false);
|
||||||
|
Assert.IsFalse((await desk.GateAsync(_none).ConfigureAwait(false)).Counts, "by itself");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The error rises: ADWIN sees it and the model is set aside.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ARisingErrorSetsTheModelAside()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 120; i++)
|
||||||
|
{
|
||||||
|
var win = i % 5 < 2;
|
||||||
|
await night.CaseAsync(win, said: [(night.Champion, win ? 0.95 : 0.05)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false));
|
||||||
|
for (var i = 0; i < 24; i++)
|
||||||
|
{
|
||||||
|
// Still more right than wrong on the last 60, but suddenly much worse.
|
||||||
|
var win = i % 5 < 2;
|
||||||
|
await night.CaseAsync(win, said: [(night.Champion, win ? 0.1 : 0.9)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(AsideCodes.ErrorDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The clues leave what the model studied: set aside, naming them. The clues not in use do not count.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task CluesNeverStudiedSetTheModelAside()
|
||||||
|
{
|
||||||
|
await using var night = await Night.CreateAsync().ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 60; i++)
|
||||||
|
{
|
||||||
|
await night.CaseAsync(i % 5 < 2, features: new Dictionary<string, double> { [Clues.Strength] = i < 48 ? 0.5 : 3, [Clues.Vix] = 900 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("Controllo del modello: nessuna anomalia.", await night.RunAsync().ConfigureAwait(false), "a fifth is not more than a fifth");
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
await night.CaseAsync(false, features: new Dictionary<string, double> { [Clues.Strength] = 3 }, said: [(night.Champion, 0.4)]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
night.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
Assert.Contains("forza della tendenza", await night.RunAsync().ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(AsideCodes.ClueDrift, (await night.Desk.CycleAsync(_none).ConfigureAwait(false)).Aside);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.5: it starts to count with 300 signals, good calibration and a gain that is not chance, and only all three.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task ItStartsToCountOnlyWithAllThreeCriteria()
|
||||||
|
{
|
||||||
|
// 40% of wins: 48% among those estimated 0.48, 28% among those estimated 0.28.
|
||||||
|
async Task Fill(Night night, int count, Func<int, double> said, string stage = StrategyStages.Simulation)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var high = i % 5 < 3;
|
||||||
|
var win = high ? i % 25 is 0 or 1 or 5 or 6 or 10 or 11 or 15 : i % 25 is 3 or 8 or 13;
|
||||||
|
await night.CaseAsync(win, stage: stage, said: [(night.Champion, said(i))]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static double Calibrated(int i) => i % 5 < 3 ? 0.47 : 0.30;
|
||||||
|
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await Fill(night, 299, Calibrated).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "299 signals");
|
||||||
|
await Fill(night, 1, Calibrated).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNotNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt);
|
||||||
|
CollectionAssert.Contains(await night.NotificationsAsync().ConfigureAwait(false), "model_activated");
|
||||||
|
}
|
||||||
|
|
||||||
|
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await Fill(night, 320, i => i % 5 < 3 ? 0.75 : 0.15).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "badly calibrated");
|
||||||
|
}
|
||||||
|
|
||||||
|
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await Fill(night, 320, _ => 0.41).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no improvement");
|
||||||
|
}
|
||||||
|
|
||||||
|
await using (var night = await Night.CreateAsync().ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await Fill(night, 320, Calibrated, StrategyStages.Observation).ConfigureAwait(false);
|
||||||
|
await night.RunAsync().ConfigureAwait(false);
|
||||||
|
Assert.IsNull((await night.Desk.CycleAsync(_none).ConfigureAwait(false)).ActivatedAt, "no signal of a strategy with capital");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>ADWIN on known cases: a jump is seen, its direction too, noise alone is not.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AdwinSeesAJumpAndNotTheNoise()
|
||||||
|
{
|
||||||
|
var alarms = 0;
|
||||||
|
for (var seed = 0; seed < 50; seed++)
|
||||||
|
{
|
||||||
|
var gen = new Gen(seed);
|
||||||
|
var adwin = new Adwin();
|
||||||
|
alarms += Enumerable.Range(0, 400).Any(_ => adwin.Add(gen.Double()) != 0) ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsLessThanOrEqualTo(2, alarms, "false alarms on noise");
|
||||||
|
var up = new Adwin();
|
||||||
|
var random = new Gen(1);
|
||||||
|
var found = Enumerable.Range(0, 200).Select(i => (i, Change: up.Add((i < 100 ? 0.2 : 0.6) + (random.Double() * 0.2)))).First(x => x.Change != 0);
|
||||||
|
Assert.AreEqual(1, found.Change);
|
||||||
|
Assert.IsTrue(found.i is >= 100 and < 140, $"{found.i}");
|
||||||
|
Assert.IsLessThan(40, up.Count - (200 - found.i - 1), "the older part is dropped");
|
||||||
|
var down = new Adwin();
|
||||||
|
Assert.AreEqual(-1, Enumerable.Range(0, 200).Select(i => down.Add(i < 100 ? 0.8 : 0.2)).First(c => c != 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,459 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The learners, their calibration, the purged validation and the choice (SPEC 11.1, 11.3; issue #63).</summary>
|
||||||
|
[TestClass]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public sealed class LearningModelTests
|
||||||
|
{
|
||||||
|
private static readonly DateOnly First = new(2020, 1, 1);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Examples whose outcome depends on what <paramref name="chance"/> says of the clues. Wins pay 2%, losses cost 2%:
|
||||||
|
/// a filter that avoids likely losses earns.
|
||||||
|
/// </summary>
|
||||||
|
internal static IReadOnlyList<Example> Cases(int count, Func<double[], double> chance, int seed = 5, string strategy = StrategyNames.CryptoTrend, int length = 8, string source = CaseSources.History)
|
||||||
|
{
|
||||||
|
var gen = new Gen(seed);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count).Select(i =>
|
||||||
|
{
|
||||||
|
var clues = new[] { gen.Double(), gen.Normal(), gen.Double(), gen.Normal() };
|
||||||
|
var win = gen.Double() < chance(clues);
|
||||||
|
var day = First.AddDays(i * 2);
|
||||||
|
var result = win ? 0.02 : -0.02;
|
||||||
|
return new Example(Guid.NewGuid(), strategy, "C" + (i % 7), source, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "test", 0.2m, null, null,
|
||||||
|
new Dictionary<string, double>
|
||||||
|
{
|
||||||
|
[Clues.Strength] = clues[0],
|
||||||
|
[Clues.Volatility] = clues[1],
|
||||||
|
[Clues.Volume] = clues[2],
|
||||||
|
[Clues.MarketTrend] = clues[3],
|
||||||
|
})
|
||||||
|
{
|
||||||
|
Label = new CaseLabel(win, result, day, day.AddDays(1 + (i % length)), "exit"),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<double[]> Rows(IEnumerable<Example> cases) => [.. cases.Select(c => Trainer.Row([Clues.Strength, Clues.Volatility, Clues.Volume, Clues.MarketTrend], c.Features))];
|
||||||
|
|
||||||
|
private static List<bool> Wins(IEnumerable<Example> cases) => [.. cases.Select(c => c.Label!.Win == true)];
|
||||||
|
|
||||||
|
private static double Loss(Learned model, IReadOnlyList<Example> cases) =>
|
||||||
|
cases.Average(c => Judge.LogLoss(c.Label!.Win == true, Odds.Probability(model.Score(Rows([c])[0]))));
|
||||||
|
|
||||||
|
/// <summary>Each learner finds a relation that is there: on new examples it is clearly better than the plain share of wins.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(LearnerNames.Logistic)]
|
||||||
|
[DataRow(LearnerNames.Boosting)]
|
||||||
|
[DataRow(LearnerNames.Forest)]
|
||||||
|
public void ALearnerFindsWhatIsThere(string learner)
|
||||||
|
{
|
||||||
|
static double Chance(double[] x) => Odds.Probability((4 * x[0]) - 2);
|
||||||
|
var train = Cases(1200, Chance, 5);
|
||||||
|
var fresh = Cases(1200, Chance, 6);
|
||||||
|
var model = Learners.Fit(learner, Rows(train), Wins(train), 1);
|
||||||
|
var share = Wins(train).Count(w => w) / 1200.0;
|
||||||
|
var plain = fresh.Average(c => Judge.LogLoss(c.Label!.Win == true, share));
|
||||||
|
Assert.IsLessThan(plain - 0.03, Loss(model, fresh));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The trees find what a straight line cannot: an exclusive or.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheTreesFindWhatALineCannot()
|
||||||
|
{
|
||||||
|
static double Chance(double[] x) => (x[0] > 0.5) == (x[2] > 0.5) ? 0.85 : 0.15;
|
||||||
|
var train = Cases(1500, Chance, 5);
|
||||||
|
var fresh = Cases(1500, Chance, 6);
|
||||||
|
var line = Loss(Learners.Fit(LearnerNames.Logistic, Rows(train), Wins(train), 1), fresh);
|
||||||
|
var trees = Loss(Learners.Fit(LearnerNames.Boosting, Rows(train), Wins(train), 1), fresh);
|
||||||
|
Assert.IsGreaterThan(0.65, line);
|
||||||
|
Assert.IsLessThan(0.55, trees);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Same data and seed, same model, to the last digit; and it survives the database as it was.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(LearnerNames.Logistic)]
|
||||||
|
[DataRow(LearnerNames.Boosting)]
|
||||||
|
[DataRow(LearnerNames.Forest)]
|
||||||
|
public void TheSameDataGiveTheSameModel(string learner)
|
||||||
|
{
|
||||||
|
var cases = Cases(300, x => Odds.Probability(x[1]));
|
||||||
|
var clues = Trainer.CluesOf(cases);
|
||||||
|
var one = Trainer.Fit(learner, cases, clues, 3);
|
||||||
|
var two = Trainer.Fit(learner, cases, clues, 3);
|
||||||
|
Assert.AreEqual(JsonSerializer.Serialize(one), JsonSerializer.Serialize(two));
|
||||||
|
var back = JsonSerializer.Deserialize<TrainedModel>(JsonSerializer.Serialize(one))!;
|
||||||
|
foreach (var c in cases)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(one.Probability(c.Features), back.Probability(c.Features));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A missing clue is no trouble, neither to learn nor to estimate, and tells what it tells.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(LearnerNames.Logistic)]
|
||||||
|
[DataRow(LearnerNames.Boosting)]
|
||||||
|
[DataRow(LearnerNames.Forest)]
|
||||||
|
public void AMissingClueIsNoTrouble(string learner)
|
||||||
|
{
|
||||||
|
var cases = Cases(600, x => Odds.Probability((4 * x[0]) - 2)).Select((c, i) => i % 3 > 0 ? c
|
||||||
|
: c with { Features = c.Features.Where(f => f.Key != Clues.Strength).ToDictionary(f => f.Key, f => f.Value) }).ToList();
|
||||||
|
var model = Trainer.Fit(learner, cases, Trainer.CluesOf(cases), 3);
|
||||||
|
foreach (var features in new[] { new Dictionary<string, double>(), new Dictionary<string, double> { [Clues.Strength] = double.NaN }, new Dictionary<string, double> { [Clues.Strength] = 1e9, [Clues.Volatility] = -1e9 } })
|
||||||
|
{
|
||||||
|
var p = model.Probability(features);
|
||||||
|
Assert.IsTrue(p is > 0 and < 1, $"{p}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Trees keep many examples in every leaf.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryLeafHasManyExamples()
|
||||||
|
{
|
||||||
|
var cases = Cases(800, x => Odds.Probability(x[1]));
|
||||||
|
var rows = Rows(cases);
|
||||||
|
Assert.AreEqual(40, Learners.MinLeaf(800));
|
||||||
|
foreach (var tree in Learners.Fit(LearnerNames.Boosting, rows, Wins(cases), 1).Trees!.Trees)
|
||||||
|
{
|
||||||
|
Assert.IsLessThanOrEqualTo(15, tree.Feature.Count, "no more than three levels");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PlattBringsScoresBackToTheTruth()
|
||||||
|
{
|
||||||
|
// The scores are three times too sure: the calibration must bring them back.
|
||||||
|
var gen = new Gen(9);
|
||||||
|
var scores = Enumerable.Range(0, 900).Select(_ => gen.Normal() * 3).ToList();
|
||||||
|
var wins = scores.Select(s => gen.Double() < Odds.Probability(s / 3)).ToList();
|
||||||
|
var fitted = Calibration.Fit(scores, wins);
|
||||||
|
Assert.AreEqual(Calibration.PlattKind, fitted.Kind);
|
||||||
|
Assert.AreEqual(1.0 / 3, fitted.Slope, 0.07);
|
||||||
|
|
||||||
|
// Scores that say the opposite, or nothing, become the plain share of wins.
|
||||||
|
var upside = Calibration.Fit(scores, [.. wins.Select(w => !w)]);
|
||||||
|
Assert.AreEqual(0, upside.Slope);
|
||||||
|
Assert.AreEqual((double)wins.Count(w => !w) / wins.Count, upside.Probability(5), 0.01);
|
||||||
|
Assert.AreEqual(0, Calibration.Platt([1, 1, 1, 1], [true, false, true, true]).Slope);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Isotonic on a known case: the classic pools, never down, never 0 or 1.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void IsotonicNeverGoesDown()
|
||||||
|
{
|
||||||
|
var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true], 1);
|
||||||
|
Assert.AreEqual(0.5, known.Probability(2.5), 1e-9);
|
||||||
|
var gen = new Gen(4);
|
||||||
|
var scores = Enumerable.Range(0, 1500).Select(_ => gen.Normal()).ToList();
|
||||||
|
var wins = scores.Select(s => gen.Double() < Odds.Probability(2 * s)).ToList();
|
||||||
|
var fitted = Calibration.Fit(scores, wins);
|
||||||
|
Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind);
|
||||||
|
var last = 0.0;
|
||||||
|
for (var s = -6.0; s <= 6; s += 0.01)
|
||||||
|
{
|
||||||
|
var p = fitted.Probability(s);
|
||||||
|
Assert.IsTrue(p >= last && p is > 0 and < 1, $"{s}: {p} after {last}");
|
||||||
|
last = p;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(Odds.Probability(1), fitted.Probability(0.5), 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Validation -------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>No training example overlaps a test one in time, nor starts in the embargo after it; going forward, all is over before.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TrainingAndTestNeverOverlap() => Property.ForAll(
|
||||||
|
gen =>
|
||||||
|
{
|
||||||
|
var at = First;
|
||||||
|
return Enumerable.Range(0, gen.Int(20, 80)).Select(i =>
|
||||||
|
{
|
||||||
|
at = at.AddDays(gen.Int(0, 6));
|
||||||
|
return Cases(1, _ => 0.5)[0] with { Day = at, Symbol = "S" + i, Label = new CaseLabel(gen.Bool(), 0.01, at, at.AddDays(gen.Int(0, 90)), "x") };
|
||||||
|
}).ToList();
|
||||||
|
},
|
||||||
|
cases =>
|
||||||
|
{
|
||||||
|
var splits = CaseSplits.Combinatorial(cases);
|
||||||
|
Assert.HasCount(15, splits);
|
||||||
|
foreach (var split in splits.Concat(CaseSplits.Folds(cases)))
|
||||||
|
{
|
||||||
|
foreach (var train in split.Train.Select(i => cases[i]))
|
||||||
|
{
|
||||||
|
foreach (var test in split.Test.Select(i => cases[i]))
|
||||||
|
{
|
||||||
|
Assert.IsTrue(train.Label!.ClosedDay < test.Day || train.Day > test.Label!.ClosedDay!.Value.AddDays(CaseSplits.Embargo), $"{train.Day}..{train.Label.ClosedDay} / {test.Day}..{test.Label!.ClosedDay}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each example is verified by as many splits as it should be: 5 of the 15.
|
||||||
|
Assert.IsTrue(splits.SelectMany(s => s.Test).GroupBy(i => i).All(g => g.Count() == 5));
|
||||||
|
foreach (var split in CaseSplits.Forward(cases))
|
||||||
|
{
|
||||||
|
var begins = split.Test.Min(i => cases[i].Day);
|
||||||
|
Assert.IsTrue(split.Train.All(i => cases[i].Label!.ClosedDay < begins));
|
||||||
|
}
|
||||||
|
}, 40);
|
||||||
|
|
||||||
|
/// <summary>Known case: ten examples a month apart, each 40 days long.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void ThePurgeOnAKnownCase()
|
||||||
|
{
|
||||||
|
var cases = Enumerable.Range(0, 6).Select(i =>
|
||||||
|
{
|
||||||
|
var day = First.AddDays(i * 30);
|
||||||
|
return Cases(1, _ => 0.5)[0] with { Day = day, Symbol = "S" + i, Label = new CaseLabel(true, 0.01, day, day.AddDays(40), "x") };
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
// Groups of one example. Testing on example 2 (day 60 to 100, embargo to 110): 1 ends on day 70 and 3 starts on 90, so both go; 0 ends on day 40, 4 starts on 120.
|
||||||
|
var split = CaseSplits.Folds(cases, 6)[2];
|
||||||
|
CollectionAssert.AreEqual(new[] { 0, 4, 5 }, split.Train.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Measures ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static Estimate Of(bool win, double probability, double rate = 0.4, double multiplier = 1, double result = 0.02, string strategy = StrategyNames.CryptoTrend) =>
|
||||||
|
new(Cases(1, _ => 0.5, strategy: strategy)[0] with { Label = new CaseLabel(win, win ? result : -result, First, First, "x") }, probability, rate, multiplier);
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, double> Capital = new() { [StrategyNames.CryptoTrend] = 1000, [StrategyNames.EquityMomentum] = 1000 };
|
||||||
|
|
||||||
|
/// <summary>Who always says the same stays at 50%, whatever the share of wins.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void AlwaysTheSameAnswerIsFiftyPercent()
|
||||||
|
{
|
||||||
|
foreach (var answer in new[] { 0.1, 0.4, 0.9 })
|
||||||
|
{
|
||||||
|
Assert.AreEqual(0.5, Judge.Precision([.. Enumerable.Range(0, 100).Select(i => Of(i < 37, answer))]));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(1.0, Judge.Precision([Of(true, 0.6), Of(false, 0.2), Of(false, 0.1)]));
|
||||||
|
Assert.IsNull(Judge.Precision([Of(true, 0.6)]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The gain is divided by the proposed operations, not by those left: discarding nearly all cannot look good.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void AModelThatDiscardsNearlyAllDoesNotLookBetter()
|
||||||
|
{
|
||||||
|
// 50 wins of 4 euro, 50 losses of 2: keeping a single win earns 4 a piece on what is left, but 0.04 per proposal.
|
||||||
|
var all = Enumerable.Range(0, 100).Select(i => Of(i < 50, 0.4, result: i < 50 ? 0.02 : 0.01)).ToList();
|
||||||
|
var picky = all.Select((e, i) => e with { Multiplier = i == 0 ? 1 : 0 }).ToList();
|
||||||
|
Assert.AreEqual(1.0, Judge.Score(all, Capital).GainWith, 1e-9);
|
||||||
|
Assert.AreEqual(0.04, Judge.Score(picky, Capital).GainWith, 1e-9);
|
||||||
|
Assert.IsLessThan(0, Judge.Score(picky, Capital).Improvement);
|
||||||
|
|
||||||
|
// Zeroing the signals of a strategy without capital is no merit.
|
||||||
|
var other = Enumerable.Range(0, 100).Select(_ => Of(false, 0.1, multiplier: 0, strategy: StrategyNames.EquityMomentum));
|
||||||
|
Assert.AreEqual(0, Judge.Score([.. all, .. other], Capital, e => e.Strategy == StrategyNames.CryptoTrend).Improvement, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Losses mature first (SPEC 11.4): the weights give back the proportion of the base rate.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheWeightsGiveBackTheProportionOfTheBaseRate()
|
||||||
|
{
|
||||||
|
var estimates = Enumerable.Range(0, 100).Select(i => Of(i < 20, 0.4)).ToList();
|
||||||
|
var weighed = Judge.Weigh(estimates, new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 });
|
||||||
|
Assert.AreEqual(0.4, weighed.Where(e => e.Win).Sum(e => e.Weight) / weighed.Sum(e => e.Weight), 1e-9);
|
||||||
|
Assert.AreEqual(100, weighed.Sum(e => e.Weight), 1e-9);
|
||||||
|
Assert.IsTrue(Judge.Weigh([.. estimates.Where(e => e.Win)], new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 }).All(e => e.Weight == 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheCalibrationErrorCountsOnlyBandsWithEnoughCases()
|
||||||
|
{
|
||||||
|
// 20 cases at 42% with 8 wins (40%), 19 cases at 80% all lost: only the first band counts.
|
||||||
|
var estimates = Enumerable.Range(0, 20).Select(i => Of(i < 8, 0.42)).Concat(Enumerable.Range(0, 19).Select(_ => Of(false, 0.8))).ToList();
|
||||||
|
var scores = Judge.Score(estimates, Capital);
|
||||||
|
Assert.AreEqual(0.02, scores.CalibrationError!.Value, 1e-9);
|
||||||
|
Assert.HasCount(2, scores.Bands);
|
||||||
|
Assert.IsNull(Judge.Score([.. estimates.Take(19)], Capital).CalibrationError);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The interval contains the truth and knows that neighbours are not independent.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheIntervalKeepsNeighboursTogether()
|
||||||
|
{
|
||||||
|
var gen = new Gen(3);
|
||||||
|
var alone = Enumerable.Range(0, 400).Select(_ => gen.Normal() + 0.05).ToList();
|
||||||
|
var ones = alone.Select(_ => 1.0).ToList();
|
||||||
|
var (low, high) = Judge.Interval(alone, ones, 0.95);
|
||||||
|
Assert.IsTrue(low < 0.05 && high > 0.05 && high - low is > 0.1 and < 0.3, $"{low} {high}");
|
||||||
|
var twins = alone.SelectMany(v => Enumerable.Repeat(v, 10)).Take(400).ToList();
|
||||||
|
var (from, to) = Judge.Interval(twins, ones, 0.95);
|
||||||
|
Assert.IsGreaterThan(1.8 * (high - low), to - from);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Multiplier -------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Criterion of the phase: whatever the numbers and the thresholds, the multiplier is between 0 and 1.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheMultiplierNeverExceedsOne()
|
||||||
|
{
|
||||||
|
double[] odd = [double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1, 0, 1, 2, 1e300, -1e300];
|
||||||
|
Property.ForAll(
|
||||||
|
gen => (P: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(), B: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(),
|
||||||
|
Rule: new MultiplierRule(gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.2, gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.4)),
|
||||||
|
x =>
|
||||||
|
{
|
||||||
|
var m = x.Rule.Of(x.P, x.B);
|
||||||
|
Assert.IsTrue(m is >= 0 and <= 1, $"{m}");
|
||||||
|
Assert.IsGreaterThanOrEqualTo(x.Rule.Of(x.P - 0.01, x.B) - 1e-4, m, "a better estimate never shrinks more");
|
||||||
|
}, 5000);
|
||||||
|
Assert.AreEqual(1, MultiplierRule.Standard.Of(0.42, 0.42));
|
||||||
|
Assert.AreEqual(1, MultiplierRule.Standard.Of(0.9, 0.42));
|
||||||
|
Assert.AreEqual(0.5, MultiplierRule.Standard.Of(0.37, 0.42), 1e-4);
|
||||||
|
Assert.AreEqual(0, MultiplierRule.Standard.Of(0.32, 0.42));
|
||||||
|
Assert.AreEqual(0, MultiplierRule.Standard.Of(0.01, 0.42));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Training ---------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
internal static TrainingInput Input(IReadOnlyList<Example> cases) => new(cases)
|
||||||
|
{
|
||||||
|
BaseRates = Trainer.SharesOf(cases),
|
||||||
|
Capital = Capital,
|
||||||
|
Funded = new HashSet<string> { StrategyNames.CryptoTrend },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>With something to learn the model earns on examples it had not studied, and it says what it looks at.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TrainingFindsTheClueThatCounts()
|
||||||
|
{
|
||||||
|
var cases = Cases(500, x => x[0] > 0.5 ? 0.75 : 0.25);
|
||||||
|
var result = Trainer.Train(Input(cases))!;
|
||||||
|
Assert.IsNotNull(result);
|
||||||
|
var chosen = result.Report.Chosen!;
|
||||||
|
Assert.IsGreaterThan(0.2, chosen.Combined.Improvement);
|
||||||
|
Assert.IsGreaterThan(0.2, chosen.Forward.Improvement);
|
||||||
|
Assert.IsLessThan(chosen.Combined.BaseLogLoss - 0.05, chosen.Combined.LogLoss);
|
||||||
|
Assert.IsGreaterThan(0.65, chosen.Combined.Precision!.Value);
|
||||||
|
Assert.AreEqual("Forza della tendenza", result.Report.Weights[0].Group);
|
||||||
|
Assert.IsGreaterThan(80m, result.Report.Weights[0].Share);
|
||||||
|
Assert.AreEqual(100m, result.Report.Weights.Sum(w => w.Share));
|
||||||
|
|
||||||
|
// Every attempt is in the report, with the same number of verified cases.
|
||||||
|
CollectionAssert.AreEquivalent(LearnerNames.All.ToArray(), result.Report.Attempts.Select(a => a.Learner).ToArray());
|
||||||
|
Assert.HasCount(1, result.Report.Attempts.Where(a => a.Chosen));
|
||||||
|
Assert.HasCount(1, result.Report.Attempts.Select(a => a.Combined.Cases).Distinct());
|
||||||
|
Assert.IsFalse(result.Report.AllStrategiesCounted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>With nothing to learn it answers about the base rate: it does not invent a gain nor lose much.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void WithNothingToLearnItChangesLittle()
|
||||||
|
{
|
||||||
|
var result = Trainer.Train(Input(Cases(500, _ => 0.42)))!;
|
||||||
|
var chosen = result.Report.Chosen!;
|
||||||
|
Assert.AreEqual(chosen.Combined.BaseLogLoss, chosen.Combined.LogLoss, 0.02);
|
||||||
|
Assert.AreEqual(0.5, chosen.Combined.Precision!.Value, 0.07);
|
||||||
|
foreach (var example in Cases(100, _ => 0.42, 77))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(0.42, result.Model.Probability(example.Features), 0.12);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TooFewExamplesOrOneOutcomeTrainNothing()
|
||||||
|
{
|
||||||
|
Assert.IsNull(Trainer.Train(Input(Cases(99, _ => 0.5))));
|
||||||
|
Assert.IsNull(Trainer.Train(Input(Cases(300, _ => 2))));
|
||||||
|
var open = Cases(300, _ => 0.5).Select((c, i) => i < 99 ? c : c with { Label = i % 2 == 0 ? null : new CaseLabel(null, null, null, c.Day, CaseOutcomes.NeverStarted) }).ToList();
|
||||||
|
Assert.IsNull(Trainer.Train(Input(open)), "an example without outcome never trains");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.2: a clue without history waits for 200 live examples that contain it.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void AClueWithoutHistoryWaitsForTwoHundredLiveExamples()
|
||||||
|
{
|
||||||
|
var history = Cases(300, _ => 0.5);
|
||||||
|
IReadOnlyList<Example> With(int live, string source) =>
|
||||||
|
[
|
||||||
|
.. history, .. Cases(live, _ => 0.5, 8, source: source).Select((c, i) => c with { Features = new Dictionary<string, double>(c.Features) { [Clues.FearGreed] = i } }),
|
||||||
|
];
|
||||||
|
Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(199, CaseSources.Live)));
|
||||||
|
Assert.Contains(Clues.FearGreed, Trainer.CluesOf(With(200, CaseSources.Live)));
|
||||||
|
Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(400, CaseSources.History)));
|
||||||
|
Assert.DoesNotContain(Clues.Breadth, Trainer.CluesOf(history), "never seen");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The first model ----------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file in the program is whole: its base rates are the shares of its examples, its report counts them, and
|
||||||
|
/// training again on them gives the same estimates (to the sixth digit: the platforms differ in the last ones).
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheFirstModelIsTheOneOfItsExamples()
|
||||||
|
{
|
||||||
|
var file = FirstModel.Embedded!;
|
||||||
|
Assert.IsNotNull(file);
|
||||||
|
var labelled = file.Examples.Where(e => e.IsLabelled).ToList();
|
||||||
|
Assert.IsGreaterThan(1000, labelled.Count);
|
||||||
|
Assert.AreEqual(labelled.Count, file.Report!.Examples);
|
||||||
|
foreach (var (strategy, rate) in Trainer.SharesOf(file.Examples))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(rate, file.BaseRates[strategy], 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(file.Examples.All(e => e.Source == CaseSources.History && e.Day <= file.Through && (e.Label?.ClosedDay is not { } closed || closed <= file.Through)));
|
||||||
|
Assert.HasCount(3, file.Report.Attempts);
|
||||||
|
var again = Trainer.Fit(file.Model!.Learned.Learner, [.. labelled.OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal)], file.Model.Clues, 11);
|
||||||
|
foreach (var e in labelled)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(file.Model.Probability(e.Features), again.Probability(e.Features), 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Contains("parte in osservazione", FirstModel.Markdown(file, "x"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>At the first start the examples and the model are there, once; a new file replaces the examples and not the model.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheFirstModelTakesChargeAtTheFirstStart()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var none = CancellationToken.None;
|
||||||
|
var file = FirstModel.Train(Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), none);
|
||||||
|
var desk = new LearningDesk(rig.Db, rig.Clock) { First = file };
|
||||||
|
await desk.PrepareHistoryAsync(none).ConfigureAwait(false);
|
||||||
|
await desk.PrepareHistoryAsync(none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(300, await desk.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false));
|
||||||
|
var models = await desk.Models.AllAsync(none).ConfigureAwait(false);
|
||||||
|
Assert.HasCount(3, models, "the chosen one and the two attempts");
|
||||||
|
var champion = models.Single(m => m.Status == ModelStatuses.Champion);
|
||||||
|
Assert.AreEqual((1, 300), (champion.Version, champion.Examples));
|
||||||
|
Assert.IsTrue(models.Where(m => m.Id != champion.Id).All(m => m is { Status: ModelStatuses.Tried, Version: null, Model: null } && m.Report.Attempts.Count == 1));
|
||||||
|
foreach (var e in file.Examples)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(file.Model!.Probability(e.Features), champion.Model!.Probability(e.Features));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.HasCount(1, await desk.Models.EventsAsync(none).ConfigureAwait(false));
|
||||||
|
var later = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), none) };
|
||||||
|
await later.PrepareHistoryAsync(none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(320, await later.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(champion.Id, (await later.Models.FindAsync(ModelStatuses.Champion, none).ConfigureAwait(false))!.Id);
|
||||||
|
Assert.HasCount(1, await later.Models.EventsAsync(none).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rule of the choice, fixed before the numbers.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public void TheChoiceFollowsTheRule()
|
||||||
|
{
|
||||||
|
static Attempt A(string learner, double gain, double loss) => new(learner, new Scores(), new Scores { GainWith = gain, LogLoss = loss }, false);
|
||||||
|
string Chosen(params Attempt[] attempts) => Trainer.Choose(attempts).Learner;
|
||||||
|
Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.66)));
|
||||||
|
Assert.AreEqual(LearnerNames.Forest, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.64)));
|
||||||
|
Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 1, 0.60), A(LearnerNames.Logistic, 2, 0.65), A(LearnerNames.Forest, 1, 0.5)));
|
||||||
|
Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 0, 0.66), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.5)));
|
||||||
|
Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 0, 0.65), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.65)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The simpler things the bot learns: slippage, what news does to prices, discoveries in plain words (SPEC 11.6; issue #65).</summary>
|
||||||
|
[TestClass]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public sealed class LearningMoreTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
|
||||||
|
private static List<PaidFill> Fills(string tier, int count, double mean, bool real, int seed = 1)
|
||||||
|
{
|
||||||
|
var gen = new Gen(seed);
|
||||||
|
return [.. Enumerable.Range(0, count).Select(i => new PaidFill(tier, mean + gen.Normal(), real, TradingRig.Start.AddHours(i)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A rise from any broker account, a fall only from real money, nothing from few cases or from noise.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheRegressionRisesByItselfAndFallsOnlyOnRealMoney()
|
||||||
|
{
|
||||||
|
var table = SlippageTable.Standard;
|
||||||
|
var rise = CostRegression.Of(Fills(SlippageTiers.Major, 40, 8.2, real: false), table).Single();
|
||||||
|
Assert.IsTrue(rise.Rise);
|
||||||
|
Assert.IsTrue(rise.Bp >= rise.Measured && rise.Bp - rise.Measured < CostRegression.Step && rise.Bp % CostRegression.Step == 0, $"{rise.Bp}");
|
||||||
|
Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 29, 8.2, real: true), table), "too few");
|
||||||
|
Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 40, 5.1, real: true), table), "noise around what is in force");
|
||||||
|
Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Minor, 200, 4, real: false), table), "a fall on a practice account");
|
||||||
|
var fall = CostRegression.Of(Fills(SlippageTiers.Minor, 40, 4, real: true), table).Single();
|
||||||
|
Assert.IsFalse(fall.Rise);
|
||||||
|
Assert.IsTrue(fall.Bp is > 3m and < 5m);
|
||||||
|
|
||||||
|
// Real money says less but everything together says more: the cautious side wins.
|
||||||
|
var mixed = CostRegression.Of([.. Fills(SlippageTiers.Equity, 40, 4, real: true), .. Fills(SlippageTiers.Equity, 400, 9, real: false, seed: 2)], table).Single();
|
||||||
|
Assert.IsTrue(mixed.Rise);
|
||||||
|
|
||||||
|
// Better than the middle price: never a negative or a zero slippage.
|
||||||
|
Assert.AreEqual(CostRegression.Step, CostRegression.Of(Fills(SlippageTiers.Equity, 60, -4, real: true), table).Single().Bp);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task FillAsync(TradingRig rig, Guid account, Instrument instrument, decimal bp, int n, OrderPurpose purpose = OrderPurpose.Entry)
|
||||||
|
{
|
||||||
|
var order = Ids.NewId(rig.Clock);
|
||||||
|
await rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose) " +
|
||||||
|
"VALUES (@id, @a, @i, 'x', @c, 'buy', 'market', @q, 'filled', @now, @now, @p)", _none, ("id", order), ("a", account), ("i", instrument.Id), ("c", "O" + order), ("q", 1m),
|
||||||
|
("now", rig.Clock.UtcNow), ("p", Wire.Text(purpose))).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp) " +
|
||||||
|
"VALUES (@id, @a, @o, @i, @e, 'buy', @q, @q, @z, 'EUR', @at, @at, 'x', @q, @bp)", _none, ("id", Ids.NewId(rig.Clock)), ("a", account), ("o", order), ("i", instrument.Id),
|
||||||
|
("e", "E" + order), ("q", 1m), ("z", 0m), ("at", rig.Clock.UtcNow.AddDays(-1).AddMinutes(n)), ("bp", bp)).ConfigureAwait(false);
|
||||||
|
}, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The month: the simulator and the stops never count, a rise is applied and said, it runs once.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheMonthLooksOnlyAtTheExecutionsOfABroker()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var simulated = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||||
|
var demo = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo, "demo").ConfigureAwait(false);
|
||||||
|
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||||
|
var book = new CostBook(rig.Db, rig.Clock);
|
||||||
|
for (var i = 0; i < 40; i++)
|
||||||
|
{
|
||||||
|
await FillAsync(rig, simulated.AccountId, btc, 40m, i).ConfigureAwait(false);
|
||||||
|
await FillAsync(rig, demo.AccountId, btc, 60m, i, OrderPurpose.Stop).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.HasCount(0, await book.ListAsync(_none).ConfigureAwait(false));
|
||||||
|
for (var i = 0; i < 40; i++)
|
||||||
|
{
|
||||||
|
await FillAsync(rig, demo.AccountId, btc, 7.2m, i).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsFalse(await book.MonthAsync(_none).ConfigureAwait(false), "once for each month");
|
||||||
|
rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||||
|
Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false));
|
||||||
|
var row = (await book.ListAsync(_none).ConfigureAwait(false)).Single();
|
||||||
|
Assert.AreEqual((SlippageTiers.Major, CostStatuses.Applied, 5m, 7.5m, 40), (row.Tier, row.Status, row.PreviousBp, row.Bp, row.Cases));
|
||||||
|
Assert.AreEqual(SlippageTable.Standard with { Major = 7.5m }, await book.TableAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual("Scostamento misurato su 40 esecuzioni (Bitcoin, Ethereum e Solana): 7,2 punti base (centesimi di punto percentuale) invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.",
|
||||||
|
(await NewsRulesTests.DiaryAsync(rig.Db).ConfigureAwait(false))[^1]);
|
||||||
|
|
||||||
|
// The next month the estimate in force is the new one: nothing to say.
|
||||||
|
rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||||
|
Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.HasCount(1, await book.ListAsync(_none).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A fall changes nothing until the user confirms it; refused, or grown old, it never will.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AFallWaitsForTheUser()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var live = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Live).ConfigureAwait(false);
|
||||||
|
var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 40; i++)
|
||||||
|
{
|
||||||
|
await FillAsync(rig, live.AccountId, pepe, 6m, i).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var book = new CostBook(rig.Db, rig.Clock);
|
||||||
|
await book.MonthAsync(_none).ConfigureAwait(false);
|
||||||
|
var first = (await book.ListAsync(_none).ConfigureAwait(false)).Single();
|
||||||
|
Assert.AreEqual((CostStatuses.Pending, 6m), (first.Status, first.Bp));
|
||||||
|
Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.HasCount(1, await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'cost_pending'", r => r.Id("id")).ConfigureAwait(false));
|
||||||
|
|
||||||
|
// A month later the same proposal takes its place; the old one cannot be confirmed any more.
|
||||||
|
rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||||
|
await book.MonthAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.IsFalse(await book.DecideAsync(first.Id, true, "utente", _none).ConfigureAwait(false));
|
||||||
|
var second = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending);
|
||||||
|
Assert.IsTrue(await book.DecideAsync(second.Id, false, "utente", _none).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false));
|
||||||
|
|
||||||
|
rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||||
|
await book.MonthAsync(_none).ConfigureAwait(false);
|
||||||
|
var third = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending);
|
||||||
|
Assert.IsTrue(await book.DecideAsync(third.Id, true, "utente", _none).ConfigureAwait(false));
|
||||||
|
Assert.IsFalse(await book.DecideAsync(third.Id, false, "utente", _none).ConfigureAwait(false), "only once");
|
||||||
|
Assert.AreEqual(SlippageTable.Standard with { Minor = 6m }, await book.TableAsync(_none).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual("utente", (await book.ListAsync(_none).ConfigureAwait(false))[^1].DecidedBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The table in force reaches the simulator and the plan of a backtest, where it stays written.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheEstimatesReachTheSimulatorAndThePlanOfATest()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||||
|
await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||||
|
var table = SlippageTable.Standard;
|
||||||
|
using var paper = new PaperBroker(PaperOptions.Okx() with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, rig.Clock, rig.QuoteAsync, rig.Spec) { Slippage = () => table };
|
||||||
|
await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false);
|
||||||
|
rig.Quote("BTC-EUR", 60000m, 60000m);
|
||||||
|
async Task<decimal> BuyAsync(string id)
|
||||||
|
{
|
||||||
|
await paper.SubmitOrderAsync(new OrderRequest(id, "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Ioc), _none).ConfigureAwait(false);
|
||||||
|
await paper.PumpAsync(_none).ConfigureAwait(false);
|
||||||
|
return (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == id).Price;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(60030m, await BuyAsync("B1").ConfigureAwait(false));
|
||||||
|
table = table with { Major = 20m };
|
||||||
|
Assert.AreEqual(60120m, await BuyAsync("B2").ConfigureAwait(false));
|
||||||
|
|
||||||
|
Assert.AreEqual(60030m, CostModel.Standard.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m));
|
||||||
|
Assert.AreEqual(60240m, new CostModel(2m) { Slippage = table }.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m));
|
||||||
|
var request = new TrialRequest(StrategyCatalog.All[0].Id, TrialSources.Research, Venues.Binance, ["BTCEUR"], new DateOnly(2024, 1, 1), new DateOnly(2025, 1, 1), 1000m, null);
|
||||||
|
var plain = Laboratory.BuildPlan(request, rig.Clock.UtcNow, SlippageTable.Standard).Plan;
|
||||||
|
Assert.AreEqual(Laboratory.BuildPlan(request, rig.Clock.UtcNow).Plan.ToJson(), plain.ToJson(), "the plans written so far stay what they are");
|
||||||
|
var plan = Laboratory.BuildPlan(request, rig.Clock.UtcNow, table).Plan;
|
||||||
|
Assert.AreEqual(table, TrialPlan.FromJson(plan.ToJson()).Slippage);
|
||||||
|
Assert.AreNotEqual(TrialPlan.Hash(plain.ToJson()), TrialPlan.Hash(plan.ToJson()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The mean return after each kind of event, from the first close after the publication.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheTableOfTheNewsStartsFromTheFirstCloseAfter()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||||
|
var first = new DateOnly(2026, 1, 1);
|
||||||
|
await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(btc.Id, Enumerable.Range(0, 20).Select(i =>
|
||||||
|
{
|
||||||
|
var close = i switch { < 4 => 100.0, 4 => 90, 5 => 81, _ => 45 };
|
||||||
|
return new DailyBar(first.AddDays(i), close, close, close, close, 1);
|
||||||
|
}), "test", _none).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Published during the fourth day (close 100): then 90 the day after, 45 five days after.
|
||||||
|
await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Exchange hacked", new DateTimeOffset(2026, 1, 4, 10, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Published when the fifth had already closed: the first close after is 81, then 45 and 45.
|
||||||
|
await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bridge hacked", new DateTimeOffset(2026, 1, 6, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Too recent, and of no known kind: they do not count.
|
||||||
|
await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Wallet hacked", new DateTimeOffset(2026, 1, 18, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false);
|
||||||
|
await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bitcoin quiet", new DateTimeOffset(2026, 1, 2, 0, 0, 0, TimeSpan.Zero), 2, 0.1, "A", trusted: true).ConfigureAwait(false);
|
||||||
|
var desk = new DiscoveryDesk(rig.Db, rig.Clock, new LearningStore(rig.Db, rig.Clock));
|
||||||
|
await desk.RefreshAsync(_none).ConfigureAwait(false);
|
||||||
|
var impact = (await desk.LatestAsync(_none).ConfigureAwait(false)).News.Single();
|
||||||
|
Assert.AreEqual(("security_incident", 2, "troppo pochi per fidarsi"), (impact.Kind, impact.Cases, impact.Trust));
|
||||||
|
Assert.AreEqual((-0.1 + ((45.0 / 81) - 1)) / 2, impact.OneDay, 1e-9);
|
||||||
|
Assert.AreEqual((-0.55 + ((45.0 / 81) - 1)) / 2, impact.FiveDays, 1e-9);
|
||||||
|
Assert.AreEqual("Attacco informatico", NewsEventNames.Label(impact.Kind));
|
||||||
|
foreach (var kind in News.NewsVerdicts.EventTypes.Where(k => k != "other"))
|
||||||
|
{
|
||||||
|
Assert.AreNotEqual("Altro", NewsEventNames.Label(kind), kind);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The close of a stock is at four in New York, not at midnight.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCloseOfAStockIsInNewYork()
|
||||||
|
{
|
||||||
|
var bars = Enumerable.Range(0, 8).Select(i => new DailyBar(new DateOnly(2026, 7, 1).AddDays(i), 1, 1, 1, 100 + i, 1)).ToList();
|
||||||
|
var before = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 19, 59, 0, TimeSpan.Zero));
|
||||||
|
var after = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 20, 0, 0, TimeSpan.Zero));
|
||||||
|
Assert.AreEqual(0.01, before!.Value.One, 1e-9);
|
||||||
|
Assert.AreEqual(1.0 / 101, after!.Value.One, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<Example> Examples(int count, Func<int, Gen, (double Volatility, bool Win)> make, int perDay = 1)
|
||||||
|
{
|
||||||
|
var gen = new Gen(4);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count).Select(i =>
|
||||||
|
{
|
||||||
|
var (volatility, win) = make(i, gen);
|
||||||
|
var day = new DateOnly(2021, 1, 1).AddDays(i / perDay * 3);
|
||||||
|
return new Example(Guid.NewGuid(), StrategyNames.CryptoTrend, "C" + i, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "t", 0.1m, null, null,
|
||||||
|
new Dictionary<string, double> { [Clues.VolatilityRatio] = volatility })
|
||||||
|
{ Label = new CaseLabel(win, win ? 0.1 : -0.1, day, day.AddDays(1), "x") };
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A real relation is found and said with its cases; without one, the bot says that it does not matter.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ARelationIsSaidWithItsCasesAndItsTrust()
|
||||||
|
{
|
||||||
|
var real = DiscoveryFinder.Of(Examples(900, (i, gen) => i % 3 == 0 ? (2, gen.Double() < 0.25) : (1, gen.Double() < 0.55)));
|
||||||
|
var found = real[0];
|
||||||
|
Assert.AreEqual("I segnali di trend sulle crypto riescono meno quando i prezzi sono molto più agitati del solito", found.Title);
|
||||||
|
Assert.AreEqual((300, "conclusione solida"), (found.Cases, found.Trust));
|
||||||
|
Assert.MatchesRegex(new System.Text.RegularExpressions.Regex("^[0-9]+% di riusciti contro il [0-9]+% degli altri$"), found.Detail);
|
||||||
|
|
||||||
|
var hint = DiscoveryFinder.Of(Examples(200, (i, gen) => i % 5 == 0 ? (2, gen.Double() < 0.1) : (1, gen.Double() < 0.6)));
|
||||||
|
Assert.AreEqual((40, "un indizio discreto"), (hint[0].Cases, hint[0].Trust));
|
||||||
|
|
||||||
|
var nothing = DiscoveryFinder.Of(Examples(900, (i, gen) => (i % 3 == 0 ? 2 : 1, gen.Double() < 0.4)));
|
||||||
|
Assert.IsTrue(nothing.Any(d => d.Title == "Il giorno della settimana non conta per i segnali di trend sulle crypto" && d.Cases == 900));
|
||||||
|
Assert.IsTrue(nothing.All(d => d.Detail == "Le differenze stanno tutte dentro il margine d'errore"), string.Join('|', nothing.Select(d => d.Title)));
|
||||||
|
|
||||||
|
// Too few to say anything at all.
|
||||||
|
Assert.HasCount(0, DiscoveryFinder.Of(Examples(15, (i, gen) => (i % 2 == 0 ? 2 : 1, i % 2 == 0))));
|
||||||
|
Assert.AreEqual("troppo pochi per fidarsi", Discovery.TrustOf(19));
|
||||||
|
Assert.AreEqual("un indizio discreto", Discovery.TrustOf(99));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>On pure chance almost nothing is declared: the many questions and the coins that move together are counted.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ChanceIsNotADiscovery()
|
||||||
|
{
|
||||||
|
var declared = 0;
|
||||||
|
for (var seed = 0; seed < 60; seed++)
|
||||||
|
{
|
||||||
|
var gen = new Gen(seed);
|
||||||
|
var months = new Dictionary<int, (bool High, double Chance)>();
|
||||||
|
|
||||||
|
// Whole months win or lose together, and whole months are agitated or calm, with no relation between the two.
|
||||||
|
var examples = Examples(1200, (i, _) =>
|
||||||
|
{
|
||||||
|
var month = i / 60;
|
||||||
|
if (!months.TryGetValue(month, out var m))
|
||||||
|
{
|
||||||
|
months[month] = m = (gen.Bool(), gen.Bool() ? 0.2 : 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (m.High ? 2 : 1, gen.Double() < m.Chance);
|
||||||
|
}, perDay: 6);
|
||||||
|
declared += DiscoveryFinder.Of(examples).Any(d => d.Detail.Contains("contro", StringComparison.Ordinal)) ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsLessThanOrEqualTo(6, declared, $"{declared} of 60");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheQuantileIsTheOneOfTheNormal()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(1.959964, DiscoveryFinder.Quantile(0.05), 1e-4);
|
||||||
|
Assert.AreEqual(2.575829, DiscoveryFinder.Quantile(0.01), 1e-4);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,464 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>What the independent review of Phase 8 found (issue #67): each defect has the case that shows it.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class LearningReviewTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
|
||||||
|
private static readonly FirstModelFile Rates = new() { BaseRates = new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4, [StrategyNames.EquityMomentum] = 0.5 } };
|
||||||
|
|
||||||
|
/// <summary>The same stretch of days as the tests of the cycle, with entries inside.</summary>
|
||||||
|
private static readonly DateOnly From = LearningCycleTests.From;
|
||||||
|
|
||||||
|
/// <summary>With few winners the lowest step is one or two losses: it must not become the floor of every other one.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheIsotonicCalibrationOrdersEvenWhenWinnersAreFew()
|
||||||
|
{
|
||||||
|
var gen = new Gen(23);
|
||||||
|
var scores = Enumerable.Range(0, 1800).Select(_ => gen.Normal()).ToList();
|
||||||
|
double Truth(double s) => 0.03 + (0.30 * Odds.Probability(2 * s));
|
||||||
|
var wins = scores.Select(s => gen.Double() < Truth(s)).ToList();
|
||||||
|
|
||||||
|
// The two smallest scores lose and the largest wins, as in the history that was shipped.
|
||||||
|
scores.AddRange([-9, -8, 9]);
|
||||||
|
wins.AddRange([false, false, true]);
|
||||||
|
var fitted = Calibration.Fit(scores, wins);
|
||||||
|
Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind);
|
||||||
|
Assert.AreEqual((double)wins.Count(w => w) / wins.Count, scores.Average(fitted.Probability), 0.01, "on the whole it says the base rate");
|
||||||
|
foreach (var s in new[] { -1.5, -0.5, 0, 0.5, 1.5 })
|
||||||
|
{
|
||||||
|
Assert.AreEqual(Truth(s), fitted.Probability(s), 0.07, $"at {s}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(fitted.Probability(-20) is > 0.02 and < 0.15 && fitted.Probability(20) is > 0.2 and < 0.5, "one case at the edge says nothing");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The model shipped must tell signals apart, and be as well calibrated as 11.5 asks on cases it had not studied.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheFirstModelTellsSignalsApart()
|
||||||
|
{
|
||||||
|
var file = FirstModel.Embedded!;
|
||||||
|
var rate = file.BaseRates[StrategyNames.CryptoTrend];
|
||||||
|
var said = file.Examples.Where(e => e.IsLabelled).Select(e => file.Model!.Probability(e.Features)).ToList();
|
||||||
|
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p < rate - 0.01));
|
||||||
|
Assert.IsGreaterThan(said.Count / 4, said.Count(p => p > rate + 0.01));
|
||||||
|
Assert.AreEqual(rate, said.Average(), 0.02);
|
||||||
|
var verified = file.Report!.Chosen!.Combined;
|
||||||
|
Assert.IsLessThan(ActivationCheck.MaxCalibrationError, verified.CalibrationError!.Value);
|
||||||
|
Assert.AreEqual(file.Report.Examples, verified.Bands.Sum(b => b.Cases), 10, "an example verified five times is one case");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Five combinations verify the same thirty examples: the band has thirty cases, not one hundred and fifty.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AnExampleVerifiedFiveTimesIsOneCase()
|
||||||
|
{
|
||||||
|
var cases = Enumerable.Range(0, 30).Select(i => Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with { Label = new CaseLabel(i < 6, 0.1, From.AddDays(i + 1), From.AddDays(i + 9), "x") }).ToList();
|
||||||
|
var band = Judge.Bands([.. Enumerable.Range(0, 5).SelectMany(_ => cases.Select(c => new Estimate(c, 0.22, 0.2, 1)))]).Single();
|
||||||
|
Assert.AreEqual(30, band.Cases);
|
||||||
|
Assert.AreEqual(0.2, band.Observed, 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.1: who knows nothing of a strategy leaves its operations as they are, even when it has a base rate.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AModelEstimatesOnlyTheStrategiesItStudied()
|
||||||
|
{
|
||||||
|
ModelRow Row(string status, params string[] studied) => new(Guid.NewGuid(), 1, LearnerNames.Logistic, status, "test", default, 500, 0, null, LearningCycleTests.Always(0.1) with { Strategies = studied }, new ModelReport());
|
||||||
|
Example Case(string strategy) => new(Guid.NewGuid(), strategy, "X", CaseSources.Live, From, default, "x", 0.2m, null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
|
||||||
|
var gate = new ModelGate(Row(ModelStatuses.Champion, StrategyNames.CryptoTrend), Row(ModelStatuses.Challenger, StrategyNames.CryptoTrend, StrategyNames.EquityMomentum), MultiplierRule.Standard, Rates.BaseRates, true);
|
||||||
|
Assert.HasCount(2, gate.Estimate(Case(StrategyNames.CryptoTrend)));
|
||||||
|
var only = gate.Estimate(Case(StrategyNames.EquityMomentum)).Single();
|
||||||
|
Assert.IsFalse(only.InCharge, "the one in charge has nothing to say");
|
||||||
|
Assert.HasCount(0, gate.Estimate(Case(StrategyNames.EquityMeanrev)), "no base rate");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> FillsAsync(LiveRig rig) => string.Join('\n', await rig.Rig.QueryAsync(
|
||||||
|
"SELECT i.symbol, f.side, f.quantity, f.executed_at FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, i.symbol",
|
||||||
|
r => $"{r.Text("symbol")} {r.Text("side")} {r.Money("quantity")} {r.Moment("executed_at"):MM-dd HH:mm}").ConfigureAwait(false));
|
||||||
|
|
||||||
|
private static async Task<(string Fills, int Failures)> RunAsync(Func<LiveRig, DateOnly, Task>? before = null)
|
||||||
|
{
|
||||||
|
var last = From.AddDays(20);
|
||||||
|
await using var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
|
||||||
|
rig.UseFirst(Rates);
|
||||||
|
await LearningCycleTests.AddModelAsync(rig.Rig.Db, rig.Rig.Clock, LearningCycleTests.Always(0.35), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
await rig.Rig.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, rig.Rig.Clock, CycleState.Key, new CycleState { ActivatedAt = rig.Rig.Clock.UtcNow }, _none), _none).ConfigureAwait(false);
|
||||||
|
for (var day = From; day <= last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
if (before is not null)
|
||||||
|
{
|
||||||
|
await before(rig, day).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (await FillsAsync(rig).ConfigureAwait(false), rig.Failures);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<int> ExecuteAsync(LiveRig rig, string sql, params (string, object?)[] parameters) => rig.Rig.Db.WriteAsync(s => s.ExecuteAsync(sql, _none, parameters), _none);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SPEC 11.1: the multiplier of birth holds to the close. The world outside cannot be read any more, or the clues of the
|
||||||
|
/// archive are damaged: operations born halved must trade as before, not be bought whole.
|
||||||
|
/// </summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AFailureOfLearningNeverForgetsTheMultiplierOfBirth()
|
||||||
|
{
|
||||||
|
var (whole, _) = await RunAsync().ConfigureAwait(false);
|
||||||
|
var (blind, failures) = await RunAsync((rig, day) => day == From.AddDays(10) ? ExecuteAsync(rig, "ALTER TABLE market_mood RENAME TO market_mood_away") : Task.CompletedTask).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual((whole, 0), (blind, failures), "without the outside");
|
||||||
|
var (damaged, again) = await RunAsync((rig, day) => day >= From.AddDays(10) ? ExecuteAsync(rig, "UPDATE ml_features SET features = @j", ("j", new DbJson("\"damaged\""))) : Task.CompletedTask)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
Assert.AreEqual((whole, 0), (damaged, again), "with damaged clues");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>ADR 0018, point 2: a failure while saving the examples takes back only the examples, on both engines.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AnExampleThatCannotBeSavedNeverStopsTheDecision()
|
||||||
|
{
|
||||||
|
var runs = 0L;
|
||||||
|
var kept = 0L;
|
||||||
|
var (fills, failures) = await RunAsync(async (rig, day) =>
|
||||||
|
{
|
||||||
|
if (day == From)
|
||||||
|
{
|
||||||
|
await ExecuteAsync(rig, "ALTER TABLE ml_predictions RENAME TO ml_predictions_away").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
runs = await rig.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM engine_runs"), _none).ConfigureAwait(false);
|
||||||
|
kept = await rig.Learning.Store.CountAsync(CaseSources.Live, _none).ConfigureAwait(false);
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(0, failures);
|
||||||
|
Assert.IsGreaterThan(15, runs, "one decision a day");
|
||||||
|
Assert.AreEqual(0, kept, "the examples were taken back whole");
|
||||||
|
Assert.IsGreaterThan(0, fills.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.2, 5.6: a decision recovered in the afternoon must not know more than the operation that started at midnight.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue()
|
||||||
|
{
|
||||||
|
var last = From.AddDays(20);
|
||||||
|
DateOnly born;
|
||||||
|
await using (var rig = await LiveRig.CreateAsync(From, last).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
rig.UseFirst(Rates);
|
||||||
|
for (var day = From; day <= last; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await rig.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
born = (await rig.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day > From.AddDays(2)).Day;
|
||||||
|
}
|
||||||
|
|
||||||
|
await using var late = await LiveRig.CreateAsync(From, last).ConfigureAwait(false);
|
||||||
|
late.UseFirst(Rates);
|
||||||
|
for (var day = From; day <= born; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
await late.DayAsync(day, morning: 8).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Off until the afternoon after the close: at noon a value of the mood was published and saved.
|
||||||
|
var midnight = new DateTimeOffset(born.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||||
|
await late.StoreBarAsync(born).ConfigureAwait(false);
|
||||||
|
var mood = new MoodStore(late.Rig.Db, late.Rig.Clock);
|
||||||
|
await mood.UpsertAsync([new(MoodIndicators.Vix, midnight.AddHours(-10), 18, null, "t")], _none).ConfigureAwait(false);
|
||||||
|
late.Rig.Clock.Set(midnight.AddHours(12));
|
||||||
|
await mood.UpsertAsync([new(MoodIndicators.FearGreed, midnight.AddHours(11), 99, null, "t")], _none).ConfigureAwait(false);
|
||||||
|
late.Rig.Clock.Set(midnight.AddHours(15));
|
||||||
|
late.Quotes(born.AddDays(1), b => b.Close);
|
||||||
|
await late.MinutesAsync(5).ConfigureAwait(false);
|
||||||
|
var example = (await late.Learning.Store.AllAsync(_none).ConfigureAwait(false)).First(e => e.Day == born);
|
||||||
|
Assert.IsFalse(example.Features.ContainsKey(Clues.FearGreed), "published after the operation had started");
|
||||||
|
Assert.AreEqual(18d, example.Features[Clues.Vix], "known when it was due");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A strategy whose labels cannot be made must not keep a model that counts from being checked.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ALabelThatFailsDoesNotStopTheCheck()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
rig.Clock.Set(new DateTimeOffset(2027, 3, 3, 2, 0, 0, TimeSpan.Zero));
|
||||||
|
var desk = new LearningDesk(rig.Db, rig.Clock) { First = Rates };
|
||||||
|
await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From), _none), _none).ConfigureAwait(false);
|
||||||
|
var cycle = new LearningCycle(rig.Db, rig.Clock, desk, (_, _, _) => throw new InvalidDataException("bars"));
|
||||||
|
await Assert.ThrowsExactlyAsync<AggregateException>(() => cycle.RunAsync(_none)).ConfigureAwait(false);
|
||||||
|
var state = await desk.CycleAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(new DateOnly(2027, 3, 3), state.LastNight);
|
||||||
|
Assert.AreEqual(1, state.Health!.Version);
|
||||||
|
Assert.IsNotNull(state.LastSunday);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Example Open(string strategy, string symbol, DateOnly day) => new(Guid.Empty, strategy, symbol, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "x", 0.2m,
|
||||||
|
null, null, new Dictionary<string, double> { [Clues.Strength] = 0.5 });
|
||||||
|
|
||||||
|
/// <summary>SPEC 5.6: the computer slept for twenty hours with the process alive; the night is made once at the waking.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public async Task TheNightIsMadeAfterALongSleep()
|
||||||
|
{
|
||||||
|
var clock = new ManualClock(new DateTimeOffset(2027, 3, 3, 0, 0, 0, TimeSpan.Zero));
|
||||||
|
var runs = 0;
|
||||||
|
var scheduler = new Scheduler(clock, new EventBus());
|
||||||
|
scheduler.Add(TradingService.ModelJob(_ =>
|
||||||
|
{
|
||||||
|
runs++;
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}), clock.UtcNow);
|
||||||
|
clock.Set(new DateTimeOffset(2027, 3, 3, 22, 0, 0, TimeSpan.Zero));
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 200 && runs == 0; i++)
|
||||||
|
{
|
||||||
|
await Task.Delay(20, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1, runs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.2: one example for each potential operation, even when a newer history reaches days already lived.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ANewerHistoryDoesNotCountTwiceWhatWasLived()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, Open(StrategyNames.CryptoTrend, "BTC-EUR", From) with { Label = new CaseLabel(true, 0.1, From.AddDays(1), From.AddDays(20), "x") }, _none), _none)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
Example Past(string symbol, int from, int to) => Open(StrategyNames.CryptoTrend, symbol, From.AddDays(from)) with
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Source = CaseSources.History,
|
||||||
|
Label = new CaseLabel(false, -0.1, From.AddDays(from + 1), From.AddDays(to), "x"),
|
||||||
|
};
|
||||||
|
var desk = new LearningDesk(rig.Db, rig.Clock)
|
||||||
|
{
|
||||||
|
First = new FirstModelFile { Examples = [Past("BTCEUR", 1, 19), Past("BTCEUR", -3, 5), Past("BTCEUR", -30, 0), Past("BTCEUR", 20, 30), Past("ETHEUR", 1, 19)] },
|
||||||
|
};
|
||||||
|
await desk.PrepareHistoryAsync(_none).ConfigureAwait(false);
|
||||||
|
var kept = (await desk.Store.AllAsync(_none).ConfigureAwait(false)).Where(e => e.Source == CaseSources.History).Select(e => e.Symbol + (e.Day.DayNumber - From.DayNumber)).Order(StringComparer.Ordinal);
|
||||||
|
Assert.AreEqual("BTCEUR-30 BTCEUR20 ETHEUR1", string.Join(' ', kept));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label leaves before the report the decision knew of, whatever the calendar says months later.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheReportOfALabelIsTheOneKnownAtTheDecision()
|
||||||
|
{
|
||||||
|
Example With(string strategy, double? days) => Open(strategy, "AAPL", From) with { Features = days is { } d ? new Dictionary<string, double> { [Clues.EarningsDays] = d } : [] };
|
||||||
|
Assert.AreEqual(From.AddDays(6), Clues.ReportOf(With(StrategyNames.EquityMeanrev, 6)));
|
||||||
|
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, Clues.FarReport)));
|
||||||
|
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMeanrev, null)));
|
||||||
|
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMomentum, 6)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Estimate Closed(int i, bool win, string stage, double p) => new(Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Stage = stage,
|
||||||
|
Label = new CaseLabel(win, win ? 0.02 : -0.02, From.AddDays(i + 1), From.AddDays(i + 2), "x"),
|
||||||
|
}, p, 0.4, MultiplierRule.Standard.Of(p, 0.4));
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, double> Money = new() { [StrategyNames.CryptoTrend] = 1000 };
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.5: three hundred signals in observation and a handful with capital prove no gain, however lucky.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AFewFundedSignalsNeverStartTheModel()
|
||||||
|
{
|
||||||
|
List<Estimate> observed = [.. Enumerable.Range(0, 400).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
|
||||||
|
ActivationCheck With(int funded) => ActivationCheck.Of([.. observed, .. Enumerable.Range(0, funded).Select(i => Closed(1000 + i, i * 7 % 25 < 9, StrategyStages.Simulation, 0.36))], Rates.BaseRates, Money);
|
||||||
|
foreach (var few in new[] { 1, 5, 10, 30, 99 })
|
||||||
|
{
|
||||||
|
var check = With(few);
|
||||||
|
Assert.AreEqual((few, true, true), (check.Funded, check.Enough, check.Calibrated));
|
||||||
|
Assert.IsFalse(check.Improves || check.Passed, $"{few} signals");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(With(100).Passed, "the same advantage on enough of them");
|
||||||
|
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), Judge.Interval([1, 1, 1], [1, 1, 1], 0.9), "nothing can be said of three");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.4: the signals with capital are weighed among themselves, not with the older ones in observation.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheGainIsWeighedOnTheSignalsItIsMeasuredOn()
|
||||||
|
{
|
||||||
|
List<Estimate> observed = [.. Enumerable.Range(0, 200).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
|
||||||
|
|
||||||
|
// Of those with capital only the losses have matured so far, nearly: without weights the filter would look good.
|
||||||
|
List<Estimate> funded = [.. Enumerable.Range(0, 100).Select(i => Closed(1000 + i, i % 10 == 0, StrategyStages.Simulation, 0.36))];
|
||||||
|
var check = ActivationCheck.Of([.. observed, .. funded], Rates.BaseRates, Money);
|
||||||
|
var alone = Judge.Score(Judge.Weigh(funded, Rates.BaseRates), Money);
|
||||||
|
Assert.AreEqual(alone.GainWithout, check.Scores.GainWithout, 1e-9);
|
||||||
|
Assert.AreEqual(alone.GainWith, check.Scores.GainWith, 1e-9);
|
||||||
|
Assert.AreEqual((0.4 * 0.02 * 200) - (0.6 * 0.02 * 200), check.Scores.GainWithout, 1e-9, "wins and losses in the proportion of the base rate");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A report already out when the operation starts is not one to leave before (ADR 0017, point 5).</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AReportAlreadyOutDoesNotCloseTheLabel()
|
||||||
|
{
|
||||||
|
var bars = Enumerable.Range(0, 10).Select(i => new DailyBar(From.AddDays(i), 100, 101, 99, 100, 1e6)).ToList();
|
||||||
|
var data = new BacktestDataset([new BacktestInstrument(MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null }, bars)], "EUR");
|
||||||
|
var example = Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(1));
|
||||||
|
DateOnly? ClosedWith(int report) => CaseLabels.Of(example, () => new LeavesBeforeReports(), data, From.AddDays(9), earnings: From.AddDays(report))?.ClosedDay;
|
||||||
|
Assert.IsNull(ClosedWith(1), "the evening of the decision");
|
||||||
|
Assert.IsNull(ClosedWith(2), "the day of the purchase");
|
||||||
|
Assert.AreEqual(From.AddDays(4), ClosedWith(4), "sold at the open of the day of the report");
|
||||||
|
Assert.AreEqual(From.AddDays(7), ClosedWith(7));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class LeavesBeforeReports : IStrategy
|
||||||
|
{
|
||||||
|
public string Id => StrategyNames.CryptoTrend;
|
||||||
|
|
||||||
|
public string Version => "t";
|
||||||
|
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(StrategyContext context) =>
|
||||||
|
!context.Portfolio.Holds("BTC-EUR") ? [new Intent("BTC-EUR", 0.2m, "x") { Strength = 0.5 }]
|
||||||
|
: context.NextEarnings?.Invoke("BTC-EUR") is { } report && context.NextSession is { } next && report <= next ? [new Intent("BTC-EUR", 0m, "report")] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 5.6: a computer off every night from the day of the installation still makes the night at its return.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AJobNeverMadeCountsFromTheFirstStart()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true).ConfigureAwait(false);
|
||||||
|
var rows = await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE name IN ('modello', 'backup')",
|
||||||
|
r => (Name: r.Text("name"), Due: r.MomentOrNull("last_due_at"))), _none).ConfigureAwait(false);
|
||||||
|
Assert.HasCount(2, rows);
|
||||||
|
Assert.IsTrue(rows.All(r => r.Due is not null), "the next start has something to count from");
|
||||||
|
var clock = new ManualClock(rows[0].Due!.Value.AddDays(2));
|
||||||
|
var scheduler = new Scheduler(clock, new EventBus());
|
||||||
|
var runs = 0;
|
||||||
|
scheduler.Add(TradingService.ModelJob(_ => Task.FromResult(runs++)), rows.First(r => r.Name == "modello").Due);
|
||||||
|
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
|
||||||
|
await scheduler.BesideAsync().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1, runs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 5.6, 9.4: the night made up for at the return waits for the bars of the absence, but not for ever.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public async Task TheNightWaitsForTheBars()
|
||||||
|
{
|
||||||
|
var midnight = new DateTimeOffset(2027, 3, 8, 0, 0, 0, TimeSpan.Zero);
|
||||||
|
var clock = new ManualClock(midnight.AddHours(8));
|
||||||
|
DateTimeOffset? last = midnight.AddDays(-3);
|
||||||
|
var asked = 0;
|
||||||
|
Task Ready() => TradingService.BarsReadyAsync(clock, () => last, () => Task.FromResult(asked++), _none);
|
||||||
|
var waiting = Ready();
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
await Task.Delay(50, _none).ConfigureAwait(false);
|
||||||
|
Assert.IsFalse(waiting.IsCompleted);
|
||||||
|
last = clock.UtcNow;
|
||||||
|
await AdvanceAsync(waiting).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1, asked);
|
||||||
|
await Ready().ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1, asked, "the bars of today are there");
|
||||||
|
|
||||||
|
// No network: after half an hour it goes on.
|
||||||
|
last = null;
|
||||||
|
var offline = Ready();
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(29));
|
||||||
|
await Task.Delay(50, _none).ConfigureAwait(false);
|
||||||
|
Assert.IsFalse(offline.IsCompleted);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(2));
|
||||||
|
await AdvanceAsync(offline).ConfigureAwait(false);
|
||||||
|
|
||||||
|
async Task AdvanceAsync(Task task)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 100 && !task.IsCompleted; i++)
|
||||||
|
{
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(10));
|
||||||
|
await Task.Delay(20, _none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(task.IsCompletedSuccessfully);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.4: with the promotion taken back, the one on trial is judged again from the first threshold.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AnUndonePromotionStartsTheTrialAgain()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var old = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.3), ModelStatuses.Retired).ConfigureAwait(false);
|
||||||
|
var champion = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
|
||||||
|
var trial = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
|
||||||
|
await rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await ModelStore.SetReplacedAsync(s, rig.Clock, champion.Id, old.Id, _none).ConfigureAwait(false);
|
||||||
|
await ModelStore.SetThresholdAsync(s, rig.Clock, trial.Id, 150, _none).ConfigureAwait(false);
|
||||||
|
}, _none).ConfigureAwait(false);
|
||||||
|
Assert.IsTrue(await LearningCycle.UndoPromotionAsync(rig.Db, rig.Clock, _none).ConfigureAwait(false));
|
||||||
|
var after = await new ModelStore(rig.Db).FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual((trial.Id, 0), (after!.Id, after.ThresholdDone));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 11.2: a story that grew after the decision was due is seen as it was then, articles, links and verdict.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AStoryIsSeenAsItWasWhenTheDecisionWasDue()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var at = rig.Clock.UtcNow;
|
||||||
|
var story = Ids.NewId(rig.Clock);
|
||||||
|
Task LinkAsync(Database db, string target, DateTimeOffset when) => db.WriteAsync(s => s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', @t, 'name', @f)",
|
||||||
|
("id", Ids.NewId(rig.Clock)), ("st", story), ("t", target), ("f", when)), _none);
|
||||||
|
await rig.Db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
// The row as it is now, grown: negative, serious, linked to one more coin.
|
||||||
|
await s.ExecuteAsync("INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, severe, importance, created_at, updated_at) " +
|
||||||
|
"VALUES (@id, 't', 't', @p, @f, @l, 2, @yes, -0.4, 'fraud', 4, @f, @l)", _none, ("id", story), ("p", at.AddHours(-5)), ("f", at.AddHours(-4)), ("l", at.AddHours(8)), ("yes", true)).ConfigureAwait(false);
|
||||||
|
await LearningCasesTests.ArticleAsync(s, rig, story, "first", at.AddHours(-5), at.AddHours(-4), 0.1).ConfigureAwait(false);
|
||||||
|
await LearningCasesTests.ArticleAsync(s, rig, story, "later", at.AddHours(3), at.AddHours(8), -0.9, 4).ConfigureAwait(false);
|
||||||
|
}, _none).ConfigureAwait(false);
|
||||||
|
await LinkAsync(rig.Db, "okx:BTC-EUR", at.AddHours(-4)).ConfigureAwait(false);
|
||||||
|
await LinkAsync(rig.Db, "okx:ETH-EUR", at.AddHours(8)).ConfigureAwait(false);
|
||||||
|
rig.Clock.Set(at.AddHours(9));
|
||||||
|
var reader = new OutsideReader(rig.Db, rig.Clock);
|
||||||
|
var specs = new Dictionary<string, InstrumentSpec> { ["BTC-EUR"] = TradingRig.Btc, ["ETH-EUR"] = TradingRig.Btc with { Symbol = "ETH-EUR" } };
|
||||||
|
var then = await reader.ReadAsync(at, specs, null, _none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(0.1, then.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
|
||||||
|
Assert.IsNull(then.News["BTC-EUR"].Active);
|
||||||
|
Assert.AreEqual((1, 0), (then.Stories3Days["BTC-EUR"], then.Stories3Days["ETH-EUR"]));
|
||||||
|
var now = await reader.ReadAsync(at.AddHours(9), specs, null, _none).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(-0.4, now.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
|
||||||
|
Assert.AreEqual(4, now.News["BTC-EUR"].Active!.Story.RuleImportance);
|
||||||
|
Assert.AreEqual(1, now.Stories3Days["ETH-EUR"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void APrecisionUnderTheAlarmNeverReadsFiftyPercent()
|
||||||
|
{
|
||||||
|
Assert.AreEqual((49, 49, 50, 45, 56), (Health.Shown(0.4999), Health.Shown(0.496), Health.Shown(0.5), Health.Shown(0.451), Health.Shown(0.556)));
|
||||||
|
Assert.AreEqual("Precisione scesa al 49% su 41 casi.", LearningCycle.AsideText(AsideCodes.Precision, new HealthCheck { Precision = 0.4967, Cases = 41 }));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Learning;
|
||||||
|
using Anubis.Server;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The Apprendimento screen, the model settings and the model box of the Panoramica (SPEC 13.5, 13.6; issue #66).</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class LearningScreenTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
|
||||||
|
private static readonly DateTimeOffset Now = new(2026, 10, 9, 6, 21, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, double> Rates = new() { [StrategyNames.CryptoTrend] = 0.4 };
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, double> Capitals = new() { [StrategyNames.CryptoTrend] = 1000 };
|
||||||
|
|
||||||
|
private static void HasAll(string page, params string[] texts)
|
||||||
|
{
|
||||||
|
foreach (var text in texts)
|
||||||
|
{
|
||||||
|
StringAssert.Contains(page, text, $"Missing \"{text}\".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The numbers of appendix F.7 as in the mockup, on the page, in the Panoramica and in Operazioni; nothing can be changed.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheDemoShowsTheModelAsInTheMockup()
|
||||||
|
{
|
||||||
|
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
||||||
|
var demoRoot = server.Host.Config.Data.Root;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var page = await server.TextAsync("/apprendimento");
|
||||||
|
HasAll(page, "Il modello impara dall'esito di ogni segnale.", "In osservazione", "Sta imparando, ma non decide ancora.",
|
||||||
|
"Non potrà mai ingrandirle, né aprirne di sue.", "<strong>212</strong> <span class=\"muted\">su 300 necessari</span>", "Al ritmo attuale, tra tre e quattro settimane.",
|
||||||
|
"56%", "Tirando a caso sarebbe il 50%", "Domenica 4 ottobre, versione 3", "Prossima verifica dello sfidante", "Domenica 11 ottobre, 03:00",
|
||||||
|
"54% su 61 casi", "71% su 14 casi", "Stima perfetta", "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato.", "troppo pochi casi per contarci",
|
||||||
|
"Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "insieme a paura e avidità pesano 17 su 100.",
|
||||||
|
"In carica, versione 2", "Sfidante, versione 3", "16 agosto", "2.152", "2.332", "0,241", "0,239", "(senza filtro: +5,84", "+7,90", "+8,10", "non serve", "14 su 100",
|
||||||
|
"La versione 3 è ancora in prova.", "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100", "Fino ad allora gira in ombra accanto alla 2.",
|
||||||
|
"Nessuna anomalia", "Il mercato di oggi somiglia a quello su cui ha studiato", "Precisione sugli ultimi 60 casi: 55%, in linea con il 56% atteso",
|
||||||
|
"Ultimo controllo oggi alle 03:00. Ultimo allarme il 19 settembre, rientrato in 3 giorni", "17 ago", "5 ott", "sotto 50%", "49%",
|
||||||
|
"I segnali di trend riescono meno quando il mercato è molto agitato", "32 casi: un indizio discreto", "17 casi: troppo pochi per fidarsi", "212 casi: conclusione solida",
|
||||||
|
"27 settembre", "Prima versione, addestrata su 2.140 segnali ricostruiti dai dati storici.", "Vedi i numeri in una tabella");
|
||||||
|
Assert.IsFalse(page.Contains("/azioni/modello", StringComparison.Ordinal), "nothing to change in the demo");
|
||||||
|
HasAll(await server.TextAsync("/"), "Il modello osserva e impara, ma non decide ancora.", "su 300 necessari", "56% su dati mai visti", "domenica 11 ottobre, 03:00");
|
||||||
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%): solo osservazione, non ha cambiato la dimensione");
|
||||||
|
|
||||||
|
// The signal was born three days before the purchase, held back meanwhile: same example, same estimate.
|
||||||
|
var (db, clock) = (server.Host.Services!.Db, server.Host.Clock);
|
||||||
|
var earlier = Ids.NewId(clock);
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
var at = (await s.FirstOrDefaultAsync("SELECT created_at FROM decisions WHERE stage = 'model' AND symbol = 'MSFT'", r => (DateTimeOffset?)r.Moment("created_at")))!.Value.AddDays(-3);
|
||||||
|
await s.ExecuteAsync("UPDATE decisions SET decision_id = @d, created_at = @at WHERE stage = 'model' AND symbol = 'MSFT'", _none, ("d", earlier), ("at", at));
|
||||||
|
await LearningStore.AddAsync(s, clock, new Example(Guid.Empty, StrategyNames.EquityMeanrev, "MSFT", CaseSources.Live, DateOnly.FromDateTime(at.UtcDateTime), at, "x", 0.2m, null, null,
|
||||||
|
new Dictionary<string, double>())
|
||||||
|
{ DecisionId = earlier }, _none);
|
||||||
|
}, _none);
|
||||||
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
|
||||||
|
|
||||||
|
// Born the evening before, with the simulated operation closed on the day of the purchase: still the one bought.
|
||||||
|
var opened = (await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT t.opened_at FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE i.symbol = 'MSFT' AND t.status = 'closed' ORDER BY t.opened_at DESC LIMIT 1", r => (DateTimeOffset?)r.Moment("opened_at")), _none))!.Value;
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("UPDATE decisions SET created_at = @at WHERE decision_id = @d", _none, ("at", opened.AddHours(-10)), ("d", earlier));
|
||||||
|
var example = (await s.FirstOrDefaultAsync("SELECT id FROM ml_features WHERE decision_id = @d", r => (Guid?)r.Id("id"), ("d", earlier)))!.Value;
|
||||||
|
var day = DateOnly.FromDateTime(opened.UtcDateTime);
|
||||||
|
await LearningStore.AddLabelAsync(s, clock, example, new CaseLabel(false, -0.01, day.AddDays(-2), day, "x"), _none);
|
||||||
|
}, _none);
|
||||||
|
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
|
||||||
|
using var post = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
|
||||||
|
Assert.AreEqual("/apprendimento?errore=motore", ServerHarness.Location(post));
|
||||||
|
using var settings = await server.PostFormAsync("/impostazioni", "/azioni/modello", (LearningSettings.Aside.Key, "on"));
|
||||||
|
Assert.AreEqual("/impostazioni?errore=motore#modello", ServerHarness.Location(settings));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await server.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
TempFolder.Delete(demoRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A new installation: no invented number, then the first model, the live signals, the challenger, the undo.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ThePageFollowsTheArchiveAndTheUserTakesAPromotionBack()
|
||||||
|
{
|
||||||
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||||
|
await using var keep = postgres;
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", env);
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
var (db, clock) = (services.Db, server.Host.Clock);
|
||||||
|
HasAll(await server.TextAsync("/apprendimento"), "Non ancora partito", "Non ha ancora cominciato.", "Prima verifica", "Nessun modello ancora.", "La storia comincia con il primo modello.",
|
||||||
|
"Il controllo gira ogni notte alle 03:00", "Nessuna stima ha ancora un esito.");
|
||||||
|
HasAll(await server.TextAsync("/impostazioni"), "Nessuna promozione da annullare.");
|
||||||
|
using (var none = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione"))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/apprendimento?errore=promozione", ServerHarness.Location(none));
|
||||||
|
}
|
||||||
|
|
||||||
|
HasAll(await server.TextAsync("/apprendimento?errore=promozione"), "Non c'è nessuna promozione da annullare.");
|
||||||
|
|
||||||
|
// The first model with the report of its verification.
|
||||||
|
var desk = new LearningDesk(db, clock, services.Settings);
|
||||||
|
await desk.PrepareHistoryAsync(_none);
|
||||||
|
var first = (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!;
|
||||||
|
var scores = first.Report.Attempts.Single(a => a.Chosen).Combined;
|
||||||
|
HasAll(await server.TextAsync("/apprendimento"), "In osservazione", "<strong>0</strong> <span class=\"muted\">su 300 necessari</span>", "È presto per dire quanto manca.",
|
||||||
|
"Per ora sono i casi storici che non aveva studiato", "In carica, versione 1", Format.Number(first.Examples), Format.Number((decimal)scores.Brier, 3),
|
||||||
|
"Nessuno sfidante in prova.", "Prossimo addestramento", "Come è stato scelto il modello in carica", first.Report.Reason, "Primo modello: versione 1");
|
||||||
|
Assert.AreEqual(100, first.Report.Weights.Sum(w => w.Share), "the clues add up to 100");
|
||||||
|
HasAll(await server.TextAsync("/"), "Il modello osserva e impara", "su 300 necessari");
|
||||||
|
|
||||||
|
// A challenger beside it, and signals both estimated: 120 closed in the last four weeks.
|
||||||
|
var second = await LearningCycleTests.AddModelAsync(db, clock, LearningCycleTests.Always(0.5), ModelStatuses.Challenger);
|
||||||
|
var today = Zones.DayIn(clock.UtcNow, Zones.Rome);
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 120; i++)
|
||||||
|
{
|
||||||
|
var day = today.AddDays(-30 + (i % 28));
|
||||||
|
var win = i % 2 == 0;
|
||||||
|
var id = (await LearningStore.AddAsync(s, clock, new Example(Guid.Empty, StrategyNames.CryptoTrend, "C" + i, CaseSources.Live, day, clock.UtcNow.AddDays(-30 + (i % 28)), "trend_entry", 0.2m, null,
|
||||||
|
null, new Dictionary<string, double> { [Clues.Strength] = 0.5 })
|
||||||
|
{ Stage = StrategyStages.Simulation, Label = new CaseLabel(win, win ? 0.02 : -0.02, day, day.AddDays(1), "x") }, _none))!.Value;
|
||||||
|
await ModelStore.AddPredictionAsync(s, clock, new PredictionRow(id, first.Id, win ? 0.47 : 0.33, 0.4, 1, true), _none);
|
||||||
|
await ModelStore.AddPredictionAsync(s, clock, new PredictionRow(id, second.Id, win ? 0.61 : 0.22, 0.4, 1, false), _none);
|
||||||
|
}
|
||||||
|
|
||||||
|
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { Health = new HealthCheck { At = clock.UtcNow, Precision = 1, Cases = 60 } }, _none);
|
||||||
|
}, _none);
|
||||||
|
var page = await server.TextAsync("/apprendimento");
|
||||||
|
HasAll(page, "<strong>120</strong> <span class=\"muted\">su 300 necessari</span>", "Sfidante, versione 2", "120 su 100", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto. Si decide ",
|
||||||
|
"Prossima verifica dello sfidante", "Al ritmo attuale, tra", "tra 45% e 50%", "Precisione sugli ultimi 60 casi: 100%, sopra il", "Nessun allarme finora", "Nessuna anomalia");
|
||||||
|
Assert.IsFalse(page.Contains("Per ora sono i casi storici", StringComparison.Ordinal), "the live bands count now");
|
||||||
|
Assert.IsFalse(page.Contains("Annulla l'ultima promozione", StringComparison.Ordinal));
|
||||||
|
|
||||||
|
// Promoted, then taken back with one click, once.
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, first.Id, ModelStatuses.Retired, _none);
|
||||||
|
await ModelStore.SetStatusAsync(s, clock, second.Id, ModelStatuses.Champion, _none);
|
||||||
|
await ModelStore.SetReplacedAsync(s, clock, second.Id, first.Id, _none);
|
||||||
|
}, _none);
|
||||||
|
HasAll(await server.TextAsync("/apprendimento"), "Annulla l'ultima promozione", "Tornerebbe in carica la versione 1.", "In carica, versione 2");
|
||||||
|
HasAll(await server.TextAsync("/impostazioni"), "Tornerebbe in carica la versione 1.");
|
||||||
|
using (var undo = await server.PostFormAsync("/impostazioni", "/azioni/modello/annulla-promozione", ("ritorno", "/impostazioni")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?ok=promozione#modello", ServerHarness.Location(undo));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(first.Id, (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!.Id);
|
||||||
|
HasAll(await server.TextAsync("/apprendimento"), "In carica, versione 1", "Promozione annullata da te: torna in carica la versione 1 al posto della 2.");
|
||||||
|
using var again = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
|
||||||
|
Assert.AreEqual("/apprendimento?errore=promozione", ServerHarness.Location(again));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SPEC 13.5, 12.4: the thresholds and the set-aside from Impostazioni; shrinking less needs the phrase with real money.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheModelSettingsAreSavedAndGuardedWithRealMoney()
|
||||||
|
{
|
||||||
|
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
||||||
|
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||||
|
await using var keep = postgres;
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", env, marketHttp: network, trading: true);
|
||||||
|
var password = await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
async Task<string> ValueAsync(SettingDefinition d) => (await services.Settings.GetAsync(d.Key, _none)).Value;
|
||||||
|
async Task PostAsync(string expected, params (string, string)[] fields)
|
||||||
|
{
|
||||||
|
using var post = await server.PostFormAsync("/impostazioni", "/azioni/modello", fields);
|
||||||
|
Assert.AreEqual("/impostazioni?" + expected + "#modello", ServerHarness.Location(post));
|
||||||
|
}
|
||||||
|
|
||||||
|
HasAll(await server.TextAsync("/impostazioni"), "Acquisto intero fino a", "Nessun acquisto da", "10 punti sotto", "Al suo posto");
|
||||||
|
await PostAsync("ok=apprendimento", (LearningSettings.Full.Key, "2"), (LearningSettings.Zero.Key, "15"), (LearningSettings.Aside.Key, "on"));
|
||||||
|
Assert.AreEqual(("2", "15", "on"), (await ValueAsync(LearningSettings.Full), await ValueAsync(LearningSettings.Zero), await ValueAsync(LearningSettings.Aside)));
|
||||||
|
HasAll(await server.TextAsync("/impostazioni?ok=apprendimento"), "Impostazioni del modello salvate", "Messo da parte: non conta");
|
||||||
|
await PostAsync("errore=impostazione", (LearningSettings.Full.Key, "0"), (LearningSettings.Zero.Key, "1"));
|
||||||
|
Assert.AreEqual("2", await ValueAsync(LearningSettings.Full), "nothing of a wrong form is saved");
|
||||||
|
|
||||||
|
// Not through the API, nor through the form of the other settings.
|
||||||
|
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
|
||||||
|
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + LearningSettings.Zero.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "20" }) })
|
||||||
|
{
|
||||||
|
request.Headers.Add(csrf!["header"], csrf["token"]);
|
||||||
|
using var put = await server.Http.SendAsync(request);
|
||||||
|
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var other = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + LearningSettings.Zero.Key, ("valore", "20")))
|
||||||
|
{
|
||||||
|
StringAssert.Contains(ServerHarness.Location(other), "errore=impostazione");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("15", await ValueAsync(LearningSettings.Zero));
|
||||||
|
|
||||||
|
// With real money: more shrinking is free, less is not.
|
||||||
|
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", _none, ("s", StrategyNames.CryptoTrend)), _none);
|
||||||
|
HasAll(await server.TextAsync("/impostazioni"), "per rimpicciolire meno, o mettere da parte il modello, servono la frase e la password");
|
||||||
|
await PostAsync("ok=apprendimento", (LearningSettings.Zero.Key, "10"), (LearningSettings.Aside.Key, "off"));
|
||||||
|
await PostAsync("errore=frase-rischio", (LearningSettings.Zero.Key, "15"));
|
||||||
|
await PostAsync("errore=frase-rischio", (LearningSettings.Full.Key, "5"));
|
||||||
|
await PostAsync("errore=frase-rischio", (LearningSettings.Aside.Key, "on"));
|
||||||
|
Assert.AreEqual(("2", "10", "off"), (await ValueAsync(LearningSettings.Full), await ValueAsync(LearningSettings.Zero), await ValueAsync(LearningSettings.Aside)));
|
||||||
|
await PostAsync("ok=apprendimento", (LearningSettings.Aside.Key, "on"), ("frase", StageBook.RaisePhrase), ("password", password));
|
||||||
|
Assert.AreEqual("on", await ValueAsync(LearningSettings.Aside));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The sentences ------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static ModelRow Row(string status, int version, int examples = 500, Guid? replaced = null, IReadOnlyList<ClueWeight>? weights = null, double? gainWithout = null) => new(Guid.NewGuid(), version,
|
||||||
|
LearnerNames.Logistic, status, "test", Now.AddDays(-5), examples, 0, replaced, LearningCycleTests.Always(0.4), new ModelReport
|
||||||
|
{
|
||||||
|
Examples = examples,
|
||||||
|
Attempts = [new Attempt(LearnerNames.Logistic, new Scores(), new Scores { Cases = 100, Precision = 0.56, Brier = 0.2412, GainWith = 7.9, GainWithout = gainWithout ?? 5.84 }, true)],
|
||||||
|
Weights = weights ?? [],
|
||||||
|
});
|
||||||
|
|
||||||
|
private static LearningView View(CycleState state, bool aside = false, IReadOnlyList<SeenEstimate>? estimates = null, IReadOnlyList<ModelEvent>? events = null, params ModelRow[] models) =>
|
||||||
|
LearningView.Of(new LearningSnapshot([], estimates ?? [], models, state), Rates, Capitals, aside, new DiscoverySet(), events ?? [], Now);
|
||||||
|
|
||||||
|
private static SeenEstimate Seen(Guid model, int daysAgo, bool win, double probability, bool inCharge = true, double multiplier = 1)
|
||||||
|
{
|
||||||
|
var day = Zones.DayIn(Now, Zones.Rome).AddDays(-daysAgo);
|
||||||
|
return new SeenEstimate(model, inCharge, new Estimate(new Example(Guid.NewGuid(), StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.Live, day, Now, "x", 0.2m, null, null,
|
||||||
|
new Dictionary<string, double> { [Clues.Strength] = 0.5 })
|
||||||
|
{ Stage = StrategyStages.Simulation, Label = new CaseLabel(win, win ? 0.02 : -0.02, day, day, "x") }, probability, 0.4, multiplier));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheStateSaysWhetherTheModelCounts()
|
||||||
|
{
|
||||||
|
var champion = Row(ModelStatuses.Champion, 1);
|
||||||
|
Assert.AreEqual(LearningStates.None, View(new CycleState()).Summary.State);
|
||||||
|
Assert.AreEqual(LearningStates.Observation, View(new CycleState(), models: champion).Summary.State);
|
||||||
|
var active = View(new CycleState { ActivatedAt = Now.AddDays(-2) }, models: champion);
|
||||||
|
Assert.AreEqual(LearningStates.Active, active.Summary.State);
|
||||||
|
StringAssert.Contains(active.Text, "Dal 7 ottobre le sue stime contano");
|
||||||
|
Assert.IsNull(active.Pace);
|
||||||
|
|
||||||
|
var health = new HealthCheck { At = Now.AddHours(-5), Precision = 0.45, Cases = 41, Aside = AsideCodes.Precision };
|
||||||
|
var alarm = new[] { new ModelEvent(ModelEvents.SetAside, 1, "Allarme", Now.AddDays(-1)) };
|
||||||
|
var aside = View(new CycleState { ActivatedAt = Now.AddDays(-20), Aside = AsideCodes.Precision, AsideAt = Now.AddDays(-1), Health = health }, events: alarm, models: champion);
|
||||||
|
Assert.AreEqual(LearningStates.Aside, aside.Summary.State);
|
||||||
|
StringAssert.Contains(aside.Text, "Precisione scesa al 45% su 41 casi. Le strategie proseguono senza di lui.");
|
||||||
|
Assert.IsTrue(aside.Anomaly);
|
||||||
|
Assert.IsTrue(aside.Checks.Any(c => c is { State: "warn", Text: "Precisione sugli ultimi 41 casi: 45%, sotto il 56% atteso" }));
|
||||||
|
Assert.IsTrue(aside.Checks.Any(c => c.Text.EndsWith("Ultimo allarme il 8 ottobre, ancora in corso", StringComparison.Ordinal)), string.Join('|', aside.Checks));
|
||||||
|
|
||||||
|
// The user's own set-aside wins over everything, even over an alarm.
|
||||||
|
Assert.AreEqual(LearningStates.Manual, View(new CycleState { Aside = AsideCodes.Precision, ActivatedAt = Now }, aside: true, models: champion).Summary.State);
|
||||||
|
Assert.AreEqual("Hai messo da parte il modello: le strategie proseguono senza di lui.", View(new CycleState(), aside: true, models: champion).Summary.Sentence);
|
||||||
|
|
||||||
|
// Back after three days.
|
||||||
|
var back = View(new CycleState { Health = health with { Aside = null, Precision = 0.55 } },
|
||||||
|
events: [new ModelEvent(ModelEvents.SetAside, 1, "a", Now.AddDays(-20)), new ModelEvent(ModelEvents.Back, 1, "b", Now.AddDays(-17))], models: champion);
|
||||||
|
StringAssert.EndsWith(back.Checks[^1].Text, "Ultimo controllo oggi alle 03:21. Ultimo allarme il 19 settembre, rientrato in 3 giorni");
|
||||||
|
Assert.AreEqual("wait", back.Checks[0].State, "too few live signals to compare the market");
|
||||||
|
|
||||||
|
// A check of another version says nothing of the one in charge now.
|
||||||
|
var changed = View(new CycleState { Health = health with { Version = 7 } }, models: champion);
|
||||||
|
StringAssert.StartsWith(changed.Checks.Single().Text, "Il modello in carica è cambiato: il primo controllo è alle 03:00.");
|
||||||
|
Assert.IsTrue(View(new CycleState { Health = health with { DriftingClues = ["Volumi scambiati"] } }, models: champion).Checks[0] is { State: "warn" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>With 300 signals it still says what is missing; the count is of the system, not of the version.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheProgressSaysWhatIsMissing()
|
||||||
|
{
|
||||||
|
var (retired, champion) = (Row(ModelStatuses.Retired, 1), Row(ModelStatuses.Champion, 2));
|
||||||
|
List<SeenEstimate> Estimates(int count, double said) => [.. Enumerable.Range(0, count).Select(i => Seen(i % 2 == 0 ? retired.Id : champion.Id, 1 + (i % 28), i % 5 < 2, said))];
|
||||||
|
var some = View(new CycleState(), estimates: Estimates(212, 0.41), models: [retired, champion]);
|
||||||
|
Assert.AreEqual(212, some.Summary.Signals);
|
||||||
|
Assert.AreEqual("Al ritmo attuale, tra una e due settimane.", some.Pace);
|
||||||
|
Assert.HasCount(0, some.Missing);
|
||||||
|
|
||||||
|
var full = View(new CycleState(), estimates: Estimates(300, 0.41), models: [retired, champion]);
|
||||||
|
Assert.AreEqual("Ha visto abbastanza casi, ma non decide ancora.", full.Title);
|
||||||
|
Assert.IsNull(full.Pace);
|
||||||
|
Assert.HasCount(1, full.Missing, "well calibrated, but no gain");
|
||||||
|
StringAssert.StartsWith(full.Missing[0], "Non è ancora provato");
|
||||||
|
var wrong = View(new CycleState(), estimates: Estimates(300, 0.62), models: [retired, champion]);
|
||||||
|
Assert.HasCount(2, wrong.Missing);
|
||||||
|
StringAssert.StartsWith(wrong.Missing[0], "Le probabilità non sono ancora ben tarate: sbagliano in media di 22,0 punti, il massimo è 5.");
|
||||||
|
|
||||||
|
Assert.AreEqual("È presto per dire quanto manca.", View(new CycleState(), estimates: [Seen(champion.Id, 3, true, 0.5)], models: champion).Pace);
|
||||||
|
Assert.AreEqual("Nelle ultime settimane nessun segnale si è concluso.", View(new CycleState(), estimates: [Seen(champion.Id, 60, true, 0.5)], models: champion).Pace);
|
||||||
|
Assert.AreEqual("Al ritmo attuale, meno di una settimana.", LearningView.PaceWords(0.4));
|
||||||
|
Assert.AreEqual("Al ritmo attuale, circa due settimane.", LearningView.PaceWords(2));
|
||||||
|
Assert.AreEqual("Al ritmo attuale, circa 5 mesi.", LearningView.PaceWords(20));
|
||||||
|
Assert.AreEqual("Al ritmo attuale, più di un anno.", LearningView.PaceWords(80));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What is shown as happened is counted, not weighed by maturation.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheBandsSayWhatReallyHappened()
|
||||||
|
{
|
||||||
|
var champion = Row(ModelStatuses.Champion, 1);
|
||||||
|
var view = View(new CycleState(), estimates: [.. Enumerable.Range(0, 20).Select(i => Seen(champion.Id, 3, i == 0, 0.41))], models: champion);
|
||||||
|
Assert.AreEqual(new LearningBand(40, 45, 20, 41, 5), view.Bands.Single());
|
||||||
|
Assert.IsFalse(view.BandsFromHistory);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the trade card says when the model would count but is set aside.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheTradeCardSaysWhyTheModelChangedNothing()
|
||||||
|
{
|
||||||
|
string Line(string tail) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":1" + tail + "}")!;
|
||||||
|
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":true"), ": era messo da parte, non ha cambiato la dimensione");
|
||||||
|
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":false"), ": solo osservazione, non ha cambiato la dimensione");
|
||||||
|
StringAssert.EndsWith(Line(",\"counts\":true,\"aside\":false"), ": taglia piena");
|
||||||
|
string Reduced(string applied) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":" + applied + "}")!;
|
||||||
|
StringAssert.EndsWith(Reduced("0.996"), ": acquisto ridotto al 99%");
|
||||||
|
StringAssert.EndsWith(Reduced("0.004"), ": acquisto ridotto al 1%");
|
||||||
|
StringAssert.EndsWith(Reduced("0"), ": acquisto non fatto");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheBandsUnderTwentyCasesAreSaidUnreliable()
|
||||||
|
{
|
||||||
|
static LearningBand B(int from, int cases, decimal observed) => new(from, from + 5, cases, from + 2.5m, observed);
|
||||||
|
Assert.IsTrue(B(40, 20, 41).Solid);
|
||||||
|
Assert.IsFalse(B(40, 19, 41).Solid);
|
||||||
|
Assert.AreEqual("Quando stima tra il 60 e il 65%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.",
|
||||||
|
LearningView.BandsWords([B(50, 61, 54), B(60, 25, 60), B(65, 14, 71)]));
|
||||||
|
Assert.AreEqual("Quando stima tra il 45 e il 50%, è andata bene il 20% delle volte: non è ancora ben tarato, in media sbaglia di 27,5 punti. Sotto il 45% ha visto solo un caso, troppo poco per contarci.",
|
||||||
|
LearningView.BandsWords([B(30, 1, 0), B(45, 30, 20)]));
|
||||||
|
StringAssert.EndsWith(LearningView.BandsWords([B(30, 30, 30), B(35, 3, 30), B(45, 30, 47)]), "Nelle fasce di mezzo con meno di 20 casi ha visto solo 3 casi, troppo pochi per contarci.");
|
||||||
|
Assert.AreEqual("Nessuna fascia ha ancora 20 casi: troppo pochi per contarci.", LearningView.BandsWords([B(30, 19, 30)]));
|
||||||
|
|
||||||
|
// The judge is the error of the criterion to start counting, as the rest of the page says it.
|
||||||
|
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 20)], 0.01), "è andata bene il 20% delle volte: è ben tarato.");
|
||||||
|
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 47)], 0.06), "non è ancora ben tarato, in media sbaglia di 6,0 punti.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The clues after the ninth are "Tutto il resto", the whole stays 100; the sentence about the news follows the numbers.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCluesAddUpToAHundred()
|
||||||
|
{
|
||||||
|
LearningView Of(params (string Name, int Share)[] weights) => View(new CycleState(), models: Row(ModelStatuses.Champion, 1, weights: [.. weights.Select(w => new ClueWeight(w.Name, w.Share))]));
|
||||||
|
var many = Of(("A", 20), ("B", 15), ("C", 12), ("D", 11), ("E", 10), ("F", 9), ("G", 8), ("H", 6), ("Paura o avidità", 5), ("Tono delle notizie, 3 giorni", 3), ("Numero di notizie", 1));
|
||||||
|
Assert.HasCount(10, many.Weights);
|
||||||
|
Assert.AreEqual(100, many.Weights.Sum(w => w.Share));
|
||||||
|
Assert.AreEqual(new LearningWeight("Tutto il resto", 4, true), many.Weights[^1]);
|
||||||
|
Assert.AreEqual("Le notizie contano, ma meno dei prezzi: insieme a paura e avidità pesano 9 su 100.", many.WeightsText);
|
||||||
|
Assert.AreEqual("Le notizie per ora non pesano; paura e avidità pesano 40 su 100.", Of(("A", 60), ("Paura o avidità", 40)).WeightsText);
|
||||||
|
Assert.AreEqual("Le notizie contano, più dei prezzi: insieme a paura e avidità pesano 60 su 100.", Of(("Notizia più grave", 60), ("A", 40)).WeightsText);
|
||||||
|
StringAssert.StartsWith(Of(("A", 100)).WeightsText, "Notizie, paura e avidità per ora non pesano");
|
||||||
|
StringAssert.StartsWith(Of(("A", 0)).WeightsText, "Su casi mai visti nessuna informazione");
|
||||||
|
Assert.HasCount(0, Of(("A", 0)).Weights);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The trial before and after the first threshold; the gain without the filter is said once when it is the same.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheTrialSaysWhereItIs()
|
||||||
|
{
|
||||||
|
var (champion, challenger) = (Row(ModelStatuses.Champion, 1), Row(ModelStatuses.Challenger, 2, 520, gainWithout: 6));
|
||||||
|
List<SeenEstimate> Pairs(int count, bool better) =>
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count).SelectMany(i =>
|
||||||
|
{
|
||||||
|
var one = Seen(champion.Id, 1 + (i % 20), i % 2 == 0, 0.5);
|
||||||
|
return new[] { one, new SeenEstimate(challenger.Id, false, one.Estimate with { Probability = (i % 2 == 0) == better ? 0.7 : 0.3 }) };
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
StringAssert.StartsWith(View(new CycleState(), models: [champion, challenger]).TrialText, "Non ha ancora casi di confronto: ne servono 100.");
|
||||||
|
var few = View(new CycleState(), estimates: Pairs(14, true), models: [champion, challenger]);
|
||||||
|
Assert.AreEqual((14, 100), (few.Pairs, few.PairsNeeded));
|
||||||
|
StringAssert.StartsWith(few.TrialText, "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100");
|
||||||
|
StringAssert.StartsWith(View(new CycleState(), estimates: Pairs(1, false), models: [champion, challenger]).TrialText, "Per ora non sembra meglio, e ha solo un caso di confronto su 100");
|
||||||
|
var more = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger]);
|
||||||
|
Assert.AreEqual((130, 100), (more.Pairs, more.PairsNeeded), "passed, and not judged yet");
|
||||||
|
StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide domenica 11 ottobre alle 03:00: prende il posto della 1 se");
|
||||||
|
var judged = View(new CycleState(), estimates: Pairs(130, false), models: [champion, challenger with { ThresholdDone = 100 }]);
|
||||||
|
Assert.AreEqual((130, 150), (judged.Pairs, judged.PairsNeeded));
|
||||||
|
StringAssert.StartsWith(judged.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide di nuovo a 150 casi:");
|
||||||
|
Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger with { ThresholdDone = 250 }]).PairsNeeded);
|
||||||
|
Assert.AreEqual((5.84m, 6m), (more.Champion!.GainWithout, more.Challenger!.GainWithout));
|
||||||
|
Assert.AreEqual((56, 0.241m, 7.9m, "4 ottobre"), (more.Champion.Precision, more.Champion.Error, more.Champion.Gain, more.Champion.Trained));
|
||||||
|
Assert.AreEqual("Nessuno sfidante in prova.", View(new CycleState(), models: champion).TrialTitle);
|
||||||
|
Assert.AreEqual(1, View(new CycleState(), models: [champion with { Status = ModelStatuses.Retired }, Row(ModelStatuses.Champion, 2, replaced: champion.Id)]).UndoTo);
|
||||||
|
Assert.IsNull(View(new CycleState(), models: [champion with { Status = ModelStatuses.Undone }, Row(ModelStatuses.Champion, 2, replaced: champion.Id)]).UndoTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The next night is the coming Sunday at 03:00 in Rome, across the change of hour and the year.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheNextCheckIsTheComingSunday()
|
||||||
|
{
|
||||||
|
string Next(DateTimeOffset at, params ModelRow[] models) => LearningView.Of(new LearningSnapshot([], [], models, new CycleState()), Rates, Capitals, false, new DiscoverySet(), [], at).Summary.NextCheck;
|
||||||
|
var champion = Row(ModelStatuses.Champion, 1);
|
||||||
|
Assert.AreEqual("domenica 11 ottobre, 03:00", Next(Now, champion));
|
||||||
|
Assert.AreEqual("domenica 11 ottobre, 03:00", Next(new DateTimeOffset(2026, 10, 11, 0, 59, 0, TimeSpan.Zero), champion), "02:59 in Rome");
|
||||||
|
Assert.AreEqual("domenica 18 ottobre, 03:00", Next(new DateTimeOffset(2026, 10, 11, 1, 1, 0, TimeSpan.Zero), champion));
|
||||||
|
Assert.AreEqual("domenica 3 gennaio, 03:00", Next(new DateTimeOffset(2026, 12, 30, 9, 0, 0, TimeSpan.Zero), champion));
|
||||||
|
Assert.AreEqual("sabato 10 ottobre, 03:00", Next(Now), "before the first model any night will do");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -110,9 +110,23 @@ internal sealed class LiveRig : IAsyncDisposable
|
|||||||
{
|
{
|
||||||
AccountReady = _ => AccountStarted,
|
AccountReady = _ => AccountStarted,
|
||||||
Gate = Gate,
|
Gate = Gate,
|
||||||
|
Learning = Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock) { First = First },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Anubis.Learning.LearningDesk Learning { get; private set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>The first model and the base rates the engine starts from.</summary>
|
||||||
|
public Anubis.Learning.FirstModelFile? First { get; private set; } = Anubis.Learning.FirstModel.Embedded;
|
||||||
|
|
||||||
|
/// <summary>The engine again, with other base rates.</summary>
|
||||||
|
public void UseFirst(Anubis.Learning.FirstModelFile? first)
|
||||||
|
{
|
||||||
|
First = first;
|
||||||
|
Engine.Dispose();
|
||||||
|
Build();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The rules of SPEC 10.5 the engine applies to purchases and stops; none unless a test sets them.</summary>
|
/// <summary>The rules of SPEC 10.5 the engine applies to purchases and stops; none unless a test sets them.</summary>
|
||||||
public News.IEntryGate? Gate { get; private set; }
|
public News.IEntryGate? Gate { get; private set; }
|
||||||
|
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ public sealed class OkxTests
|
|||||||
return socket;
|
return socket;
|
||||||
});
|
});
|
||||||
|
|
||||||
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(60));
|
||||||
var reading = Task.Run(async () =>
|
var reading = Task.Run(async () =>
|
||||||
{
|
{
|
||||||
await foreach (var item in okx.StreamAsync(["BTC-EUR"], stop.Token).ConfigureAwait(false))
|
await foreach (var item in okx.StreamAsync(["BTC-EUR"], stop.Token).ConfigureAwait(false))
|
||||||
@@ -262,7 +262,7 @@ public sealed class OkxTests
|
|||||||
publicSocket.Push(ticker);
|
publicSocket.Push(ticker);
|
||||||
}
|
}
|
||||||
|
|
||||||
await reading.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
await reading.WaitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
|
||||||
Assert.IsTrue(sockets.All(s => s.Disposed));
|
Assert.IsTrue(sockets.All(s => s.Disposed));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ public sealed class OverviewScreenTests
|
|||||||
// A new installation: the screens say what is missing instead of showing numbers.
|
// A new installation: the screens say what is missing instead of showing numbers.
|
||||||
var home = await server.TextAsync("/");
|
var home = await server.TextAsync("/");
|
||||||
StringAssert.Contains(home, "La lettura delle notizie è spenta insieme ai dati di mercato.");
|
StringAssert.Contains(home, "La lettura delle notizie è spenta insieme ai dati di mercato.");
|
||||||
StringAssert.Contains(home, "L'apprendimento non è ancora attivo.");
|
StringAssert.Contains(home, "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.");
|
||||||
var diary = await server.TextAsync("/diario");
|
var diary = await server.TextAsync("/diario");
|
||||||
StringAssert.Contains(diary, "Come sta il sistema");
|
StringAssert.Contains(diary, "Come sta il sistema");
|
||||||
StringAssert.Contains(diary, "non configurato");
|
StringAssert.Contains(diary, "non configurato");
|
||||||
|
|||||||
@@ -178,16 +178,37 @@ internal sealed class TestDb : IAsyncDisposable
|
|||||||
ConnectTimeoutSeconds = 30,
|
ConnectTimeoutSeconds = 30,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Forced, a drop still waits only five seconds for the sessions it ends, and on a busy server an autovacuum can
|
||||||
|
/// take longer to leave ("is being accessed by other users"), or the answer can arrive late. That is the server,
|
||||||
|
/// not the code under test: the drop is tried again.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task DropAsync(string name)
|
||||||
|
{
|
||||||
|
for (var attempt = 1; ; attempt++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var admin = Anubis.Db.Database.Open(AdminSettings());
|
||||||
|
await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await using var command = connection.CreateCommand();
|
||||||
|
command.CommandText = $"DROP DATABASE IF EXISTS {name} WITH (FORCE)";
|
||||||
|
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
catch (Npgsql.NpgsqlException ex) when (attempt < 4 && (ex.IsTransient || ex.SqlState == Npgsql.PostgresErrorCodes.ObjectInUse))
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(attempt)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
await Db.DisposeAsync().ConfigureAwait(false);
|
await Db.DisposeAsync().ConfigureAwait(false);
|
||||||
if (_postgresName is not null)
|
if (_postgresName is not null)
|
||||||
{
|
{
|
||||||
await using var admin = Anubis.Db.Database.Open(AdminSettings());
|
await DropAsync(_postgresName).ConfigureAwait(false);
|
||||||
await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false);
|
|
||||||
await using var command = connection.CreateCommand();
|
|
||||||
command.CommandText = $"DROP DATABASE IF EXISTS {_postgresName} WITH (FORCE)";
|
|
||||||
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_folder is not null)
|
if (_folder is not null)
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ int Screenshots(string[] pages)
|
|||||||
|
|
||||||
var folder = Path.Combine(root, "artifacts", "screenshots");
|
var folder = Path.Combine(root, "artifacts", "screenshots");
|
||||||
Directory.CreateDirectory(folder);
|
Directory.CreateDirectory(folder);
|
||||||
var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/notizie", "/impostazioni"];
|
var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/notizie", "/apprendimento", "/impostazioni"];
|
||||||
using var shots = Shots.Start(browser);
|
using var shots = Shots.Start(browser);
|
||||||
foreach (var page in targets)
|
foreach (var page in targets)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user