Fase 8 — Apprendimento #109
No files matched your search
+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 |
|
||||
| `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.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.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 |
|
||||
|---|---|---|---|---|
|
||||
| `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 | — |
|
||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
||||
| `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` | — | 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. |
|
||||
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||
|
||||
## 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.
|
||||
- `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
|
||||
|
||||
## Carattere
|
||||
|
||||
+11
-11
@@ -239,20 +239,20 @@ Un modello che impara dall'esito dei segnali e può solo rimpicciolire le operaz
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#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
|
||||
- [ ] [#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
|
||||
- [ ] [#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] [#62](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/62) Archivio degli indizi "a una certa data" ed etichette
|
||||
- [x] [#63](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/63) Addestramento, convalida, calibrazione e registro dei modelli
|
||||
- [x] [#64](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/64) Ciclo continuo: modello in carica e sfidante, ombra, deriva, messa da parte
|
||||
- [x] [#65](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/65) Altri apprendimenti semplici: scostamento, impatto delle notizie, scoperte in chiaro
|
||||
- [x] [#66](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/66) Schermata Apprendimento; Impostazioni sul modello
|
||||
- [x] [#67](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/67) Chiusura della fase, revisione indipendente e tag `fase-8`
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] Un test dimostra che nessun indizio usa dati successivi alla decisione
|
||||
- [ ] Il primo modello è addestrato sugli esempi storici con rapporto di convalida
|
||||
- [ ] Il moltiplicatore non può superare 1 (test di proprietà)
|
||||
- [ ] Promozione, scarto e messa da parte sono coperti da test con dati sintetici
|
||||
- [ ] La schermata Apprendimento corrisponde al mockup
|
||||
- [x] Un test dimostra che nessun indizio usa dati successivi alla decisione (`NoClueUsesDataAfterTheDecision`, `NothingSavedOrDatedAfterTheDecisionIsRead`, `ADecisionRecoveredLateSeesOnlyWhatWasKnownWhenItWasDue`)
|
||||
- [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
|
||||
- [x] Il moltiplicatore non può superare 1 (test di proprietà: `TheMultiplierNeverExceedsOne`, `TheFilterNeverMakesAnOrderBigger`)
|
||||
- [x] Promozione, scarto e messa da parte sono coperti da test con dati sintetici (`AChallengerThatIsReallyBetterIsPromotedAtAThreshold`, `AChallengerThatIsNotBetterIsDiscardedAfterThreeHundredCases`, `ThePrecisionUnderHalfSetsTheModelAsideUntilItComesBack`, `ARisingErrorSetsTheModelAside`, `CluesNeverStudiedSetTheModelAside`)
|
||||
- [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
|
||||
|
||||
|
||||
+13
-4
@@ -4,7 +4,7 @@ Aggiornato: 2026-12-01
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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.
|
||||
- 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.
|
||||
- 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.
|
||||
- **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.
|
||||
@@ -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).
|
||||
- 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 della revisione indipendente (#67, ADR 0018 punto 17).
|
||||
|
||||
## In corso
|
||||
|
||||
Nulla.
|
||||
@@ -121,14 +129,14 @@ Nulla.
|
||||
## 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.
|
||||
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.
|
||||
|
||||
## Da sapere
|
||||
|
||||
- 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 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.
|
||||
- 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.
|
||||
@@ -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.
|
||||
- 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).
|
||||
- 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.
|
||||
- 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).
|
||||
|
||||
@@ -32,7 +32,7 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
|
||||
|
||||
**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. Un punteggio che fuori campione non dice niente, o dice il contrario, diventa la frequenza di base.
|
||||
- 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`.
|
||||
@@ -44,12 +44,13 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
|
||||
**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. Nessuno dei tre modelli fa meglio di chi risponde sempre la frequenza di base (log-loss 0,494 contro 0,481 nelle combinazioni); il guadagno medio per operazione proposta passa da +1,69 a +1,76 euro, differenza che non vale niente. Resta in osservazione come tutti i modelli; i criteri di 11.5 lo fermano se non impara altro.
|
||||
- **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.
|
||||
- Un guasto del modello lascia le intenzioni com'erano e finisce nel registro tecnico.
|
||||
- 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.
|
||||
@@ -81,3 +82,16 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
|
||||
- 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.
|
||||
@@ -1 +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":[-3.950815298593455,-2.295424845384458,-1.9151100659396874,-1.7663451007315563,-1.7294273092893189,-1.6834534361695037,-1.6486334946177699,-1.2851328574592205,-0.12266591732662607,0.08702724987460952],"Values":[0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.6666666666666667]},"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.5039820727635489,"BaseLogLoss":0.47884194965218496,"Brier":0.15907636401310338,"Precision":0.49573711063372716,"GainWithout":1.7619015934416593,"GainWith":1.3671192662708858,"Improvement":-0.39478232717077355,"CalibrationError":0.08995233818515404,"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":240,"Estimated":0.17557548247994598,"Observed":0.15444000663544563},{"From":0.2,"To":0.25,"Cases":180,"Estimated":0.2232734796319761,"Observed":0.12922452472685167},{"From":0.25,"To":0.3,"Cases":291,"Estimated":0.25353021765415845,"Observed":0.1822752256443538},{"From":0.3,"To":0.35,"Cases":260,"Estimated":0.33272092703111206,"Observed":0.1947431154393129},{"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.49132446909272104,"BaseLogLoss":0.4806696575091626,"Brier":0.15507682960514105,"Precision":0.5230360608846665,"GainWithout":1.6880808292523108,"GainWith":1.6479770415699562,"Improvement":-0.040103787682354675,"CalibrationError":0.043970436437853075,"Bands":[{"From":0.05,"To":0.1,"Cases":189,"Estimated":0.08358931699861316,"Observed":0.15873015873015872},{"From":0.1,"To":0.15,"Cases":1511,"Estimated":0.13511708396610708,"Observed":0.19324950363997354},{"From":0.15,"To":0.2,"Cases":3905,"Estimated":0.1754909013303589,"Observed":0.18053777208706787},{"From":0.2,"To":0.25,"Cases":1563,"Estimated":0.2136126207759515,"Observed":0.19897632757517594},{"From":0.25,"To":0.3,"Cases":1051,"Estimated":0.26208823479755566,"Observed":0.16079923882017128},{"From":0.3,"To":0.35,"Cases":788,"Estimated":0.3288561548679041,"Observed":0.1700507614213198},{"From":0.35,"To":0.4,"Cases":102,"Estimated":0.3735783374752225,"Observed":0.22549019607843138},{"From":0.4,"To":0.45,"Cases":48,"Estimated":0.42372393439600436,"Observed":0.2916666666666667},{"From":0.45,"To":0.5,"Cases":28,"Estimated":0.47168117170804486,"Observed":0.25},{"From":0.5,"To":0.55,"Cases":15,"Estimated":0.5189195543992838,"Observed":0.13333333333333333},{"From":0.55,"To":0.6,"Cases":8,"Estimated":0.574330374974163,"Observed":0.125},{"From":0.6,"To":0.65,"Cases":3,"Estimated":0.6261332225482069,"Observed":0},{"From":0.65,"To":0.7,"Cases":9,"Estimated":0.6659045693196883,"Observed":0.2222222222222222}]},"Chosen":false},{"Learner":"logistic","Forward":{"Cases":1107,"LogLoss":0.49501524768221683,"BaseLogLoss":0.47884194965218496,"Brier":0.15713196527346796,"Precision":0.5181989063568011,"GainWithout":1.7619015934416593,"GainWLine truncated
|
||||
{"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
|
||||
@@ -24,28 +24,28 @@ Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si
|
||||
|
||||
| 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,5040 | 0,4788 | 0,1591 | 49,6% | +1,76 € | +1,37 € |
|
||||
| Alberi potenziati | a combinazioni | 9220 | 0,4913 | 0,4807 | 0,1551 | 52,3% | +1,69 € | +1,65 € |
|
||||
| Regressione logistica (scelto) | in avanti | 1107 | 0,4950 | 0,4788 | 0,1571 | 51,8% | +1,76 € | +1,78 € |
|
||||
| Regressione logistica (scelto) | a combinazioni | 9220 | 0,4938 | 0,4807 | 0,1560 | 53,4% | +1,69 € | +1,76 € |
|
||||
| Foresta casuale | in avanti | 1107 | 0,4960 | 0,4788 | 0,1569 | 50,2% | +1,76 € | +1,66 € |
|
||||
| Foresta casuale | a combinazioni | 9220 | 0,4909 | 0,4807 | 0,1547 | 52,2% | +1,69 € | +1,63 € |
|
||||
| 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 non sono migliori di chi risponde sempre la frequenza di base: su questo storico il modello non ha trovato niente di solido. Con il filtro il guadagno medio per operazione proposta cambia di +0,07 € nelle combinazioni e di +0,02 € in avanti.
|
||||
**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 |
|
||||
|---|---|
|
||||
| Forza della tendenza | 40 |
|
||||
| Quota di titoli in salita | 20 |
|
||||
| Giorno della settimana | 17 |
|
||||
| Agitazione recente dei prezzi | 14 |
|
||||
| Fase generale del mercato | 9 |
|
||||
| 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 |
|
||||
|
||||
@@ -53,24 +53,18 @@ Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizi
|
||||
|
||||
## Ci si può fidare delle probabilità?
|
||||
|
||||
Verifica a combinazioni, fasce da 5 punti. Contano le fasce con almeno 20 casi; errore medio 6,3 punti.
|
||||
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% | 13 | 3,6% | 30,8% |
|
||||
| 5–10% | 213 | 7,5% | 17,8% |
|
||||
| 10–15% | 1475 | 13,3% | 15,5% |
|
||||
| 15–20% | 2986 | 17,5% | 20,7% |
|
||||
| 20–25% | 793 | 22,1% | 19,7% |
|
||||
| 25–30% | 2412 | 25,6% | 17,5% |
|
||||
| 30–35% | 1275 | 33,3% | 16,5% |
|
||||
| 35–40% | 17 | 37,5% | 23,5% |
|
||||
| 40–45% | 9 | 42,3% | 33,3% |
|
||||
| 45–50% | 10 | 47,5% | 20,0% |
|
||||
| 50–55% | 9 | 50,5% | 22,2% |
|
||||
| 60–65% | 1 | 61,5% | 0,0% |
|
||||
| 65–70% | 1 | 66,7% | 100,0% |
|
||||
| 75–80% | 6 | 75,0% | 33,3% |
|
||||
| 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
|
||||
|
||||
|
||||
@@ -715,6 +715,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.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; }
|
||||
|
||||
@@ -33,9 +33,9 @@
|
||||
</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 @b.Cases casi</span></span>
|
||||
<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 below" style="left:@Pct(X(fullest.Estimated) / 10);top:@Pct(Y(fullest.Observed) / 10)">@Label(fullest)</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>
|
||||
@@ -62,7 +62,7 @@
|
||||
<tbody>
|
||||
@foreach (var b in Bands)
|
||||
{
|
||||
<tr><td>tra @(b.From)% e @(b.To)%</td><td class="num">@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>
|
||||
<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>
|
||||
@@ -78,7 +78,9 @@
|
||||
[Parameter]
|
||||
public string Text { get; set; } = "";
|
||||
|
||||
private static string Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {(b.Cases == 1 ? "un caso" : b.Cases + " casi")}";
|
||||
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);
|
||||
|
||||
|
||||
@@ -126,12 +126,16 @@ else if (Errore is not null)
|
||||
<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">@v.Pairs su @v.PairsNeeded</td></tr>
|
||||
<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)
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
"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-tolta" => "Chiave tolta.",
|
||||
"apprendimento" => "Impostazioni del modello salvate: valgono dalla prossima decisione.",
|
||||
"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.",
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
@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 (tra @Bp(c.LowBp) e @Bp(c.HighBp) al 95%).</span></p>
|
||||
<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>
|
||||
|
||||
@@ -111,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>
|
||||
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)
|
||||
{
|
||||
@@ -767,8 +768,8 @@ internal static partial class Forms
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6).</summary>
|
||||
private static async Task<IResult> DecideCostAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
/// <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"))
|
||||
{
|
||||
|
||||
@@ -112,6 +112,9 @@ internal sealed record LearningView
|
||||
|
||||
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; } = "";
|
||||
@@ -169,7 +172,7 @@ internal sealed record LearningView
|
||||
: 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" : Format.Day(DayOf(last.TrainedAt)),
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -213,7 +216,8 @@ internal sealed record LearningView
|
||||
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
|
||||
var (title, text) = Words(summary, state, now);
|
||||
|
||||
var live = activation.Scores.Bands;
|
||||
// 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();
|
||||
@@ -224,7 +228,7 @@ internal sealed record LearningView
|
||||
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" : $"{Format.Day(DayOf(last.TrainedAt))}, versione {last.Version}",
|
||||
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),
|
||||
BandsFromHistory = history && bands.Count > 0,
|
||||
@@ -239,6 +243,7 @@ internal sealed record LearningView
|
||||
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))],
|
||||
@@ -248,13 +253,15 @@ internal sealed record LearningView
|
||||
{
|
||||
view = view with
|
||||
{
|
||||
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Points(w.Precision)!.Value))],
|
||||
Checks = state.Health is { } health ? ChecksOf(health, snapshot, champion, verified, events, now) : [],
|
||||
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), champion.Version, challenger.Version)
|
||||
? 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.",
|
||||
@@ -274,7 +281,7 @@ internal sealed record LearningView
|
||||
$"{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. Si riattiva da Impostazioni."),
|
||||
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}"),
|
||||
@@ -363,7 +370,7 @@ internal sealed record LearningView
|
||||
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" : cases.ToString(_it) + " casi, troppo pochi")} per contarci.";
|
||||
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) : "");
|
||||
}
|
||||
@@ -380,6 +387,7 @@ internal sealed record LearningView
|
||||
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.";
|
||||
@@ -396,17 +404,17 @@ internal sealed record LearningView
|
||||
? 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);
|
||||
|
||||
private static LearningView WithTrial(LearningView view, TrialCheck check, int? champion, int? challenger)
|
||||
/// <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 > check.Pairs, TrialCheck.Thresholds[^1]);
|
||||
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, TrialCheck.Thresholds[^1]);
|
||||
var first = TrialCheck.Thresholds[0];
|
||||
var thresholds = string.Join(", ", TrialCheck.Thresholds.SkipLast(1)) + " e " + TrialCheck.Thresholds[^1];
|
||||
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. Si decide solo quando i casi superano {thresholds}: " +
|
||||
_ => $"{(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 };
|
||||
@@ -422,7 +430,7 @@ internal sealed record LearningView
|
||||
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(Points(health.Precision), health.Cases, Points(verified?.Precision)),
|
||||
PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)),
|
||||
};
|
||||
if (health.ErrorDrift)
|
||||
{
|
||||
@@ -500,7 +508,7 @@ internal sealed record LearningView
|
||||
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), champion.Version, challenger.Version);
|
||||
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 --------------------------------------------------------------------------------------------------
|
||||
@@ -536,6 +544,9 @@ internal sealed record LearningView
|
||||
|
||||
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);
|
||||
|
||||
|
||||
@@ -80,7 +80,8 @@ internal static class ReasonTexts
|
||||
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto";
|
||||
}
|
||||
|
||||
return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": solo osservazione, non ha cambiato la dimensione";
|
||||
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.
|
||||
|
||||
@@ -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,
|
||||
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(
|
||||
"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",
|
||||
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);
|
||||
return (e, d);
|
||||
|
||||
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
|
||||
var m = d.Any(x => x.Stage == DecisionStages.Model) ? [] : 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);
|
||||
|
||||
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
|
||||
@@ -193,6 +200,7 @@ internal sealed record TradesView(
|
||||
: 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? 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);
|
||||
List<WhyLine> bought = [.. Lines(buy.Key), .. earlier.SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
|
||||
return (bought, sold, entrySlip, exitSlip, code);
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,9 @@ public static class Clues
|
||||
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),
|
||||
@@ -175,12 +178,19 @@ public static class Clues
|
||||
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, 31) : 31);
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -160,7 +160,7 @@ public sealed class CostBook(Database db, IClock clock)
|
||||
"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 invece dei {current:0.0} previsti.");
|
||||
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);
|
||||
|
||||
@@ -166,7 +166,7 @@ public static class FirstModel
|
||||
Line($"");
|
||||
Line($"## Ci si può fidare delle probabilità?");
|
||||
Line($"");
|
||||
Line($"Verifica a combinazioni, fasce da 5 punti. Contano le fasce con almeno {Judge.BandMin} casi; errore medio {(report.Chosen!.Combined.CalibrationError is { } error ? error * 100 : 0):0.0} punti.");
|
||||
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($"|---|---|---|---|");
|
||||
@@ -186,7 +186,7 @@ public static class FirstModel
|
||||
{
|
||||
var (s, f) = (chosen.Combined, chosen.Forward);
|
||||
var probabilities = s.LogLoss < s.BaseLogLoss && f.LogLoss < f.BaseLogLoss
|
||||
? "Le stime sono migliori di chi risponde sempre la frequenza di base, in tutte e due le prove."
|
||||
? 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.";
|
||||
|
||||
@@ -13,6 +13,9 @@ 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; }
|
||||
|
||||
@@ -103,6 +106,10 @@ public static class Health
|
||||
/// <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.
|
||||
@@ -119,6 +126,7 @@ public static class Health
|
||||
return new HealthCheck
|
||||
{
|
||||
At = at,
|
||||
Version = champion.Version,
|
||||
Precision = precision,
|
||||
Cases = last.Count,
|
||||
ErrorDrift = error,
|
||||
|
||||
@@ -33,7 +33,9 @@ public sealed record Estimate(Example Case, double Probability, double BaseRate,
|
||||
public bool SaysWin => Probability >= BaseRate - 1e-9;
|
||||
}
|
||||
|
||||
/// <summary>A band of estimated probabilities and how often it went well.</summary>
|
||||
/// <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>
|
||||
@@ -153,12 +155,14 @@ public static class Judge
|
||||
{
|
||||
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), g.Count(),
|
||||
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);
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -653,8 +653,11 @@ public sealed record Calibration
|
||||
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; never exactly 0 or 1.</summary>
|
||||
public static Calibration Isotonic(IReadOnlyList<double> scores, IReadOnlyList<bool> wins)
|
||||
/// <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);
|
||||
@@ -670,11 +673,29 @@ public sealed record Calibration
|
||||
}
|
||||
}
|
||||
|
||||
// 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, 1.0 / (blocks[0].Count + 2), 1 - (1.0 / (blocks[^1].Count + 2))))],
|
||||
Values = [.. blocks.Select(b => Math.Clamp(b.Wins / b.Count, edge, 1 - edge))],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,8 @@ using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Learning;
|
||||
|
||||
/// <summary>What the labels of a strategy need: the collected bars, through which closed day, its rules, the first report after a day.</summary>
|
||||
public sealed record LabelData(BacktestDataset Data, DateOnly Through, Func<IStrategy> Create)
|
||||
{
|
||||
public Func<DateOnly, CancellationToken, Task<IReadOnlyDictionary<string, DateOnly>?>>? Earnings { get; init; }
|
||||
}
|
||||
/// <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)
|
||||
@@ -58,21 +55,45 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await desk.PrepareHistoryAsync(cancellationToken).ConfigureAwait(false);
|
||||
await LabelAsync(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();
|
||||
if (await dataOf(group.Key, open, cancellationToken).ConfigureAwait(false) is not { } source)
|
||||
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;
|
||||
}
|
||||
@@ -85,17 +106,17 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
|
||||
continue;
|
||||
}
|
||||
|
||||
DateOnly? report = null;
|
||||
if (example.Strategy == StrategyNames.EquityMeanrev && source.Earnings is not null
|
||||
&& await source.Earnings(example.Day, cancellationToken).ConfigureAwait(false) is { } next && next.TryGetValue(example.Symbol, out var date))
|
||||
try
|
||||
{
|
||||
report = date;
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
if (CaseLabels.Of(example, source.Create, source.Data, source.Through, earnings: report) is { } label)
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
await desk.Store.AddLabelAsync(example.Id, label, cancellationToken).ConfigureAwait(false);
|
||||
made++;
|
||||
failed.Add(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,7 +181,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
|
||||
ArgumentNullException.ThrowIfNull(health);
|
||||
return reason switch
|
||||
{
|
||||
AsideCodes.Precision => string.Create(It, $"Precisione scesa al {(health.Precision ?? 0) * 100:0}% su {health.Cases} casi."),
|
||||
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.",
|
||||
|
||||
@@ -48,7 +48,12 @@ public sealed record ModelEstimate(ModelRow Row, double Probability, double Base
|
||||
/// <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>Without a model, or without a base rate for the strategy, there is no estimate (ADR 0018).</summary>
|
||||
/// <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);
|
||||
@@ -60,7 +65,7 @@ public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, Multipl
|
||||
var estimates = new List<ModelEstimate>();
|
||||
foreach (var (row, inCharge) in new[] { (Champion, true), (Challenger, false) })
|
||||
{
|
||||
if (row?.Model is { } model && model.Probability(example.Features) is var probability && double.IsFinite(probability))
|
||||
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));
|
||||
@@ -111,18 +116,25 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
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)
|
||||
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, clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
@@ -132,6 +144,13 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
}, 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)
|
||||
@@ -139,12 +158,20 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
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);
|
||||
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 it could not be prepared.</summary>
|
||||
public async Task<LearningTurn?> PrepareAsync(string strategy, string stage, DateOnly day, BacktestDataset data, Func<IStrategy> create, IReadOnlyDictionary<string, DateOnly>? earnings,
|
||||
CancellationToken cancellationToken)
|
||||
/// <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);
|
||||
@@ -153,28 +180,41 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
async Task<T> OrAsync<T>(Func<Task<T>> read, Func<Task<T>> otherwise)
|
||||
{
|
||||
var live = await Store.LiveAsync(strategy, cancellationToken).ConfigureAwait(false);
|
||||
for (var i = 0; i < live.Count; i++)
|
||||
try
|
||||
{
|
||||
// The operation of the example may have closed with the bars of today, before the nightly labels.
|
||||
if (live[i].Label is null && !SingleOperation.NeedsUniverse(strategy) && data[live[i].Symbol] is { } instrument && instrument.IndexOf(live[i].Day) >= 0
|
||||
&& CaseLabels.Of(live[i], create, data, day) is { } label)
|
||||
{
|
||||
live[i] = live[i] with { Label = label };
|
||||
}
|
||||
return await read().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogFailed(_logger, ex, strategy);
|
||||
return await otherwise().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||
var outside = await _outside.ReadAsync(clock.UtcNow, specs, earnings, cancellationToken).ConfigureAwait(false);
|
||||
return new LearningTurn(strategy, stage, day, live, outside, await GateAsync(cancellationToken).ConfigureAwait(false), clock, ex => LogFailed(_logger, ex, strategy));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
|
||||
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)
|
||||
{
|
||||
LogFailed(_logger, ex, strategy);
|
||||
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}")]
|
||||
@@ -277,8 +317,10 @@ public sealed class LearningTurn
|
||||
return AppliedTo(made);
|
||||
}
|
||||
|
||||
// The operation was born with the latest example before this day: without one the model had nothing to say.
|
||||
return _live[symbol].LastOrDefault(e => e.Day <= context.Day)?.Multiplier ?? 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)
|
||||
@@ -293,8 +335,28 @@ public sealed class LearningTurn
|
||||
|
||||
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.</summary>
|
||||
/// <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)
|
||||
{
|
||||
@@ -332,6 +394,7 @@ public sealed class LearningTurn
|
||||
["applied"] = applied,
|
||||
["version"] = estimate.Row.Version,
|
||||
["counts"] = _gate.Counts,
|
||||
["aside"] = _gate.Aside,
|
||||
}, now), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,16 @@ public sealed class LearningStore(Database db, IClock clock)
|
||||
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);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Anubis.Backtest;
|
||||
@@ -498,7 +499,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
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, data, () => CreateStrategy(m.Strategy, stage.Qualification?.Parameters), await EarningsOfAsync(m, cancellationToken)
|
||||
: 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)
|
||||
{
|
||||
@@ -795,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 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)
|
||||
{
|
||||
@@ -1337,10 +1339,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
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))
|
||||
{
|
||||
Earnings = Earnings is null ? null : async (day, ct) => (await Earnings(day, ct).ConfigureAwait(false))?.Next,
|
||||
};
|
||||
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.
|
||||
|
||||
@@ -36,7 +36,7 @@ public static class ReasonCatalog
|
||||
["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.",
|
||||
["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.",
|
||||
["model_filter"] = "Il modello dava a questa operazione meno probabilità del solito: acquisto rimpicciolito o non fatto.",
|
||||
// News and calendar (SPEC 10.5).
|
||||
["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.",
|
||||
|
||||
@@ -546,10 +546,10 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The night of the model: once, however long the absence (SPEC 5.6), and beside the others because it is long.</summary>
|
||||
/// <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.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650), Beside = true };
|
||||
{ MaxLateness = TimeSpan.FromDays(3650), CatchUpWithin = TimeSpan.FromDays(3650), Beside = true };
|
||||
|
||||
public IReadOnlyList<ScheduledJob> Jobs() =>
|
||||
[
|
||||
|
||||
@@ -98,6 +98,18 @@ public sealed class LaboratoryScreenTests
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
@@ -16,7 +16,7 @@ public sealed class LearningCycleTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
|
||||
private static readonly DateOnly From = new(2026, 6, 1);
|
||||
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()
|
||||
|
||||
@@ -148,7 +148,7 @@ public sealed class LearningModelTests
|
||||
[TestMethod]
|
||||
public void IsotonicNeverGoesDown()
|
||||
{
|
||||
var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true]);
|
||||
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();
|
||||
|
||||
@@ -86,7 +86,7 @@ public sealed class LearningMoreTests
|
||||
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 invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.",
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
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)));
|
||||
}
|
||||
|
||||
[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 }));
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,19 @@ public sealed class LearningScreenTests
|
||||
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%)");
|
||||
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"));
|
||||
@@ -118,7 +131,7 @@ public sealed class LearningScreenTests
|
||||
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 150", "La versione 2 è ancora in prova.", "Sembra un po' meglio su 120 casi di confronto.",
|
||||
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));
|
||||
@@ -247,6 +260,10 @@ public sealed class LearningScreenTests
|
||||
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" });
|
||||
}
|
||||
|
||||
@@ -279,6 +296,28 @@ public sealed class LearningScreenTests
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
@@ -333,9 +372,12 @@ public sealed class LearningScreenTests
|
||||
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, 150), (more.Pairs, more.PairsNeeded));
|
||||
StringAssert.StartsWith(more.TrialText, "Per ora non sembra meglio su 130 casi di confronto. Si decide solo quando i casi superano 100, 150, 200, 250 e 300");
|
||||
Assert.AreEqual(300, View(new CycleState(), estimates: Pairs(320, false), models: [champion, challenger]).PairsNeeded);
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user