From 501c9be70e74c73f5f1a62e052d1247b851eee13 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Thu, 3 Dec 2026 22:59:16 +0100 Subject: [PATCH] Phase 11: decisions from the numbers only, outside rules measured in the shadow News, the economic calendar and earnings dates no longer change any decision by default (ADR 0023). A new switch, decisions.external_rules, chooses between "misurate" (default) and "attive" (the Phase 7 behaviour); ADR 0027 records every choice. - Engine: with "misurate" nothing is held, postponed or kept, no diary or note is written and equity_meanrev gets no earnings dates. The gate is still asked, per rule and with all rows on, to write one shadow case per rule, strategy, instrument and day. The switch is read once per decision; the one-step check and the release of a planned order read it as it was when the decision ran. - Shadow: five rules measured with the existing improvement machinery, 99% interval, "too early" under six months, the ADR 0023 criterion; the earnings exit is measured by relabelling with the report date. Shown in the Laboratorio and in the quarterly review beside the historical restriction balance. - Model: the seven outside clues stay out of training; a champion that uses one is set aside at once, without an alarm, and Sunday trains one without them. - Settings: the switch changes only from the settings form, with the protections of the five rows; the API refuses it; each change writes one diary line. The first start of this version records "attive" until then on an installation that had already decided. - Screens, demo and manual follow "misurate". Two independent review rounds; their confirmed findings are fixed and tested. SQLite, PostgreSQL and the image with the guard drill are green. refs #116, refs #117 Co-Authored-By: Claude Opus 5.5 --- docs/MANUALE.md | 16 +- docs/ROADMAP.md | 20 +- docs/STATE.md | 15 +- docs/adr/0023-decisioni-solo-matematiche.md | 4 +- docs/adr/0027-scelte-fase-11.md | 85 ++++ src/Anubis.Server/AnubisHost.cs | 8 +- src/Anubis.Server/Assets/app.css | 2 + .../Components/Pages/Apprendimento.razor | 4 +- .../Components/Pages/Impostazioni.razor | 56 ++- .../Components/Pages/Laboratorio.razor | 14 + .../Components/Pages/Notizie.razor | 28 +- .../Components/Pages/Rischio.razor | 10 +- .../Components/ReviewReportView.razor | 34 +- .../Components/ShadowRulesTable.razor | 30 ++ src/Anubis.Server/Endpoints.cs | 2 +- src/Anubis.Server/Forms.cs | 42 +- src/Anubis.Server/LearningView.cs | 41 +- src/Anubis.Server/NewsView.cs | 30 +- src/Anubis.Server/PanoramaView.cs | 6 +- src/Anubis.Server/RiskView.cs | 4 + src/Anubis.Server/StrategiesView.cs | 7 +- src/Anubis/Backtest/QuarterlyReview.cs | 29 ++ src/Anubis/Core/Settings.cs | 38 +- src/Anubis/Demo/Data/aggregates.json | 6 +- src/Anubis/Demo/Data/journal.csv | 6 - src/Anubis/Learning/Clues.cs | 30 +- src/Anubis/Learning/LearningCycle.cs | 96 +++- src/Anubis/Learning/LearningDesk.cs | 84 +++- src/Anubis/Learning/ModelStore.cs | 8 + src/Anubis/Learning/Shadow.cs | 240 ++++++++- src/Anubis/Learning/Training.cs | 11 +- src/Anubis/News/ExternalRules.cs | 87 ++++ src/Anubis/News/NewsBoard.cs | 34 +- src/Anubis/News/NewsDesk.cs | 83 ++- src/Anubis/Strategies/EquityStrategies.cs | 22 +- src/Anubis/Trading/LiveEngine.cs | 122 ++++- src/Anubis/Trading/TradingService.cs | 1 + tests/Anubis.Tests/DatabaseTests.cs | 17 + tests/Anubis.Tests/LaboratoryScreenTests.cs | 2 +- tests/Anubis.Tests/LearningScreenTests.cs | 2 +- tests/Anubis.Tests/LiveStockSupport.cs | 18 + tests/Anubis.Tests/LiveSupport.cs | 12 + tests/Anubis.Tests/MeasuredRulesTests.cs | 472 ++++++++++++++++++ tests/Anubis.Tests/NewsAnalystTests.cs | 2 +- tests/Anubis.Tests/NewsScreenTests.cs | 16 +- tests/Anubis.Tests/OverviewScreenTests.cs | 12 +- tests/Anubis.Tests/QuarterlyReviewTests.cs | 4 + 47 files changed, 1743 insertions(+), 169 deletions(-) create mode 100644 docs/adr/0027-scelte-fase-11.md create mode 100644 src/Anubis.Server/Components/ShadowRulesTable.razor create mode 100644 src/Anubis/News/ExternalRules.cs create mode 100644 tests/Anubis.Tests/MeasuredRulesTests.cs diff --git a/docs/MANUALE.md b/docs/MANUALE.md index a67f8c0..8aa6ffb 100644 --- a/docs/MANUALE.md +++ b/docs/MANUALE.md @@ -19,6 +19,8 @@ Anubis compra e vende da solo azioni USA (su Alpaca) e crypto (su OKX Europe), s **Questa versione lavora solo con denaro finto.** Usa il simulatore interno, che è sempre acceso, e i conti di prova dei broker se ne inserisci le chiavi. Non c'è modo di collegare un conto vero, nemmeno con `ANUBIS_ALLOW_LIVE=1`: lascialo a `0`. +**Decide solo con i numeri.** Notizie, calendario economico e date delle trimestrali non cambiano nessuna decisione: il bot continua a raccoglierli, li mostra nella pagina **Notizie e mercato** come archivio e registra, senza farlo, che cosa avrebbe fatto ogni regola. Il confronto si legge nel **Laboratorio**, alla voce «Regole esterne misurate in ombra». Se un giorno vuoi che tornino ad agire, lo decidi tu in Impostazioni → Notizie, interruttore «Notizie, calendario e trimestrali». + Le strategie non partono tutte allo stesso modo. Una strategia manda ordini, anche finti, solo se ha superato i suoi test sul passato; altrimenti resta in osservazione, cioè decide e annota senza ordinare. La pagina **Strategie** dice a che punto è ognuna e perché. --- @@ -220,10 +222,10 @@ In alternativa le chiavi si passano come variabili (`ALPACA_API_KEY_DEMO`, `ALPA ### 3.3 Cose facoltative -- **Chiave Finnhub** (gratuita): date delle trimestrali. La strategia dei ribassi brevi non compra un titolo che pubblica i conti nella seduta d'acquisto o nelle tre successive e, se lo ha già, lo vende prima dei conti. Il momentum non usa questo filtro. +- **Chiave Finnhub** (gratuita): date delle trimestrali. Con le regole solo misurate (il predefinito) le date non cambiano le decisioni: servono a misurare in ombra il filtro della strategia dei ribassi brevi, che con le regole attive non compra un titolo che pubblica i conti nella seduta d'acquisto o nelle tre successive e, se lo ha già, lo vende prima dei conti. Senza la chiave quella misura non parte. Il momentum non usa questo filtro. - **Chiave FRED** (gratuita): calendario economico più lungo. - **Contatto per la SEC**: di solito un indirizzo e-mail, scritto senza spazi né lettere accentate, che la SEC chiede a chi usa i suoi archivi. Serve a conoscere i settori delle azioni. Anubis lo manda alla SEC e a nessun altro; senza, non interroga quegli archivi e i settori restano sconosciuti (il notiziario pubblico della SEC si legge comunque). -- **Modello linguistico**: un secondo parere sulle notizie, a pagamento e con un tetto di spesa al giorno. Può solo aggiungere prudenza. +- **Modello linguistico**: un secondo parere sulle notizie, a pagamento e con un tetto di spesa al giorno. Può solo aggiungere prudenza; con le regole solo misurate la sua rilettura entra nella misura in ombra. Si inseriscono tutte in Impostazioni → Notizie, riquadro «Notizie e calendario». @@ -239,10 +241,10 @@ Non c'è niente da fare ogni giorno. Un'occhiata alla Panoramica basta. | **Conti e posizioni** | Ogni posizione con il suo stop; lo stato di ogni conto e il controllo con il registro | | **Operazioni** | Ogni operazione con la scheda "perché" e l'esportazione in CSV | | **Strategie** | A che stadio è ognuna, cosa le manca per avanzare, le strategie candidate in osservazione | -| **Notizie e mercato** | Cosa ha letto e cosa ne ha fatto, il calendario | +| **Notizie e mercato** | Cosa ha letto e cosa avrebbe fatto ogni regola, il calendario: un archivio, perché oggi le notizie non decidono niente | | **Apprendimento** | Cosa ha imparato il modello e se conta già | | **Rischio** | Interruttore d'emergenza, limiti, blocchi attivi, scenari | -| **Laboratorio** | Prove sul passato, revisione trimestrale, migliorie in osservazione, stime di costo da confermare | +| **Laboratorio** | Prove sul passato, revisione trimestrale, migliorie in osservazione, regole esterne misurate in ombra, stime di costo da confermare | | **Diario e sistema** | Tutto quello che è successo, in frasi; salute delle parti; registri da scaricare | | **Impostazioni** | Tutto quello che puoi cambiare, con il registro delle modifiche | @@ -262,6 +264,10 @@ Per ripartire, togli il file e conferma dalla pagina Rischio. **Parametri delle strategie.** Non si toccano dall'interfaccia: sono quelli con cui ogni strategia è stata provata. Un cambio è una nuova prova in Laboratorio. Si cambiano invece capitale, ripartizione, limiti di rischio, regole sulle notizie e del modello. +**Notizie, calendario e trimestrali: solo misurate o attive.** In Impostazioni → Notizie l'interruttore sopra le cinque regole dice se agiscono. «Solo misurate» è il predefinito: le decisioni guardano solo i prezzi, e ogni regola scrive in ombra che cosa avrebbe fatto. «Attive» è il comportamento delle versioni precedenti: le regole accese possono fermare o rinviare un acquisto. Il bot non le riaccende mai da solo. Prima di farlo guarda nel Laboratorio la tabella delle regole in ombra: una regola merita di agire solo dopo almeno 6 mesi di misura, almeno 30 ingressi cambiati e un effetto tutto sopra lo zero (la riga dice «Criterio raggiunto»). Per riaccenderne una sola, spegni le altre righe e poi scegli «Attive». Passare da «Attive» a «Solo misurate» toglie protezioni: se una strategia usa soldi veri chiede la frase, la password e, se l'hai attivato, il codice a sei cifre, come quando spegni una regola. Ogni cambio lascia una riga nel Diario. Con le regole solo misurate un modello in carica che usa indizi delle notizie, delle trimestrali o di paura e avidità viene messo da parte subito. La domenica ne addestra uno senza, che prende il posto solo dopo aver vinto i confronti con il modello in carica; nel frattempo nessun modello conta. + +Chi aggiorna da una versione precedente trova nel Diario una riga sola: da questa versione le regole sono solo misurate. Le decisioni prese prima restano come erano, con le regole attive. + **Importare dati tuoi (CSV).** Solo da riga di comando. Copia nella cartella `import` dei dati il file e, accanto, la sua descrizione con lo stesso nome (`file.csv` → `file.mapping.json`; in mancanza vale un `mapping.json` per tutta la cartella). Un esempio per barre giornaliere: ```json @@ -424,7 +430,7 @@ In **Impostazioni → Dati → Esportazione per la dichiarazione** scarichi, ann | **L'interruttore è scattato** | [RUNBOOK.md, interruttore](RUNBOOK.md#3-interruttore-scattato) | | **"Il broker non accetta più la chiave"** | [RUNBOOK.md, chiave scaduta](RUNBOOK.md#4-chiave-scaduta-o-rifiutata) | | **Il server è rimasto spento** | Niente: alla riaccensione il bot recupera, aggiorna le uscite e lascia perdere gli acquisti troppo vecchi. Un'assenza di più di un giorno resta segnata in Panoramica finché non la vedi | -| **Le strategie non comprano mai** | Guarda **Strategie**: in osservazione non ordinano. Nel **Diario** trovi le rinunce dovute a restrizioni, dati mancanti, prezzo cambiato, ritardo o rifiuto del broker; in **Rischio** i blocchi e i limiti attivi. Un acquisto fermato da un limite di rischio non lascia una riga nel Diario | +| **Le strategie non comprano mai** | Guarda **Strategie**: in osservazione non ordinano. Nel **Diario** trovi le rinunce dovute a restrizioni (solo con le regole sulle notizie attive), dati mancanti, prezzo cambiato, ritardo o rifiuto del broker; in **Rischio** i blocchi e i limiti attivi. Un acquisto fermato da un limite di rischio non lascia una riga nel Diario | | **Voglio mostrare un problema a chi sviluppa** | Diario e sistema → **Scarica i dati per l'analisi**: un testo senza chiavi né password | ### Disinstallare diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a443965..6a5905d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -20,7 +20,7 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest | 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Completata | | 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Completata (pubblicazione e prova su Unraid in attesa dell'utente) | | 10 | [Nuova rotta: solo Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/37) | Completata (prova di durata dal container in attesa dell'utente) | -| 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Da fare | +| 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Completata (unione e tag dopo il sì dell'utente; misura sulle azioni in attesa delle chiavi Alpaca e Finnhub) | | 12 | [Dati e matematica dei panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/80) | Da fare | | 13 | [Campionato: unità di lavoro, piano e statistica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/81) | Da fare | | 14 | [Motore a panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/82) | Da fare | @@ -332,17 +332,19 @@ Un solo interruttore decide se notizie, calendario e trimestrali agiscono o veng **Lavori** -- [ ] [#116](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/116) Decisioni solo matematiche -- [ ] [#117](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/117) Chiusura della fase, revisione indipendente e tag `fase-11` (dopo il sì dell'utente) +- [x] [#116](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/116) Decisioni solo matematiche +- [x] [#117](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/117) Chiusura della fase, revisione indipendente e tag `fase-11` (dopo il sì dell'utente) **Criteri di accettazione** -- [ ] Predefinito: una notizia grave confermata su un titolo in acquisto non cambia niente (ordine rilasciato, nessuna riga di blocco, nessuna nota, nessuna chiamata a Telegram). -- [ ] `equity_meanrev` con la trimestrale domani entra, e non emette mai l'uscita per trimestrale. -- [ ] L'addestramento ignora gli indizi esterni; un modello in carica che ne contiene uno non si applica. -- [ ] Con l'interruttore su «attive», impostato dal supporto di prova, i test di oggi sulle regole (`NewsRulesTests`, `AbsenceTests`, `NewsAnalystTests`, `QuarterlyReviewTests`) passano senza altre modifiche. -- [ ] Un caso in ombra per regola, strategia, strumento e giorno; sotto i sei mesi la riga dice «troppo presto»; la revisione trimestrale mostra il bilancio storico e, accanto, le regole misurate. -- [ ] L'interruttore si cambia solo dalle Impostazioni, con le protezioni che hanno già le cinque righe, e scrive una riga nel diario. Fotografie delle schermate a 1440 px (chiaro e scuro) e a 390 px. +- [x] Predefinito: una notizia grave confermata su un titolo in acquisto non cambia niente (ordine rilasciato, nessuna riga di blocco, nessuna nota, nessuna chiamata a Telegram). +- [x] `equity_meanrev` con la trimestrale domani entra, e non emette mai l'uscita per trimestrale. +- [x] L'addestramento ignora gli indizi esterni; un modello in carica che ne contiene uno non si applica. +- [x] Con l'interruttore su «attive», impostato dal supporto di prova, i test di oggi sulle regole (`NewsRulesTests`, `AbsenceTests`, `NewsAnalystTests`, `QuarterlyReviewTests`) passano senza altre modifiche. +- [x] Un caso in ombra per regola, strategia, strumento e giorno; sotto i sei mesi la riga dice «troppo presto»; la revisione trimestrale mostra il bilancio storico e, accanto, le regole misurate. +- [x] L'interruttore si cambia solo dalle Impostazioni, con le protezioni che hanno già le cinque righe, e scrive una riga nel diario. Fotografie delle schermate a 1440 px (chiaro e scuro) e a 390 px. + +Prove: `MeasuredRulesTests` (14 casi: interruttore, notizia grave, trimestrale, sorvegliante, addestramento, modello messo da parte, registro dei modelli, ombra al 99%, impostazioni, aggiornamento da una versione precedente, ordine deciso con le regole misurate); i test della Fase 7 invariati con «attive» impostato dal supporto di prova. Scelte nell'ADR 0027. Con le chiavi di oggi la misura riguarda solo `crypto_trend` e le due regole sulle notizie: le tre regole su trimestrali e calendario delle azioni aspettano le chiavi di Alpaca e di Finnhub. ## Fase 12 — Dati e matematica dei panieri (solo ricerca) diff --git a/docs/STATE.md b/docs/STATE.md index 3a6a6fd..67cf20c 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,9 +4,9 @@ Aggiornato: 2026-12-03 ## Fase corrente -**Fase 10 — Nuova rotta: solo Docker: completata** e unita in `main` con il tag `fase-10`, dopo il sì dell'utente del 3 dicembre 2026. Resta in attesa dell'utente la prova di durata dal container (#55). 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 11 — Decisioni solo matematiche: completata** sul branch `fase-11`, con la pull request aperta: unione in `main` e tag `fase-11` aspettano il sì dell'utente. Notizie, calendario e trimestrali non cambiano più nessuna decisione (interruttore «Notizie, calendario e trimestrali», predefinito «solo misurate»): ogni regola scrive in ombra che cosa avrebbe fatto. La Fase 10 è unita con il tag `fase-10`; resta in attesa dell'utente la prova di durata dal container (#55). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. -**Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023): notizie, calendario e trimestrali si misureranno in ombra; fino alla Fase 11 il codice resta quello della Fase 7. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale. +**Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023, applicato dalla Fase 11 con l'ADR 0027): notizie, calendario e trimestrali si misurano in ombra. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale. ## Fatto @@ -140,13 +140,21 @@ Aggiornato: 2026-12-03 - `tasks dev` usa la cartella `artifacts/dev-data` e i valori di sviluppo del compose con SQLite. - Spostamento dei dati (#78) e manuali senza desktop (#80): `docs/MANUALE.md` 5.7 dice come portare nel container i dati della prova fatta su Windows, con `db export` dalla versione `fase-9` e `db import`. +- **Fase 11 — Decisioni solo matematiche** (#116, ADR 0027, nessun pacchetto nuovo): + - Interruttore `decisions.external_rules`, «misurate» (predefinito) o «attive» (il comportamento della Fase 7), sopra le cinque righe di SPEC 10.5. Si cambia solo dal modulo delle Impostazioni, con le protezioni delle cinque righe; l'interfaccia per i programmi lo rifiuta; ogni cambio scrive una riga nel diario, senza Telegram. Il motore lo legge una volta per decisione e, al controllo a un passo e all'invio di un ordine pianificato, com'era all'istante della decisione. Al primo avvio un'installazione che aveva già deciso registra «attive» → «misurate» con autore «aggiornamento». + - Con «misurate»: nessun rinvio, nessun blocco, nessuno stop tenuto fermo, nessuna nota e nessuna riga di diario delle notizie; `equity_meanrev` non riceve date di trimestrali (entra, e non esce mai per i conti). Le cinque regole scrivono un caso in ombra per regola, strategia, strumento e giorno (`shadow_cases`, chiavi `rule_*`); la trimestrale in uscita si misura rietichettando l'operazione con la data dei conti. + - Laboratorio e revisione trimestrale mostrano la tabella «Regole esterne misurate in ombra»: intervallo al 99%, «Troppo presto» sotto i 6 mesi, criterio di ADR 0023 (30 ingressi cambiati, effetto tutto sopra lo zero). Il bilancio delle restrizioni resta come storia del periodo in cui le regole agivano. + - Modello: i sette indizi esterni (tono, numero e gravità delle notizie, giorni alla trimestrale, paura e avidità) restano fuori dall'addestramento; un modello in carica che ne usa uno è messo da parte subito, senza allarmi, e la domenica se ne addestra uno senza, che entra come sfidante. + - Schermate: Notizie come archivio con l'avviso fisso, «Cosa avrebbe fatto la regola»; Panoramica, Rischio, Strategie, Apprendimento, Impostazioni e Laboratorio con le frasi «solo registrato». Fotografie in `artifacts/screenshots/` (1440 px chiaro e scuro, 390 px). La modalità dimostrativa segue «misurate». + - Revisione indipendente in due giri: 16 problemi confermati nel primo e corretti (tra cui la lettura dell'interruttore all'invio, il messaggio «anomalia rientrata» mentre il modello restava da parte, le trimestrali che coprivano le regole delle notizie nella pagina Notizie). + ## In corso Nulla. ## Prossimo passo -1. La **Fase 11 — Decisioni solo matematiche**, in una nuova sessione, sul branch `fase-11` da `main`. Letture: la riga della Fase 11 nella tabella dell'ADR 0021 (punto 3), l'ADR 0023 e la Fase 11 del piano. +1. Il sì dell'utente per unire la pull request della Fase 11 e mettere il tag `fase-11`. Poi la **Fase 12 — Dati e matematica dei panieri**, in una nuova sessione, sul branch `fase-12` da `main`. Letture: la riga della Fase 12 nella tabella dell'ADR 0021 (punto 3) e la Fase 12 del piano. 2. L'utente decide se pubblicare l'immagine (prossimo tag `v*`) e prova il template su Unraid seguendo `docs/MANUALE.md`. 3. Il rapporto della prova di durata (#55): si raccoglie dal container sul server di casa (48 ore a `--memory=2g`), si analizza, si salva in `docs/diagnostica/` e si chiude #55. 4. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. @@ -161,6 +169,7 @@ Nulla. - **Prova di durata (#55)** non chiusa: manca il rapporto, che ora si raccoglie dal container. - **La logica del documento della nuova rotta**, misurata dal documento stesso, è negativa o non si distingue dal caso. Il piano mette le prove davanti agli ordini, e l'esito più probabile è che resti una prova sul Demo, fuori dai totali. - **Il modello** è appena migliore della frequenza di base e ha studiato solo `crypto_trend`. +- **La misura in ombra delle regole esterne** parte ora: il primo giudizio non arriva prima di 6 mesi, e con le chiavi di oggi riguarda solo `crypto_trend` e le due regole sulle notizie. Con poche proposte d'ingresso è probabile che non arrivi a un giudizio. - **Dati**: gli universi azionari passati usano i flag di oggi; la storia crypto prima di novembre 2023 viene da Binance in USDT; gli archivi della SEC non sono mai stati letti dal vivo. - **Un acquisto tagliato da un limite di rischio** non lascia una riga nel diario, solo nelle decisioni. - **Importazione CSV** solo da riga di comando, e il Laboratorio legge solo le serie di Binance. diff --git a/docs/adr/0023-decisioni-solo-matematiche.md b/docs/adr/0023-decisioni-solo-matematiche.md index 18db4cb..7be1113 100644 --- a/docs/adr/0023-decisioni-solo-matematiche.md +++ b/docs/adr/0023-decisioni-solo-matematiche.md @@ -1,6 +1,6 @@ # 0023 — Decisioni solo matematiche -Data: 2026-12-03 · Stato: accettata; il codice arriva nella Fase 11 · Decisione dell'utente del 2 dicembre 2026 (ADR 0021, scelta 2: «Continua in silenzio») · Sostituisce SPEC 1 punto 4; 8.3 (filtro in ingresso e uscita per trimestrale); 8.5 (righe «Eventi in calendario» e «Notizie»); 10.1; 10.4 (paura e avidità come indizio); 10.5 come comportamento predefinito, avviso Telegram compreso; 11.2 (indizi esterni); 8.7 per il criterio di riaccensione; ADR 0011 punto 2, ADR 0014 punti 9–11, l'elenco degli indizi dell'ADR 0018, ADR 0020 punti 30 e 49 +Data: 2026-12-03 · Stato: accettata; applicata nella Fase 11 (ADR 0027) · Decisione dell'utente del 2 dicembre 2026 (ADR 0021, scelta 2: «Continua in silenzio») · Sostituisce SPEC 1 punto 4; 8.3 (filtro in ingresso e uscita per trimestrale); 8.5 (righe «Eventi in calendario» e «Notizie»); 10.1; 10.4 (paura e avidità come indizio); 10.5 come comportamento predefinito, avviso Telegram compreso; 11.2 (indizi esterni); 8.7 per il criterio di riaccensione; ADR 0011 punto 2, ADR 0014 punti 9–11, l'elenco degli indizi dell'ADR 0018, ADR 0020 punti 30 e 49 ## Contesto @@ -34,7 +34,7 @@ Dalla Fase 7 notizie, calendario economico e date delle trimestrali agiscono sul 7. **Il confronto in backtest** (Fase 17) usa le stesse regole come variante del piano, solo dove lo storico esiste; le varianti «con le notizie» non sono mai finaliste del campionato e stanno fuori dal suo conteggio. 8. **Fino alla Fase 11** il codice resta quello della Fase 7: le regole agiscono. Questo ADR fissa la decisione; la Fase 11 la applica. -Data del cambio nel codice: *si scrive nella Fase 11*. +Data del cambio nel codice: **3 dicembre 2026** (Fase 11, ADR 0027). Il registro dei modelli la mostra una volta per installazione, alla prima verifica notturna con «misurate». ## Alternative scartate diff --git a/docs/adr/0027-scelte-fase-11.md b/docs/adr/0027-scelte-fase-11.md new file mode 100644 index 0000000..bef49fb --- /dev/null +++ b/docs/adr/0027-scelte-fase-11.md @@ -0,0 +1,85 @@ +# 0027 — Scelte della Fase 11 (decisioni solo matematiche) + +Data: 2026-12-03 · Stato: accettata · Applica l'ADR 0023 · Precisa SPEC 8.7, 10.5, 11.2–11.4, 13.5 e 13.6 · Sostituisce, nell'appendice F, le righe della modalità dimostrativa che fanno agire notizie, trimestrali e indizi esterni (F.7 pesi degli indizi, F.9 «cosa ho fatto», Panoramica) + +## Contesto + +L'ADR 0023 ha deciso che notizie, calendario e trimestrali non cambiano più nessuna decisione e girano «in ombra». Lascia aperti alcuni punti che si possono fissare solo guardando il codice: dove si legge l'interruttore, che cosa vuol dire «misurare» una regola che oggi agisce in tre posti diversi, che fare del modello che usa gli indizi esterni, quali testi cambiano. Dove c'era da scegliere si è presa la via più prudente. + +## Decisione + +### L'interruttore + +1. `decisions.external_rules` (`Anubis.News.ExternalRules`): «misurate», predefinito, oppure «attive». È un'impostazione a sé, sopra le cinque righe di SPEC 10.5, non una sesta riga. +2. Si legge **una volta per decisione** (il motore), **per giro** (il sorvegliante delle notizie) e **per pagina**: un cambio vale dalla decisione successiva, senza riavvio. Il controllo a un passo (SPEC 12.3) rifà la decisione di ieri con il valore che l'interruttore aveva ieri, ricavato dal registro delle modifiche: un cambio a metà non diventa una «differenza». Lo stesso vale per l'invio di un ordine pianificato: il controllo all'invio appartiene alle decisioni prese con «attive», quindi l'interruttore si legge com'era all'istante della decisione (che il registro delle esecuzioni e l'ordine pianificato conservano), non all'invio. Un'azione decisa alle 16 e inviata alle 9:35 del giorno dopo non cambia regola a metà strada. +3. Un componente costruito senza impostazioni, cosa che succede solo nelle prove, si comporta come «attive», come già le cinque righe senza impostazioni sono tutte accese. Il supporto di prova (`DatabaseTests.MigratedAsync`) scrive «attive» nel database di ogni prova; il server delle prove e ogni installazione vera partono invece da «misurate». Così le prove della Fase 7 passano senza modifiche, e le prove nuove chiedono «misurate» esplicitamente. +4. **Protezioni**, le stesse delle cinque righe: si cambia solo dal modulo delle Impostazioni; l'interfaccia per i programmi (`PUT /api/settings`) lo rifiuta; la modalità dimostrativa lo rifiuta. Il passaggio da «attive» a «misurate» toglie restrizioni, come spegnere una riga: con una strategia a soldi veri chiede frase, password e codice. Il passaggio a «attive» è libero. +5. Ogni cambio vero scrive una riga nel diario (tipo Sistema, codice `external_rules_changed`), nella stessa transazione del cambio, senza Telegram. Un salvataggio che non cambia niente non scrive niente. +6. **Le cinque righe valgono solo con «attive».** Con «misurate» restano visibili, in grigio, con la scritta che valgono quando le regole sono attive. Per riaccendere una regola sola (ADR 0023 punto 5): si spengono le altre righe, poi si mette l'interruttore su «attive». La riga delle trimestrali comanda entrambe le regole sulle trimestrali, come nella Fase 7. + +### Le decisioni con «misurate» + +7. **Cancello sugli ingressi.** Il motore lo interroga ancora, ma per regola e con tutte le righe accese, e non applica la risposta: nessun rinvio, nessuno stop tenuto fermo, nessuna riga di blocco (`Correctives` o `Order` con esito rifiutato o rinviato), nessuna riga di diario. Al momento dell'invio dell'ordine il cancello non si interroga più. +8. **Quando si guarda.** Le notizie si leggono all'istante della decisione, con ciò che si sapeva allora (ADR 0023: la misura è al momento della decisione). Il dato macro invece si guarda all'ora in cui l'ordine partirebbe, con il calendario noto alla decisione: con «attive» è il controllo all'invio che lo prende, e guardarlo all'istante della decisione non lo vedrebbe quasi mai. Una notizia arrivata tra la decisione e l'invio non entra nella misura. +9. **Trimestrali.** Nessuna data arriva alle decisioni, al controllo a un passo e agli indizi dell'esempio (`earnings_days`): il dal vivo coincide con i backtest, che non hanno mai avuto le date. Le date si leggono lo stesso, se Finnhub risponde, e vanno solo alla misura in ombra. Un esempio nato con «misurate» non ha quindi `earnings_days` e la sua etichetta non esce per trimestrale. Uno nato con «attive» e ancora aperto al cambio resta etichettato con ciò che sapeva il giorno della decisione. +10. **Diario e Telegram.** Il sorvegliante delle notizie non scrive note (`news_notes`), righe di diario né avvisi: restrizioni, voci da ricontrollare, trimestrali in arrivo. La riga del tetto di spesa del modello linguistico resta: parla di spesa, non di una notizia. Le note già scritte restano come storia. + +### La misura in ombra + +11. Chiavi in `shadow_cases`, accanto alle migliorie di SPEC 8.7 ma in un elenco a parte (`ShadowRules`): `rule_news_severe`, `rule_news_negative`, `rule_macro`, `rule_earnings_entry`, `rule_earnings_exit`; gli stop tenuti fermi si contano sotto `rule_news_severe_stop`. La chiave unica della tabella dà un caso per regola, strategia, strumento e giorno. Nessuna tabella nuova. +12. I casi si scrivono **solo con «misurate»**: con «attive» le regole agiscono e i loro blocchi li misura il bilancio delle restrizioni. Si scrivono con l'apprendimento, nella stessa transazione della decisione e con lo stesso salvataggio a parte: un errore della misura non tocca la decisione. +13. **Ingressi nuovi** (quelli che hanno un esempio, SPEC 11.2), per le tre regole sulle notizie e sul calendario: + - la regola l'avrebbe tolto (fine della restrizione oltre la scadenza dell'ordine, SPEC 5.6): fattore 0. L'effetto è meno il risultato dell'ingresso fatto, come per il filtro di mercato di SPEC 8.7: positivo vuol dire che la regola avrebbe evitato una perdita; + - la regola l'avrebbe solo rinviato: contato, non valutato; + - la regola non avrebbe fatto niente: fattore 1, effetto zero. + Un aumento di una posizione aperta si conta e non si valuta: non ha un esempio suo. +14. **Trimestrale in ingresso** (`equity_meanrev`): lo stesso predicato della strategia (`EquityMeanrev.EarningsAhead`, reso pubblico e puro) sulle date note alla decisione. Non conta il candidato che avrebbe preso il posto lasciato libero. +15. **Trimestrale in uscita** (`equity_meanrev`): il caso nasce all'ingresso, con la data nota allora, uno per operazione. Si misura quando l'operazione ha la sua etichetta: l'etichetta rifatta con la trimestrale, meno l'etichetta vera. Se la regola non l'avrebbe fatta uscire prima, il fattore diventa 1 e l'effetto zero. Il prezzo dell'uscita saltata è la chiusura della seduta prima della trimestrale, come nel backtest e nelle etichette; con «attive» il dal vivo vende invece all'apertura dopo, perché il controllo delle 15:55 non legge le date: è una differenza della Fase 7, dichiarata e non corretta. Una trimestrale annunciata dopo l'ingresso non entra nella misura. +16. **Tabella e criterio** (ADR 0023 punto 5): intervallo al 99% (quantile 0,995 di Student sui mesi, gli stessi errori raggruppati per mese di SPEC 8.7). «Troppo presto» finché dal primo caso della regola non sono passati 6 mesi; poi il criterio: almeno 30 ingressi cambiati (fattore 0 valutati: i rinvii e gli aumenti non contano), intervallo tutto sopra lo zero, confronto della Fase 17 «non ancora disponibile». Senza casi: «In attesa delle chiavi Alpaca» per le regole che riguardano solo le azioni e «In attesa della chiave Finnhub» per le trimestrali. Il bot dice solo se il criterio è raggiunto; non riaccende niente. +17. La tabella sta nel Laboratorio, sotto le migliorie, e nella revisione trimestrale accanto al bilancio delle restrizioni, come fotografia del giorno della pubblicazione (`ReviewReport.ShadowRules`; le revisioni già pubblicate la mostrano vuota). Le regole non entrano nelle scoperte di SPEC 11.6, che usano il 95%. + +### Il modello + +18. Sono **esterni** sette indizi: tono delle notizie a 1 e 3 giorni, numero di notizie a 1 e 3 giorni, notizia più grave, paura e avidità, giorni alla trimestrale. Con «misurate» l'addestramento li esclude; si continuano a registrare (tranne `earnings_days`, punto 9), così l'archivio e le scoperte restano. +19. Un modello in carica che ne contiene uno è **messo da parte subito**, alla decisione successiva, non alla verifica delle 3: non cambia la dimensione di nessuna operazione nuova. Ha un motivo suo, distinto dall'allarme: non manda Telegram, scrive un evento nel registro dei modelli e una riga nel diario dell'apprendimento quando comincia e quando finisce. Le operazioni già nate con un moltiplicatore lo tengono fino alla chiusura (SPEC 11.1). +20. La domenica, con «misurate», se il modello in carica è messo da parte per gli indizi esterni si riaddestra anche senza esempi nuovi; uno sfidante che li contiene è scartato. Il modello riaddestrato entra come **sfidante** e aspetta i confronti di SPEC 11.4: non prende il posto da solo (ADR 0020 punto 30). Nel frattempo nessun modello conta. +21. Il primo modello non contiene indizi esterni: con le chiavi di oggi non cambia niente. +22. **Data del cambio** (ADR 0023 punto 6): 3 dicembre 2026, scritta nell'ADR 0023. Il registro dei modelli la mostra una volta per installazione, alla prima verifica notturna con «misurate», con il numero degli esempi già etichettati con un'uscita per trimestrale. Non si rietichetta niente. Il giorno mostrato è quello in cui le decisioni hanno smesso di leggere le regole: l'ultimo passaggio a «misurate» nel registro delle modifiche, oppure il giorno in cui questa versione ha scritto l'interruttore; mai la notte della verifica. Al primo avvio questa versione scrive l'interruttore nella configurazione; su un'installazione che aveva già deciso qualcosa aggiunge al registro delle modifiche «attive» → «misurate», con autore «aggiornamento», e una riga nel diario: le decisioni di prima, rifatte dal controllo a un passo, leggono le regole com'erano. Una copia spostata altrove porta con sé la riga e non la ripete. + +### Testi e modalità dimostrativa + +23. **Bozzetto.** I bozzetti di `docs/design/` sono immagini e non si ridisegnano senza strumenti esterni. Il bozzetto di questa fase è la tabella dei testi qui sotto, scritta prima del codice; le fotografie della fase diventano il riferimento delle schermate cambiate. + + | Dove | Con «misurate» | + |---|---| + | Notizie, in testa | «Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola.» | + | Notizie, sommario | «N notizie lette nelle ultime 24 ore, K su cui una regola avrebbe agito.» Filtro «Con una regola, K» | + | Notizie, riga | «Cosa avrebbe fatto la regola:» seguito dalla frase della regola al condizionale e da «Solo registrato.»; mai evidenziata | + | Notizie, umore | «Paura e avidità è solo registrato: non entra più nel modello. Il nervosismo di Wall Street e le scommesse a leva restano indizi del modello, come numeri del mercato.» | + | Notizie, calendario | «Riguarda JPM: con le regole attive niente mean reversion fino a martedì. Solo registrato.»; «Impatto alto: con le regole attive nessun nuovo ingresso dalle 14:00 alle 15:00. Solo registrato.» | + | Panoramica, notizie | «Negativa: la regola l'avrebbe fermata, solo registrato»; per una trimestrale in arrivo «Evento in arrivo: con le regole attive niente nuovi acquisti di mean reversion su JPM prima dei conti, solo registrato» | + | Notizie, trimestrale in arrivo | «Con le regole attive niente nuovi acquisti di mean reversion su JPM prima dei conti. Solo registrato.», solo se nessuna regola delle notizie riguarda la storia | + | Rischio, blocchi | «Prossimo dato macro (solo registrato)» e «con le regole attive in quell'ora non aprirei posizioni; ora le apro come sempre»; «Nessun blocco: le regole delle notizie e del calendario sono solo misurate.» | + | Strategie, mean reversion | «Trimestrali solo misurate: non salta i giorni prima» | + | Impostazioni, notizie | L'interruttore «Notizie, calendario e trimestrali: solo misurate / attive» sopra le righe; le righe in grigio con «Valgono quando le regole sono attive» | + | Apprendimento | Stato «Messo da parte: usa indizi che ora sono solo misurati»; frase dei pesi «Notizie, trimestrali, paura e avidità non entrano nel modello: le decisioni guardano solo i numeri del mercato.» | + | Laboratorio e revisione | Tabella «Regole esterne misurate in ombra» | + +24. **La modalità dimostrativa segue il predefinito**, «misurate»: mostra ciò che un'installazione nuova mostra. I dati dell'appendice F restano (notizie, calendario, note di allora come storia); cambiano solo le frasi che dicevano un effetto in corso e i pesi del modello in carica, dove tono delle notizie e paura e avidità lasciano il posto a due indizi di mercato. Escono dal diario dimostrativo le sei righe delle notizie di oggi e di ieri: con «misurate» il bot non le scrive. È l'unica parte dell'appendice F che questo ADR sostituisce. +25. La revisione trimestrale tiene il suo bilancio delle restrizioni com'è, come storia del periodo in cui le regole agivano; la frase «la riga delle trimestrali non è misurata» diventa «le trimestrali sono misurate nella tabella delle regole in ombra». + +## Alternative scartate + +- **Leggere l'interruttore solo all'avvio del motore**: un cambio dalle Impostazioni varrebbe solo dopo un riavvio. +- **Trattare un componente senza impostazioni come «misurate»**: le prove della Fase 7 cambierebbero comportamento senza che nessuno le tocchi. +- **Misurare le regole anche con «attive»**: i blocchi veri finirebbero contati due volte, dal bilancio delle restrizioni e dall'ombra. +- **Scrivere la trimestrale in uscita nel giorno dell'uscita saltata**: la stessa operazione darebbe un caso ogni giorno fino alla trimestrale. +- **Rispettare le cinque righe anche nell'ombra**: spegnere una riga ne fermerebbe la misura, e la riga spenta non si potrebbe più giudicare. +- **Promuovere subito il modello riaddestrato senza indizi esterni**: salterebbe i confronti di SPEC 11.4. +- **Lasciare la modalità dimostrativa su «attive»**: le fotografie della fase non mostrerebbero le schermate come le vede un'installazione nuova. + +## Conseguenze + +- Con «misurate» una notizia grave confermata su un titolo in acquisto non cambia niente: ordine rilasciato, nessuna riga di blocco, nessuna nota, nessun avviso; nasce un caso in ombra per regola. +- `equity_meanrev` entra anche con la trimestrale il giorno dopo e non esce mai per trimestrale. +- Con le chiavi di oggi la misura riguarda solo `crypto_trend` e le due regole sulle notizie, più il dato macro se FRED o le riunioni delle banche centrali hanno eventi ad alto impatto vicino all'ora degli ordini. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index f911145..79d6068 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -387,6 +387,7 @@ internal sealed partial class AnubisHost( Guard?.Step("servizi"); var key = Config.SecretKey.GetOrCreateKey(); var settings = new SettingsStore(_db, clock, bus, StartupOverrides()); + await News.ExternalRules.SettleAsync(_db, clock, cancellationToken).ConfigureAwait(false); var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys); var access = new AccessStore(_db, clock, secrets, PasswordIterations, _accessGuards); if (options.Demo && identity.Verdict == IdentityVerdict.Created) @@ -439,7 +440,12 @@ internal sealed partial class AnubisHost( _lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger); if (_lab is { } laboratory && _trading is { } running && _market is { } market) { - var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger); + async Task HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet; + var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger) + { + Keys = async ct => (await HasAsync("ALPACA_API_KEY_DEMO", ct).ConfigureAwait(false) && await HasAsync("ALPACA_API_SECRET_DEMO", ct).ConfigureAwait(false), + await HasAsync("FINNHUB_API_KEY", ct).ConfigureAwait(false)), + }; laboratory.ReviewTrialEnded = review.ConcludeAsync; running.QuarterlyReview = review.RunIfDueAsync; } diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 3ed00ed..5c36c40 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -235,6 +235,8 @@ h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; } .notice-loss { background: var(--loss-bg); color: var(--loss); } .notice-gain { background: var(--gain-bg); color: var(--gain); } .notice-attention { background: var(--attention-bg); color: var(--attention); } +.news-archive { margin-bottom: 16px; background: var(--info-bg); color: var(--text); } +.rules-off { opacity: 0.6; } .badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 8px; font-size: 18px; line-height: 24px; font-weight: 600; } .badge-gain { background: var(--gain-bg); color: var(--gain); } .badge-loss { background: var(--loss-bg); color: var(--loss); } diff --git a/src/Anubis.Server/Components/Pages/Apprendimento.razor b/src/Anubis.Server/Components/Pages/Apprendimento.razor index 79985d3..925c187 100644 --- a/src/Anubis.Server/Components/Pages/Apprendimento.razor +++ b/src/Anubis.Server/Components/Pages/Apprendimento.razor @@ -23,7 +23,7 @@ else if (Errore is not null)
- @Badge(s.State) + @Badge(s.State)

@v.Title

@v.Text

@if (s.State != LearningStates.None) @@ -285,6 +285,7 @@ else if (Errore is not null) LearningStates.None => "Non ancora partito", LearningStates.Active => "Attivo", LearningStates.Aside => "Messo da parte", + LearningStates.Rules => "Messo da parte", LearningStates.Manual => "Messo da parte da te", _ => "In osservazione", }; @@ -294,6 +295,7 @@ else if (Errore is not null) LearningStates.None => "clock", LearningStates.Active => "check", LearningStates.Aside => "alert", + LearningStates.Rules => "pause", LearningStates.Manual => "pause", _ => "eye", }; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 354f6c5..a3faaf0 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -396,13 +396,53 @@

Notizie e calendario

-

Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.

+ @if (_measured) + { +

Notizie, calendario e trimestrali non cambiano nessuna decisione: le decisioni guardano solo i numeri del mercato. Per ogni regola registro solo cosa avrebbe fatto, e il Laboratorio mostra quanto avrebbe reso.

+ } + else + { +

Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.

+ }

Regole

+ @if (_rules is { } switchValue) + { + var key = Anubis.News.ExternalRules.Setting.Key; + var toMeasured = !_measured; +
+ + + + + @if (switchValue.ReadOnly) + { + Fissato da @switchValue.Source: si cambia lì. + } + else if (!Shell.IsDemo && _anyLive && toMeasured) + { +

Una strategia usa soldi veri: per misurare soltanto le regole servono la frase e la password.

+ + + + + } + else if (!Shell.IsDemo) + { + + } + +

@(_measured + ? "Le righe qui sotto valgono quando le regole sono attive. Per riaccenderne una sola, spegni le altre e poi scegli «Attive». Il bot non le riaccende mai da solo." + : "Ogni cambio scrive una riga nel diario.")

+ } @foreach (var rule in _newsRules) { var definition = SettingsStore.Definition(rule.Key); -
+ @@ -464,7 +504,7 @@ }

Modello linguistico

-

Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.

+

Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: @(_measured ? "con le regole solo misurate la sua rilettura entra nella misura in ombra, come farebbe se fossero attive" : "può aggiungere una restrizione, mai toglierla"), e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.

@DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico") @ModelSetting(Anubis.News.NewsModelSettings.Provider.Key, "servizio", "Servizio", null) @ModelSetting(Anubis.News.NewsModelSettings.Model.Key, "modello", "Modello", null) @@ -475,7 +515,7 @@

I prezzi in dollari li conto come euro: la spesa calcolata è un po' più alta di quella vera, mai più bassa. Il tetto vale da mezzanotte a mezzanotte; prima di ogni richiesta controllo che anche il caso peggiore ci stia dentro.

Calendario

-

Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.

+

Senza chiave di Finnhub non conosco le date delle trimestrali: @(_measured ? "la misura in ombra del filtro della mean reversion non parte" : "la mean reversion non usa il suo filtro"); senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.

@DataKey("FINNHUB_API_KEY", "Chiave di Finnhub") @DataKey("FRED_API_KEY", "Chiave di FRED")

Settori delle società

@@ -666,6 +706,10 @@ private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private readonly List _newsRules = []; + + private SettingValue? _rules; + + private bool _measured; private readonly List _model = []; private int? _undoTo; private readonly Dictionary _llm = []; @@ -702,6 +746,8 @@ _sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct); _taxMethod = await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct); _taxChoices = await Anubis.Trading.TaxExport.ChoicesAsync(services.Db, ct); + _rules = await services.Settings.GetAsync(Anubis.News.ExternalRules.Setting.Key, ct); + _measured = _rules.Value == Anubis.News.ExternalRules.Measured; foreach (var rule in Anubis.News.NewsRuleSettings.All) { _newsRules.Add(await services.Settings.GetAsync(rule.Key, ct)); @@ -941,6 +987,8 @@ "fifo" => "Primo comprato, primo venduto (FIFO)", "EUR" => "Euro (EUR)", "USD" => "Dollaro (USD)", + Anubis.News.ExternalRules.Measured => "Solo misurate", + Anubis.News.ExternalRules.Active => "Attive", "active" => "Attivo", "paused" => "In pausa", "stopped" => "Fermo", diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor index a6bc82f..7c8d679 100644 --- a/src/Anubis.Server/Components/Pages/Laboratorio.razor +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -219,6 +219,14 @@

L'effetto è una quota di quanto il segnale avrebbe investito: +0,10% vuol dire un euro in più ogni mille. L'intervallo contiene il valore vero 95 volte su 100.

+
+

Regole esterne misurate in ombra

+

@(_measured + ? "Notizie, calendario e trimestrali non cambiano nessuna decisione. Per ogni ingresso scrivo cosa avrebbe fatto ciascuna regola, e quando l'operazione si chiude misuro quanto avrebbe reso." + : "Le regole sono attive: agiscono sugli acquisti e il bilancio delle restrizioni della revisione trimestrale ne misura l'effetto. Qui restano i casi misurati quando erano solo misurate.")

+ +
+

Stime di costo da confermare

Scostamento contato da simulatore e backtest: @string.Join("; ", SlippageTiers.All.Select(t => SlippageTiers.Label(t) + " " + Bp(_table.Of(t)))). Ogni mese si confronta con le esecuzioni ottenute dai broker, mai con quelle del simulatore. Una stima sale da sola; scende solo se viene da soldi veri e la confermi tu.

@@ -283,6 +291,10 @@ private IReadOnlyList _research = []; private IReadOnlyList _costs = []; private IReadOnlyList _improvements = []; + + private IReadOnlyList _rules = []; + + private bool _measured; private IReadOnlyList _reviews = []; private DateOnly _nextReview; private bool _anyLive; @@ -312,6 +324,8 @@ async Task HasAsync(string secret) => (await services.Secrets.StatusAsync(secret, ct)).IsSet; _improvements = await learning.Shadow.LoadAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync(Edgar.ContactSecret), (await learning.BaseRatesAsync(ct)).ContainsKey(StrategyNames.EquityMeanrev) && champion?.Model?.Strategies.Contains(StrategyNames.EquityMeanrev) == true, ct); + _rules = await learning.Shadow.LoadRulesAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync("FINNHUB_API_KEY"), ct); + _measured = await learning.RulesMeasuredAsync(ct); _reviews = await QuarterlyReview.ListAsync(services.Db, ct); _nextReview = QuarterlyReview.NextDue(Zones.DayIn(Clock.UtcNow, Zones.Rome), await QuarterlyReview.LastQuarterAsync(services.Db, Clock, ct)); _running = _trials.Any(t => !t.IsFinished); diff --git a/src/Anubis.Server/Components/Pages/Notizie.razor b/src/Anubis.Server/Components/Pages/Notizie.razor index cc03af3..2773797 100644 --- a/src/Anubis.Server/Components/Pages/Notizie.razor +++ b/src/Anubis.Server/Components/Pages/Notizie.razor @@ -17,14 +17,18 @@ }; var shown = _all ? rows : rows.Take(Shown).ToList(); } +@if (v.Measured) +{ +

Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola.

+}

@Lead(v)

-

Cosa ho letto e cosa ne ho fatto

+

@(v.Measured ? "Cosa ho letto e cosa avrebbe fatto ogni regola" : "Cosa ho letto e cosa ne ho fatto")

@@ -74,7 +78,11 @@ Importanza @n.Importance su 5

- @if (n.Active) + @if (v.Measured) + { +

Cosa avrebbe fatto la regola: @Inline(n.Action)

+ } + else if (n.Active) {

Cosa ho fatto: @Inline(n.Action)

} @@ -124,7 +132,7 @@ } -

Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.

+

@(v.Measured ? "Paura e avidità è solo registrato: non entra più nel modello. Il nervosismo di Wall Street e le scommesse a leva restano indizi del modello, come numeri del mercato. Da soli non fanno comprare né vendere." : "Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.")

@Anubis.Data.FearGreed.Attribution.

@@ -211,17 +219,21 @@ private static string Lead(NewsView v) { var read = v.Board.Read == 1 ? "1 notizia letta" : $"{v.Board.Read} notizie lette"; - var active = v.Board.Active switch + var active = (v.Measured, v.Board.Active) switch { - 0 => "nessuna con un effetto in corso", - 1 => "1 con un effetto in corso", - var n => $"{n} con un effetto in corso", + (true, 0) => "nessuna su cui una regola avrebbe agito", + (true, 1) => "1 su cui una regola avrebbe agito", + (true, var n) => $"{n} su cui una regola avrebbe agito", + (_, 0) => "nessuna con un effetto in corso", + (_, 1) => "1 con un effetto in corso", + (_, var n) => $"{n} con un effetto in corso", }; return $"{read} nelle ultime 24 ore, {active}."; } private string Empty(NewsView v) => _filter switch { + "effetto" when v.Measured => "Nessuna regola avrebbe agito: compro e vendo come dicono le strategie, come sempre.", "effetto" => "Nessuna notizia ha un effetto in corso: compro e vendo come dicono le strategie.", "posizioni" => "Nessuna notizia sulle tue posizioni nelle ultime 24 ore.", _ when !v.Collecting && !Shell.IsDemo => "Non leggo ancora notizie: la raccolta parte con i dati di mercato. Le fonti si scelgono nelle impostazioni.", diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index 21ac9d9..f5cf665 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -137,17 +137,21 @@ }
-
Prossimo blocco in programma
+
@(v.RulesMeasured ? "Prossimo dato macro (solo registrato)" : "Prossimo blocco in programma")
@if (v.NextCalendarBlock is { } next) { -
@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")@next.Title: in quell'ora non apro posizioni.
+
@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")@next.Title: @(v.RulesMeasured ? "con le regole attive in quell'ora non aprirei posizioni; ora le apro come sempre." : "in quell'ora non apro posizioni.")
} else {
Nessun dato economico importante nei prossimi 14 giorni.
}
Ultimo blocco scattato
- @if (v.LastCalendarBlock is { } last) + @if (v.RulesMeasured) + { +
Nessun blocco: le regole delle notizie e del calendario sono solo misurate.
+ } + else if (v.LastCalendarBlock is { } last) {
@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")@last.Title.
} diff --git a/src/Anubis.Server/Components/ReviewReportView.razor b/src/Anubis.Server/Components/ReviewReportView.razor index 6a9484f..4e78083 100644 --- a/src/Anubis.Server/Components/ReviewReportView.razor +++ b/src/Anubis.Server/Components/ReviewReportView.razor @@ -67,7 +67,7 @@ else }

Bilancio delle restrizioni

-

Acquisti fermati da notizie e calendario e come sarebbero finiti, dal @LabText.Day(r.RestrictionsFrom) e da quando Anubis è in funzione. La riga delle trimestrali non è misurata: agisce dentro la strategia, prima del segnale.

+

Acquisti fermati da notizie e calendario e come sarebbero finiti, dal @LabText.Day(r.RestrictionsFrom) e da quando Anubis è in funzione: la storia del periodo in cui le regole agivano. Le trimestrali sono misurate nella tabella delle regole in ombra, qui sotto.

@if (restrictions.Count == 0) {

Nessun acquisto fermato finora.

@@ -102,3 +102,35 @@ else [Parameter, EditorRequired] public Review Review { get; set; } = null!; } + +

Regole esterne misurate in ombra

+@if (r.ShadowRules.Count == 0) +{ +

Questa revisione è di prima della misura in ombra (ADR 0023).

+} +else +{ +

Cosa avrebbero fatto notizie, calendario e trimestrali mentre erano solo misurate, al giorno della revisione. Il bot non riaccende niente da solo.

+
+ + + + + @foreach (var x in r.ShadowRules) + { + + + + + + + + + + + } + +
Regole esterne misurate in ombra al giorno della revisione
RegolaEsaminatiIngressi cambiatiSolo rinviatiAumenti fermatiStop tenuti fermiEffetto medio a ingressoStato
@x.Name@x.Examined@x.Changed@x.Postponed@x.Increases@(x.Key == Anubis.Learning.ShadowRules.NewsSevere ? x.StopsKept.ToString(System.Globalization.CultureInfo.InvariantCulture) : "—")@(x.Mean is { } mean ? Anubis.Learning.ImprovementText.Percent(mean) : "—")@if (x.Low is { } low && x.High is { } high) { tra @Anubis.Learning.ImprovementText.Percent(low) e @Anubis.Learning.ImprovementText.Percent(high)}@if (x.Missing is { } few) { (@few)}@x.State@if (x.JudgedFrom is { } from) {, giudizio non prima del @Format.LongDate(from)}
+
+

Intervallo al 99%: contiene il valore vero 99 volte su 100. Criterio per riaccendere una regola: 6 mesi, @Anubis.Learning.ShadowRules.MinChanged ingressi cambiati, effetto tutto sopra lo zero.

+} diff --git a/src/Anubis.Server/Components/ShadowRulesTable.razor b/src/Anubis.Server/Components/ShadowRulesTable.razor new file mode 100644 index 0000000..7c54e66 --- /dev/null +++ b/src/Anubis.Server/Components/ShadowRulesTable.razor @@ -0,0 +1,30 @@ +@* The rules of ADR 0023 measured in the shadow (ADR 0027 points 16 and 17): the Laboratorio and the quarterly review show the same table. *@ +@using Anubis.Learning + +
+ + + + + @foreach (var r in Rules) + { + + + + + + + + + + + } + +
Regole esterne misurate in ombra
RegolaEsaminatiIngressi cambiatiSolo rinviatiAumenti fermatiStop tenuti fermiEffetto medio a ingressoStato
@r.Rule.Name
@r.Rule.What
@r.Examined@r.Changed@r.Postponed@r.Increases@(r.Rule.Key == ShadowRules.NewsSevere ? r.StopsKept.ToString(System.Globalization.CultureInfo.InvariantCulture) : "—")@(r.Line.Mean is { } mean ? ImprovementText.Percent(mean) : "—")@if (r.Line.Interval is { } i) { tra @ImprovementText.Percent(i.Low) e @ImprovementText.Percent(i.High)}@if (r.Line.Missing is { } missing) { (@missing)}@r.State@if (r.State == "Troppo presto" && r.JudgedFrom is { } from) {
giudizio non prima del @Format.LongDate(from)}
+
+

Per riaccendere una regola servono almeno 6 mesi di misura, almeno @ShadowRules.MinChanged ingressi cambiati e un effetto tutto sopra lo zero, con un intervallo che contiene il valore vero 99 volte su 100 (5% diviso per cinque regole); il confronto in backtest della Fase 17 non è ancora disponibile. L'effetto è una quota di quanto l'ingresso ha investito: positivo vuol dire che la regola avrebbe evitato una perdita. Un rinvio e un aumento si contano ma non si valutano. Il bot non riaccende niente da solo: lo fai tu, dalle Impostazioni.

+ +@code { + [Parameter, EditorRequired] + public IReadOnlyList Rules { get; set; } = []; +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 922e608..37e11ca 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -154,7 +154,7 @@ internal static partial class Endpoints } // And for the rules of the news, and where the model's key goes: the page asks for the password. - if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key)) + if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key) || key == Anubis.News.ExternalRules.Setting.Key) { return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le regole delle notizie e il modello linguistico si cambiano da Impostazioni, con la password quando serve."); } diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 62f0a41..c01d21b 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -272,17 +272,23 @@ internal static partial class Forms var back = Back(form, "/impostazioni"); var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key); var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key); + var rules = key == Anubis.News.ExternalRules.Setting.Key; if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key && - !news && !model) + !news && !model && !rules) { return Results.Redirect(With(back, "errore", "impostazione")); } - if ((news || model) && host.IsDemo) + if ((news || model || rules) && host.IsDemo) { return Results.Redirect(With(back, "errore", "motore")); } + if (rules && host.Services is { } services0) + { + return Results.Redirect(await ExternalRulesAsync(services0, clock, form, context, ct).ConfigureAwait(false) is { } problem ? With(back, "errore", problem) : back); + } + if (model) { // Amounts as the user writes them, "0,50" or "0,50 €", stored as "0.50"; the other values trimmed. @@ -327,6 +333,38 @@ internal static partial class Forms return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione")); } + /// + /// The general switch of ADR 0023 (ADR 0027 points 4 and 5): only measuring the rules takes restrictions away, so with + /// real money it asks for the phrase and the password, as switching a row off; acting again is free. A real change + /// writes its diary line in the same transaction. Null when saved, otherwise the error code of the page. + /// + private static async Task ExternalRulesAsync(AppServices app, IClock clock, IFormCollection form, HttpContext context, CancellationToken ct) + { + var value = form["valore"].ToString(); + if (value is not (Anubis.News.ExternalRules.Measured or Anubis.News.ExternalRules.Active)) + { + return "impostazione"; + } + + var key = Anubis.News.ExternalRules.Setting.Key; + if (value == Anubis.News.ExternalRules.Measured && (await app.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value != Anubis.News.ExternalRules.Measured && + await RaiseRefusalAsync(app, clock, null, form, ct).ConfigureAwait(false) is { } refusal) + { + return refusal; + } + + var by = context.User.Identity?.Name ?? "utente"; + try + { + await app.Settings.SetAsync(key, value, by, (s, old) => Anubis.News.ExternalRules.WriteChangeAsync(s, clock, old, value, by, ct), ct).ConfigureAwait(false); + return null; + } + catch (ReadOnlySettingException) + { + return "impostazione"; + } + } + private static async Task BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/"); diff --git a/src/Anubis.Server/LearningView.cs b/src/Anubis.Server/LearningView.cs index 22db6c8..0a263ac 100644 --- a/src/Anubis.Server/LearningView.cs +++ b/src/Anubis.Server/LearningView.cs @@ -20,6 +20,9 @@ internal static class LearningStates /// Set aside by the user. public const string Manual = "manual"; + + /// Set aside because it uses an outside clue while news, calendar and earnings are only measured (ADR 0027 point 19). + public const string Rules = "rules"; } /// A band of estimates: percentages as they are read, the point at the mean estimate. @@ -52,6 +55,7 @@ internal sealed record LearningSummary(string State, int Signals, int Needed, in LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.", LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.", LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.", + LearningStates.Rules => "Il modello è messo da parte: usa indizi che ora sono solo misurati.", _ => "Il modello osserva e impara, ma non decide ancora.", }; } @@ -159,10 +163,11 @@ internal sealed record LearningView var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false); var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false); var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); - return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow); + return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false), + host.Clock.UtcNow); } - private static LearningSummary Summarise(IReadOnlyList models, int evaluated, CycleState state, bool aside, DateTimeOffset now) + private static LearningSummary Summarise(IReadOnlyList models, int evaluated, CycleState state, bool aside, bool measured, DateTimeOffset now) { var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion); var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger); @@ -170,6 +175,7 @@ internal sealed record LearningView var status = champion is null ? LearningStates.None : aside ? LearningStates.Manual : state.Aside is not null ? LearningStates.Aside + : measured && Clues.HasExternal(champion.Model?.Clues) ? LearningStates.Rules : state.ActivatedAt is not null ? LearningStates.Active : LearningStates.Observation; return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now), @@ -199,22 +205,26 @@ internal sealed record LearningView var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false); var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false); - return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow); + return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow, + await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false)); } - /// The page from what was read, without touching the database. + /// The page from what was read, without touching the database. : news, calendar and earnings only measured (ADR 0023). public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary baseRates, IReadOnlyDictionary capitals, bool aside, DiscoverySet discoveries, - IReadOnlyList events, DateTimeOffset now) + IReadOnlyList events, DateTimeOffset now, bool measured = false) { ArgumentNullException.ThrowIfNull(snapshot); ArgumentNullException.ThrowIfNull(discoveries); ArgumentNullException.ThrowIfNull(events); var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State); var inCharge = snapshot.InCharge; - var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now); + var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, measured, now); var activation = ActivationCheck.Of(inCharge, baseRates, capitals); var last = snapshot.Models.LastOrDefault(m => m.Version is not null); - var (title, text) = Words(summary, state, now); + var outside = measured && Clues.HasExternal(champion?.Model?.Clues); + // A challenger without the outside clues is already the one trained in its place. + var clean = challenger is not null && !Clues.HasExternal(challenger.Model?.Clues) ? challenger.Version : null; + var (title, text) = Words(summary, state, now, outside, clean); // What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene". var live = Judge.Bands(inCharge); @@ -248,7 +258,7 @@ internal sealed record LearningView News = discoveries.News, Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))], }; - view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []); + view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? [], measured, outside); if (champion is not null) { view = view with @@ -269,7 +279,7 @@ internal sealed record LearningView }; } - private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now) + private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now, bool outside = false, int? clean = null) { const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero."; const string Limits = "Non potrà mai ingrandirle, né aprirne di sue."; @@ -280,7 +290,9 @@ internal sealed record LearningView LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.", $"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."), LearningStates.Aside => ("Per ora è messo da parte.", - $"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."), + $"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} {(outside ? "Anche quando l'anomalia rientra resta da parte, perché usa indizi che ora sono solo misurati" : "Torna da solo quando l'anomalia rientra")}{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."), + LearningStates.Rules => ("Per ora è messo da parte.", + $"Usa notizie, trimestrali o paura e avidità, che ora sono solo misurate: non cambia nessuna operazione nuova. {Alone} Continua a stimare e a imparare; {(clean is { } version ? string.Create(CultureInfo.InvariantCulture, $"la versione {version}, senza quegli indizi, è già in prova come sfidante.") : "la domenica ne addestro uno senza quegli indizi, che entra in prova come sfidante.")}"), 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}"), @@ -382,7 +394,8 @@ internal sealed record LearningView (between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : ""); } - private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights) + // uses: the model in charge has an outside clue in its list, even one that weighs nothing (then it is set aside). + private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights, bool measured, bool uses = false) { var rest = weights.Skip(NamedWeights).Sum(w => w.Share); var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList(); @@ -393,7 +406,10 @@ 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 outside = weights.Where(w => Clues.ExternalGroups.Contains(w.Name)).Sum(w => w.Share); var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime." + : measured && !uses && outside == 0 ? "Notizie, trimestrali, paura e avidità non entrano nel modello: le decisioni guardano solo i numeri del mercato." + : measured ? $"Il modello usa notizie, trimestrali o paura e avidità (pesano {outside} su 100), che ora sono solo misurate: per questo è messo da parte." : 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." @@ -515,7 +531,8 @@ 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), 0, summary.NextCheck, champion.Version, challenger.Version); + // The demo shows a new installation: news, calendar and earnings only measured (ADR 0027 point 24). + return WithTrial(WithWeights(view, named, measured: true), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version); } // ---- Words -------------------------------------------------------------------------------------------------- diff --git a/src/Anubis.Server/NewsView.cs b/src/Anubis.Server/NewsView.cs index cc48267..396ead2 100644 --- a/src/Anubis.Server/NewsView.cs +++ b/src/Anubis.Server/NewsView.cs @@ -40,6 +40,9 @@ internal sealed record NewsView( public const int CalendarRows = 6; + /// News, calendar and earnings only measured (ADR 0023): the page is an archive of what each rule would have done. + public bool Measured => Board.Measured; + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; public static async Task LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) @@ -52,7 +55,7 @@ internal sealed record NewsView( var board = await new NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false); var switches = await NewsRuleSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); var mood = await MoodAsync(new MoodStore(services.Db, clock), now, cancellationToken).ConfigureAwait(false); - var calendar = await CalendarAsync(services, clock, shell.Zone, switches, cancellationToken).ConfigureAwait(false); + var calendar = await CalendarAsync(services, clock, shell.Zone, switches, board.Measured, cancellationToken).ConfigureAwait(false); using var aggregates = shell.Aggregates(); if (aggregates?.RootElement.GetProperty("notizie") is { } demo) @@ -120,7 +123,7 @@ internal sealed record NewsView( // The events that change something or that the user expects to see: this week's US and euro data of medium or high // impact, the central banks of the next month, the earnings of the stocks held or watched. - private static async Task> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches, + private static async Task> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches, bool measured, CancellationToken cancellationToken) { var now = clock.UtcNow; @@ -133,20 +136,26 @@ internal sealed record NewsView( return (h, n); }, cancellationToken).ConfigureAwait(false); var stocks = held.ToHashSet(StringComparer.Ordinal); + // Measured: no note is written, so the candidates come from the list the filter of the earnings reads, within the + // reach the notes would have had (ADR 0027). + var candidates = measured ? await NewsWatcher.WatchedStocksAsync(services.Db, cancellationToken).ConfigureAwait(false) : new HashSet(); + var reach = NewsDesk.EarningsReach(now); + var withNote = noted.ToHashSet(StringComparer.Ordinal); var shown = events.Where(e => e.Kind switch { CalendarEventKinds.Economic => e.OccursAt - now <= EconomicAhead && e.Currency is "USD" or "EUR" && e.Impact is "High" or "Medium", CalendarEventKinds.CentralBank => true, - CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey)), + CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey) + || (candidates.Contains(s) && Zones.DayIn(e.OccursAt, Zones.NewYork) <= reach)), _ => false, }).OrderBy(e => e.OccursAt).Take(CalendarRows); - return [.. shown.Select(e => Row(e, now, zone, switches))]; + return [.. shown.Select(e => Row(e, now, zone, switches, measured))]; } - private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches) + private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches, bool measured) { var local = TimeZoneInfo.ConvertTime(e.OccursAt, zone); var day = DateOnly.FromDateTime(local.DateTime); @@ -163,7 +172,9 @@ internal sealed record NewsView( "amc" => (", dopo la chiusura", "fino alla seduta dopo i conti"), _ => ("", "fino alla seduta dopo i conti"), }; - return switches.Earnings + return measured + ? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: con le regole attive niente mean reversion {until}. Solo registrato.", false) + : switches.Earnings ? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: niente mean reversion {until}", true) : new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: la regola è spenta, nessun effetto", false); } @@ -177,6 +188,13 @@ internal sealed record NewsView( }; if (CalendarBlocks.Window(e) is { } window) { + if (measured) + { + var start = TimeZoneInfo.ConvertTime(window.From, zone); + var end = TimeZoneInfo.ConvertTime(window.To, zone); + return new CalendarRow(whenText, e.Title, string.Create(_it, $"{impact}: con le regole attive nessun nuovo ingresso dalle {start:HH:mm} alle {end:HH:mm}. Solo registrato."), false); + } + if (!switches.Macro) { return new CalendarRow(whenText, e.Title, impact + ": la regola è spenta, nessun blocco", false); diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs index c28f569..4efb93a 100644 --- a/src/Anubis.Server/PanoramaView.cs +++ b/src/Anubis.Server/PanoramaView.cs @@ -50,9 +50,13 @@ internal sealed record PanoramaView( { ArgumentNullException.ThrowIfNull(board); ArgumentNullException.ThrowIfNull(shell); + // With the rules only measured nothing is in force: the tile says what the rule would have done (ADR 0027 point 23). return [.. board.Rows.Where(r => r.Active || r.OnPositions).Take(3).Select(r => new PanoramaNews( Format.ShortDate(r.At, shell.Now, shell.Zone), "su " + r.About, r.Title, - r.Active ? $"{r.Tone.Split(',')[0]}: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].TrimEnd('.')}" : "Nessun effetto: non cambio nulla", r.Active))]; + r.Active && board.Measured && r.Action.StartsWith("Con le regole attive", StringComparison.Ordinal) + ? $"Evento in arrivo: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].Replace(". Solo registrato.", ", solo registrato", StringComparison.Ordinal)}" + : r.Active && board.Measured ? $"{r.Tone.Split(',')[0]}: la regola l'avrebbe fermata, solo registrato" + : r.Active ? $"{r.Tone.Split(',')[0]}: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].TrimEnd('.')}" : "Nessun effetto: non cambio nulla", r.Active && !board.Measured))]; } public static async Task LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken) diff --git a/src/Anubis.Server/RiskView.cs b/src/Anubis.Server/RiskView.cs index 6b947b8..71d5eb2 100644 --- a/src/Anubis.Server/RiskView.cs +++ b/src/Anubis.Server/RiskView.cs @@ -56,6 +56,9 @@ internal sealed record RiskView( bool HasPositions, IReadOnlyList Tripped) { + /// News, calendar and earnings only measured (ADR 0023): the figures block nothing, they are only recorded. + public bool RulesMeasured { get; init; } + /// After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it. public ProtectedRestartView? ProtectedRestart { get; init; } @@ -162,6 +165,7 @@ internal sealed record RiskView( positions.Count > 0, tripped) { ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false), + RulesMeasured = await Anubis.News.ExternalRules.MeasuredAsync(services.Settings, cancellationToken).ConfigureAwait(false), }; } diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs index 4ca2890..483f1b9 100644 --- a/src/Anubis.Server/StrategiesView.cs +++ b/src/Anubis.Server/StrategiesView.cs @@ -99,9 +99,14 @@ internal sealed record StrategiesView(IReadOnlyList Cards, IReadOn ], }; + /// The lines of a strategy as the rules of the news are now: with them only measured the earnings change nothing (ADR 0023). + public static IReadOnlyList RulesOf(string strategy, bool measured) => + [.. (Rules.GetValueOrDefault(strategy) ?? []).Select(r => measured && r == "Salta i giorni prima delle trimestrali" ? "Trimestrali solo misurate: non salta i giorni prima" : r)]; + public static async Task LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(services); + var measured = await Anubis.News.ExternalRules.MeasuredAsync(services.Settings, cancellationToken).ConfigureAwait(false); var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock); var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m; @@ -212,7 +217,7 @@ internal sealed record StrategiesView(IReadOnlyList Cards, IReadOn : null; var flows = equity?.Flows ?? 0m; cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"), - family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result), + family?.Description ?? "", RulesOf(stage.Strategy, measured), account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result), flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)], requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap)); } diff --git a/src/Anubis/Backtest/QuarterlyReview.cs b/src/Anubis/Backtest/QuarterlyReview.cs index 88d1352..27c7582 100644 --- a/src/Anubis/Backtest/QuarterlyReview.cs +++ b/src/Anubis/Backtest/QuarterlyReview.cs @@ -90,6 +90,25 @@ public sealed record ReviewReport public RestrictionReport Restrictions { get; init; } = new([]); public RestrictionReport RestrictionsEver { get; init; } = new([]); + + /// + /// The rules of ADR 0023 measured in the shadow, as they stood on the day of the review (ADR 0027 point 17). Empty in the + /// reviews published before Phase 11. + /// + public IReadOnlyList ShadowRules { get; init; } = []; +} + +/// A rule measured in the shadow, frozen in a published review. +public sealed record ShadowRuleLine(string Key, string Name, string What, int Examined, int Changed, int Postponed, int StopsKept, double? Mean, double? Low, double? High, + string? Missing, string State, DateOnly? JudgedFrom, int Increases = 0) +{ + public static ShadowRuleLine Of(ShadowRuleView view) + { + ArgumentNullException.ThrowIfNull(view); + var interval = view.Line.Interval; + return new ShadowRuleLine(view.Rule.Key, view.Rule.Name, view.Rule.What, view.Examined, view.Changed, view.Postponed, view.StopsKept, view.Line.Mean, interval?.Low, interval?.High, + view.Line.Missing, view.State, view.State == "Troppo presto" ? view.JudgedFrom : null, view.Increases); + } } /// A row of quarterly_reviews. @@ -120,6 +139,12 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator private readonly ILogger _logger = logger ?? NullLogger.Instance; + /// + /// Whether the keys of Alpaca and Finnhub are there, read as the Laboratorio reads them: the table of the rules in the + /// shadow says the same thing in both places. Without it the review falls back to the data it finds. + /// + public Func>? Keys { get; init; } + private sealed record State(string Quarter); public static string QuarterOf(DateOnly day) => string.Create(CultureInfo.InvariantCulture, $"{day.Year:0000}-Q{((day.Month - 1) / 3) + 1}"); @@ -276,6 +301,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false); var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false); var restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false); + var keys = Keys is { } read ? await read(cancellationToken).ConfigureAwait(false) + : (stockBars, await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM calendar_events WHERE kind = @k", ("k", CalendarEventKinds.Earnings)), cancellationToken).ConfigureAwait(false) > 0); + var rules = await learning.Shadow.LoadRulesAsync(keys.Item1, keys.Item2, cancellationToken).ConfigureAwait(false); var report = new ReviewReport { Missing = missing, @@ -284,6 +312,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome), Restrictions = restrictions, RestrictionsEver = RestrictionBalance.Add(previous?.Report?.RestrictionsEver, restrictions), + ShadowRules = [.. rules.Select(ShadowRuleLine.Of)], }; var lines = new List(); foreach (var stage in all) diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index f07f721..9d447c3 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]); public static readonly IReadOnlyList All = - [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All]; + [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary(); @@ -65,7 +65,14 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead return new SettingValue(key, saved is null ? definition.Default : JsonSerializer.Deserialize(saved)!, false, null); } - public async Task SetAsync(string key, string value, string changedBy, CancellationToken cancellationToken = default) + public Task SetAsync(string key, string value, string changedBy, CancellationToken cancellationToken = default) => + SetAsync(key, value, changedBy, null, cancellationToken); + + /// + /// Saves a value. runs in the same transaction, with the old value, only when the + /// value really changes: a diary line that must exist exactly when the change does. Returns whether it changed. + /// + public async Task SetAsync(string key, string value, string changedBy, Func? alsoWhenChanged, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(value); var definition = Definition(key); @@ -84,10 +91,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead throw new ArgumentException(problem, nameof(value)); } - var now = clock.UtcNow; var json = new DbJson(JsonSerializer.Serialize(value)); var changed = await db.WriteAsync(async s => { + // The time of the change is taken under the writer's lock: a reader of the log never sees it out of order. + var now = clock.UtcNow; var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false); if (old == json.Text) { @@ -108,6 +116,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead var previous = old is null ? new DbJson(JsonSerializer.Serialize(definition.Default)) : new DbJson(old); await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("o", previous), ("n", json), ("by", changedBy), ("t", now)).ConfigureAwait(false); + if (alsoWhenChanged is not null) + { + await alsoWhenChanged(s, JsonSerializer.Deserialize(previous.Text)!).ConfigureAwait(false); + } + return true; }, cancellationToken).ConfigureAwait(false); @@ -115,6 +128,25 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead { bus.Publish(new SettingChanged(key, value)); } + + return changed; + } + + /// + /// The value a setting had at : the old value of the first change after it, or the value of now + /// when nothing changed since. Values of the startup configuration never change. + /// + public async Task ValueAtAsync(string key, DateTimeOffset at, CancellationToken cancellationToken = default) + { + var now = await GetAsync(key, cancellationToken).ConfigureAwait(false); + if (now.ReadOnly) + { + return now.Value; + } + + var then = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT old_value FROM config_history WHERE key = @k AND created_at > @at ORDER BY created_at, id LIMIT 1", + r => r.TextOrNull("old_value"), ("k", key), ("at", at)), cancellationToken).ConfigureAwait(false); + return then is null ? now.Value : JsonSerializer.Deserialize(then) ?? now.Value; } /// The change log, newest first. Secret values never appear: their entries say only "impostato" or "tolto". diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json index eb0b652..460b15f 100644 --- a/src/Anubis/Demo/Data/aggregates.json +++ b/src/Anubis/Demo/Data/aggregates.json @@ -54,8 +54,8 @@ "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50", "fonti": [{ "nome": "Alpaca News", "frequenza": "in tempo reale" }, { "nome": "14 testate e banche centrali", "frequenza": "ogni 2 minuti" }, { "nome": "Comunicati alla SEC", "frequenza": "ogni 2 minuti" }, { "nome": "Calendario economico", "frequenza": "aggiornato alle 08:00" }], "panoramica": [ - { "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: per 24 ore non aumento SOL", "in_corso": true }, - { "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: niente mean reversion su JPM fino a martedì", "in_corso": true }, + { "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: la regola l'avrebbe fermata, solo registrato", "in_corso": false }, + { "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: con le regole attive niente mean reversion su JPM, solo registrato", "in_corso": false }, { "quando": "07:52", "riguarda": "sul mercato in generale", "titolo": "I verbali della banca centrale USA non cambiano le attese sui tassi", "effetto": "Nessun effetto: non cambio nulla", "in_corso": false } ] }, @@ -87,7 +87,7 @@ "fasce_testo": "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.", "indizi": [ { "nome": "Forza della tendenza", "peso": 22 }, { "nome": "Agitazione recente dei prezzi", "peso": 17 }, { "nome": "Fase generale del mercato", "peso": 14 }, - { "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Tono delle notizie, 3 giorni", "peso": 9 }, { "nome": "Paura o avidità", "peso": 8 }, + { "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Nervosismo di Wall Street", "peso": 9 }, { "nome": "Quota di titoli in salita", "peso": 8 }, { "nome": "Volumi scambiati", "peso": 7 }, { "nome": "Scommesse a leva sulle crypto", "peso": 5 }, { "nome": "Giorno della settimana", "peso": 3 }, { "nome": "Altro", "peso": 4 } ], diff --git a/src/Anubis/Demo/Data/journal.csv b/src/Anubis/Demo/Data/journal.csv index 825406a..13423d2 100644 --- a/src/Anubis/Demo/Data/journal.csv +++ b/src/Anubis/Demo/Data/journal.csv @@ -1,16 +1,10 @@ Giorno;Ora;Voce;Tipo Oggi;08:20;Controllo periodico: registri in ordine, conto Alpaca allineato.;Sistema Oggi;08:00;Inviato il riepilogo del mattino su Telegram.;Sistema -Oggi;07:52;Notizia sui verbali della banca centrale USA: nessun effetto.;Notizie -Oggi;06:10;Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.;Notizie Oggi;03:00;Controllo del modello: nessuna anomalia.;Apprendimento Oggi;02:06;Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.;Ordini Oggi;02:05;Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.;Decisioni -Ieri;22:41;Ho messo una restrizione fino a martedì: niente mean reversion su JPM. Motivo: JPMorgan pubblica i conti martedì prima dell'apertura.;Notizie Ieri;22:21;Azioni: nessun nuovo acquisto. AAPL resta aperta: non è ancora tornata sopra la media a 5 giorni.;Decisioni Ieri;21:58;Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni. (con il collegamento "Perché l'ho comprata e venduta");Ordini -Ieri;18:20;Ricontrollata la voce sui prelievi rallentati di un exchange: rientrata.;Notizie -Ieri;16:20;Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.;Notizie Ieri;15:36;Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.;Ordini Ieri;15:35;Rimessi 6 stop giornalieri sulle frazioni di azione.;Ordini -Ieri;14:31;Richieste di sussidi USA sotto le attese: impatto medio, nessun blocco.;Notizie diff --git a/src/Anubis/Learning/Clues.cs b/src/Anubis/Learning/Clues.cs index 44ea0ff..d8a9b0a 100644 --- a/src/Anubis/Learning/Clues.cs +++ b/src/Anubis/Learning/Clues.cs @@ -10,9 +10,10 @@ namespace Anubis.Learning; /// /// A clue of SPEC 11.2. is what the interface calls it: several clues may tell the same thing. /// is false for one whose past cannot be rebuilt here: it stays out of the model until at least -/// live examples contain it. +/// live examples contain it. marks the clues of news, earnings and fear and +/// greed: with those rules only measured no model may use them (ADR 0023 point 2, ADR 0027 point 18). /// -public sealed record Clue(string Key, string Group, bool FromHistory); +public sealed record Clue(string Key, string Group, bool FromHistory, bool External = false); /// What was known outside the bars at a decision: each value only if it was already out and already read. public sealed record OutsideView @@ -84,16 +85,16 @@ public static class Clues new(Breadth, "Quota di titoli in salita", true), new(WeekSin, "Giorno della settimana", true), new(WeekCos, "Giorno della settimana", true), - new(Tone1, "Tono delle notizie, 1 giorno", false), - new(Tone3, "Tono delle notizie, 3 giorni", false), - new(Count1, "Numero di notizie", false), - new(Count3, "Numero di notizie", false), - new(WorstEvent, "Notizia più grave", false), - new(FearGreed, "Paura o avidità", false), + new(Tone1, "Tono delle notizie, 1 giorno", false, External: true), + new(Tone3, "Tono delle notizie, 3 giorni", false, External: true), + new(Count1, "Numero di notizie", false, External: true), + new(Count3, "Numero di notizie", false, External: true), + new(WorstEvent, "Notizia più grave", false, External: true), + new(FearGreed, "Paura o avidità", false, External: true), new(Vix, "Nervosismo di Wall Street", false), new(Funding, "Scommesse a leva sulle crypto", false), new(OpenInterest, "Scommesse a leva sulle crypto", false), - new(EarningsDays, "Giorni alla trimestrale", false), + new(EarningsDays, "Giorni alla trimestrale", false, External: true), ]; /// The groups that come from the news, for the sentence under the weights of the clues. @@ -104,6 +105,17 @@ public static class Clues public static Clue? Find(string key) => All.FirstOrDefault(c => c.Key == key); + /// The seven outside clues: news, earnings, fear and greed. VIX, funding and open interest are market numbers and stay. + public static readonly IReadOnlySet External = All.Where(c => c.External).Select(c => c.Key).ToHashSet(StringComparer.Ordinal); + + /// The groups of the outside clues, as the page names them. + public static readonly IReadOnlySet ExternalGroups = All.Where(c => c.External).Select(c => c.Group).ToHashSet(StringComparer.Ordinal); + + public static bool IsExternal(string key) => External.Contains(key); + + /// Whether a model that studies these clues uses an outside one. + public static bool HasExternal(IEnumerable? keys) => keys?.Any(IsExternal) == true; + /// The instrument whose trend is the market's: Bitcoin for crypto, SPY for stocks. public static string? MarketOf(string strategy, StrategyContext context) { diff --git a/src/Anubis/Learning/LearningCycle.cs b/src/Anubis/Learning/LearningCycle.cs index 98a15d9..b9af7e1 100644 --- a/src/Anubis/Learning/LearningCycle.cs +++ b/src/Anubis/Learning/LearningCycle.cs @@ -130,6 +130,13 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, public async Task CheckAsync(CancellationToken cancellationToken) { var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false); + var measured = await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false); + if (measured && snapshot.State.RulesMeasuredSince is null) + { + await ChangeDayAsync(snapshot, cancellationToken).ConfigureAwait(false); + snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false); + } + if (snapshot.Champion is not { } champion) { return; @@ -141,14 +148,31 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, var health = Health.Check(champion, labelled, [.. snapshot.Examples.Where(e => e.Source == CaseSources.Live)], now); var activation = ActivationCheck.Of(snapshot.InCharge, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), await CapitalsAsync(cancellationToken).ConfigureAwait(false)); var state = snapshot.State; - var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now }; - if (state.ActivatedAt is null && activation.Passed) + var outside = measured && Clues.HasExternal(champion.Model?.Clues); + var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now, OutsideAside = outside }; + + // A model that cannot count does not start counting: the message would say the contrary of what happens. + if (state.ActivatedAt is null && activation.Passed && !outside) { next = next with { ActivatedAt = now }; } await db.WriteAsync(async s => { + // Its own reason, never the words of an alarm, and nothing to the phone (ADR 0027 point 19). + if (outside && !state.OutsideAside) + { + var text = string.Create(It, $"Metto da parte la versione {champion.Version}: usa notizie, trimestrali o paura e avidità, che ora sono solo misurate. La domenica ne addestro una senza, che entra in prova come sfidante."); + await TellAsync(s, ModelEvents.RulesAside, champion.Version, text, "Controllo del modello: " + Lower(text), notify: false, cancellationToken).ConfigureAwait(false); + } + else if (!outside && state.OutsideAside) + { + var text = !measured + ? string.Create(It, $"Notizie, calendario e trimestrali sono di nuovo attive: la versione {champion.Version} non è più da parte per i loro indizi.") + : string.Create(It, $"La versione {champion.Version} in carica non usa indizi solo misurati: nessun modello è più da parte per questo."); + await TellAsync(s, ModelEvents.RulesBack, champion.Version, text, "Controllo del modello: " + Lower(text), notify: false, cancellationToken).ConfigureAwait(false); + } + if (health.Aside is { } reason && state.Aside is null) { var text = AsideText(reason, health) + " Lo metto da parte finché non rientra: le strategie proseguono senza di lui."; @@ -157,13 +181,18 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, else if (health.Aside is null && state is { Aside: not null, AsideAt: { } since }) { var days = Math.Max(1, (int)Math.Round((now - since).TotalDays)); - var text = $"Anomalia rientrata dopo {(days == 1 ? "un giorno" : days.ToString(It) + " giorni")}: il modello non è più da parte."; + var after = days == 1 ? "un giorno" : days.ToString(It) + " giorni"; + var text = outside + ? $"Anomalia rientrata dopo {after}, ma il modello resta da parte: usa indizi che ora sono solo misurati." + : $"Anomalia rientrata dopo {after}: il modello non è più da parte."; await TellAsync(s, ModelEvents.Back, champion.Version, text, "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false); } else if (state.LastNight != today) { await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_check", - health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health) : "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false); + health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health) + : outside ? "Controllo del modello: nessuna anomalia, ma resta da parte perché usa indizi che ora sono solo misurati." + : "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false); } if (next.ActivatedAt is not null && state.ActivatedAt is null) @@ -176,6 +205,39 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, }, cancellationToken).ConfigureAwait(false); } + // Once for each installation: the day news, calendar and earnings stopped changing decisions, and how many labels made + // before it left before a report. They stay as they are (ADR 0023 point 6). + private async Task ChangeDayAsync(LearningSnapshot snapshot, CancellationToken cancellationToken) + { + // The day the decisions stopped reading the rules: the last change to «misurate», or the day the switch was + // written with this version; not the night of this check (ADR 0027 point 22). + var since = await db.ReadAsync(async s => + { + var changes = await s.QueryAsync("SELECT new_value, created_at FROM config_history WHERE key = @k ORDER BY created_at DESC, id DESC", + r => (Value: r.TextOrNull("new_value"), At: r.Moment("created_at")), ("k", News.ExternalRules.Setting.Key)).ConfigureAwait(false); + return changes.FirstOrDefault(c => c.Value is { } v && System.Text.Json.JsonSerializer.Deserialize(v) == News.ExternalRules.Measured) is { Value: not null } last + ? last.At + : await s.FirstOrDefaultAsync("SELECT created_at FROM config WHERE key = @k", r => (DateTimeOffset?)r.Moment("created_at"), ("k", News.ExternalRules.Setting.Key)) + .ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + var now = since is { } at && at < clock.UtcNow ? at : clock.UtcNow; + var before = snapshot.Examples.Count(e => e.Source == CaseSources.Live && e.Label?.ExitReason == EquityMeanrev.Reasons.ExitEarnings); + var labels = before switch + { + 0 => "Nessun esempio già etichettato usava l'uscita per trimestrale.", + 1 => "Un esempio già etichettato usava l'uscita per trimestrale e resta così.", + _ => string.Create(It, $"{before} esempi già etichettati usavano l'uscita per trimestrale e restano così."), + }; + var text = string.Create(It, $"Dal {Format.Day(Zones.DayIn(now, Zones.Rome))} notizie, calendario e trimestrali non cambiano le decisioni, e il modello non ne usa gli indizi per decidere. {labels}"); + var state = snapshot.State with { RulesMeasuredSince = now }; + await db.WriteAsync(async s => + { + await ModelStore.AddEventAsync(s, clock, ModelEvents.RulesMeasured, null, text, cancellationToken).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_" + ModelEvents.RulesMeasured, text, null, cancellationToken).ConfigureAwait(false); + await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + public static string AsideText(string reason, HealthCheck health) { ArgumentNullException.ThrowIfNull(health); @@ -217,13 +279,25 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, } var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false); + var measured = await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false); if (snapshot is { Champion: { } champion, Challenger: { } challenger }) { - await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false); - return; + if (!measured || !Clues.HasExternal(challenger.Model?.Clues)) + { + await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false); + return; + } + + // Promoted, it would be set aside at once: it leaves its place to one trained without the outside clues (ADR 0027 point 20). + await db.WriteAsync(async s => + { + await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Discarded, cancellationToken).ConfigureAwait(false); + var text = string.Create(It, $"Scartata la versione {challenger.Version}: usa indizi che ora sono solo misurati. Ne addestro una senza."); + await TellAsync(s, ModelEvents.Discarded, challenger.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); } - await TrainAsync(snapshot, sunday, cancellationToken).ConfigureAwait(false); + await TrainAsync(snapshot, sunday, measured, snapshot.Challenger is not null, cancellationToken).ConfigureAwait(false); } private Task SaveAsync(CycleState state, CancellationToken cancellationToken) => @@ -259,7 +333,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, }, cancellationToken).ConfigureAwait(false); } - private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, CancellationToken cancellationToken) + private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, bool measured, bool discarded, CancellationToken cancellationToken) { // A strategy without a base rate is not estimated, so it does not train either (ADR 0018). var rates = await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false); @@ -268,7 +342,10 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, var seen = state.TrainedOn > 0 ? state.TrainedOn : snapshot.Champion?.Examples ?? 0; var champion = snapshot.Champion; TrainingResult? result = null; - if (examples.Count != seen && (champion is not null || examples.Count >= ActivationCheck.Needed)) + // A model in charge set aside for the outside clues is trained again even without new labels: otherwise it could + // stay aside for ever (ADR 0027 point 20). So is one in place of a challenger just discarded for the same reason. + var again = measured && (discarded || Clues.HasExternal(champion?.Model?.Clues)); + if ((examples.Count != seen || again) && (champion is not null || examples.Count >= ActivationCheck.Needed)) { var input = new TrainingInput(examples) { @@ -276,6 +353,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk, Capital = await CapitalsAsync(cancellationToken).ConfigureAwait(false), Funded = await FundedAsync(cancellationToken).ConfigureAwait(false), Rule = (await desk.GateAsync(cancellationToken).ConfigureAwait(false)).Rule, + ExternalClues = !measured, }; result = await Task.Run(() => Trainer.Train(input, cancellationToken), cancellationToken).ConfigureAwait(false); state = state with { TrainedOn = examples.Count }; diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs index c6fae41..90c4793 100644 --- a/src/Anubis/Learning/LearningDesk.cs +++ b/src/Anubis/Learning/LearningDesk.cs @@ -32,6 +32,12 @@ public sealed record CycleState public int TrainedOn { get; init; } public HealthCheck? Health { get; init; } + + /// True while the model in charge is set aside because it uses an outside clue (ADR 0027 point 19). + public bool OutsideAside { get; init; } + + /// When this installation first ran with the rules only measured: the day of the change (ADR 0023 point 6). + public DateTimeOffset? RulesMeasuredSince { get; init; } } /// Why a model is set aside on its own (SPEC 11.4). @@ -48,9 +54,12 @@ public sealed record ModelEstimate(ModelRow Row, double Probability, double Base /// What decides about the operations at a decision: the model in charge, the one on trial, and whether it counts. public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, MultiplierRule Rule, IReadOnlyDictionary BaseRates, bool Counts) { - /// It would count, but it is set aside: by an alarm or by the user. + /// It would count, but it is set aside: by an alarm, by the user, or because it uses an outside clue. public bool Aside { get; init; } + /// Set aside because it uses an outside clue while those rules are only measured (ADR 0027 point 19). + public bool OutsideClues { get; init; } + public static readonly ModelGate None = new(null, null, MultiplierRule.Standard, new Dictionary(), false); /// Without a base rate for the strategy, or a model that studied it, there is no estimate (ADR 0018). @@ -211,14 +220,27 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor public async Task CycleAsync(CancellationToken cancellationToken) => await Store.StateAsync(CycleState.Key, cancellationToken).ConfigureAwait(false) ?? new CycleState(); - public async Task GateAsync(CancellationToken cancellationToken) + /// Whether news, calendar and earnings are only measured now (ADR 0023); without settings they act. + public Task RulesMeasuredAsync(CancellationToken cancellationToken) => News.ExternalRules.MeasuredAsync(settings, cancellationToken); + + public async Task GateAsync(CancellationToken cancellationToken) => + await GateAsync(await RulesMeasuredAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + + /// + /// The gate of a decision. With the rules only measured a model in charge that uses an outside clue is set aside at + /// once, for that reason and no other (ADR 0027 point 19): it keeps estimating, and changes no size. + /// + public async Task GateAsync(bool rulesMeasured, CancellationToken cancellationToken) { var (rule, aside) = await LearningSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); var state = await CycleAsync(cancellationToken).ConfigureAwait(false); - return new ModelGate(await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false), - await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, await BaseRatesAsync(cancellationToken).ConfigureAwait(false), state is { ActivatedAt: not null, Aside: null } && !aside) + var champion = await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false); + var outside = rulesMeasured && Clues.HasExternal(champion?.Model?.Clues); + return new ModelGate(champion, await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, + await BaseRatesAsync(cancellationToken).ConfigureAwait(false), state is { ActivatedAt: not null, Aside: null } && !aside && !outside) { - Aside = state.Aside is not null || aside, + Aside = state.Aside is not null || aside || outside, + OutsideClues = outside, }; } @@ -228,8 +250,12 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor /// 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). /// + /// + /// With the rules of the news only measured (, ADR 0027 point 9) the earnings dates go to + /// the shadow and nowhere else: the example has no earnings_days, so its label never leaves before a report. + /// public async Task PrepareAsync(string strategy, string stage, DateOnly day, DateTimeOffset at, BacktestDataset data, Func create, - IReadOnlyDictionary? earnings, CancellationToken cancellationToken) + IReadOnlyDictionary? earnings, bool rulesMeasured, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(create); @@ -270,9 +296,10 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor } 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); + var outside = await OrAsync(() => _outside.ReadAsync(at, specs, rulesMeasured ? null : earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false); + var gate = await OrAsync(() => GateAsync(rulesMeasured, cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false); var shadow = await OrAsync(() => Shadow.InputAsync(strategy, stage, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false); + shadow = shadow with { RulesMeasured = rulesMeasured, Earnings = rulesMeasured ? earnings : null }; return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy), shadow, create); } @@ -377,6 +404,20 @@ public sealed class LearningTurn ]; } + /// What the rules of the news would have done to this decision, for the shadow only (ADR 0027 point 13). + public void Rules(IReadOnlyList answers) + { + ArgumentNullException.ThrowIfNull(answers); + try + { + _shadow.Rules(answers); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _failed(ex); + } + } + // What the model in charge would say of an entry that was not made. private double? ProbabilityOf(StrategyContext context, Intent intent) => _gate.Estimate(new Example(Guid.Empty, _strategy, intent.Symbol, CaseSources.Live, context.Day, context.Now, intent.Reason, intent.TargetWeight ?? 0m, intent.Stop, intent.StopOffset, @@ -473,18 +514,23 @@ public sealed class LearningTurn .ConfigureAwait(false); if (estimate.InCharge) { + var data = new Dictionary + { + ["probability"] = estimate.Probability, + ["base_rate"] = estimate.BaseRate, + ["multiplier"] = estimate.Multiplier, + ["applied"] = applied, + ["version"] = estimate.Row.Version, + ["counts"] = _gate.Counts, + ["aside"] = _gate.Aside, + }; + if (_gate.OutsideClues) + { + data["outside_clues"] = true; + } + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, _strategy, account, made.Symbol, DecisionStages.Model, - applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [], - new Dictionary - { - ["probability"] = estimate.Probability, - ["base_rate"] = estimate.BaseRate, - ["multiplier"] = estimate.Multiplier, - ["applied"] = applied, - ["version"] = estimate.Row.Version, - ["counts"] = _gate.Counts, - ["aside"] = _gate.Aside, - }, now), cancellationToken).ConfigureAwait(false); + applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [], data, now), cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Anubis/Learning/ModelStore.cs b/src/Anubis/Learning/ModelStore.cs index fb904e9..9c3de29 100644 --- a/src/Anubis/Learning/ModelStore.cs +++ b/src/Anubis/Learning/ModelStore.cs @@ -49,6 +49,14 @@ public static class ModelEvents public const string SetAside = "set_aside"; public const string Back = "back"; public const string Drift = "drift"; + + /// The day news, calendar and earnings stopped changing decisions on this installation (ADR 0023 point 6). + public const string RulesMeasured = "rules_measured"; + + /// Set aside, and back, because the model in charge uses an outside clue while those rules are only measured. + public const string RulesAside = "rules_aside"; + + public const string RulesBack = "rules_back"; } /// The register of the models, their estimates and their history (SPEC 11.3–11.5). diff --git a/src/Anubis/Learning/Shadow.cs b/src/Anubis/Learning/Shadow.cs index cbf02ca..242b50d 100644 --- a/src/Anubis/Learning/Shadow.cs +++ b/src/Anubis/Learning/Shadow.cs @@ -43,6 +43,66 @@ public static class Improvements ]; } +/// +/// The five rules of news, calendar and earnings measured in the shadow while they only are measured (ADR 0023 point 4, +/// ADR 0027 points 11–17). Apart from the improvements of 8.7: their own level (99%), their own criterion, no discoveries. +/// +public static class ShadowRules +{ + public const string NewsSevere = "rule_news_severe"; + public const string NewsNegative = "rule_news_negative"; + public const string Macro = "rule_macro"; + public const string EarningsEntry = "rule_earnings_entry"; + public const string EarningsExit = "rule_earnings_exit"; + + /// The stops a serious event would have kept where they were: only counted. + public const string SevereStop = "rule_news_severe_stop"; + + /// Five rules share 5%: each is judged at 99% (ADR 0023 point 5). + public const double Level = 0.99; + + /// Months of measure before a judgement; under them the line says «troppo presto». + public const int Months = 6; + + /// Entries the rule would have changed, at least. + public const int MinChanged = 30; + + public static readonly IReadOnlyList All = + [ + new(NewsSevere, "Notizia grave", "Evento grave confermato: niente nuovi acquisti per 72 ore, lo stop resta dov'è", + [StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]), + new(NewsNegative, "Notizia negativa", "Notizia negativa confermata: niente acquisti né aumenti per 24 ore", + [StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]), + new(Macro, "Dato macro", "Dato macro ad alto impatto: niente ingressi da 30 minuti prima a 30 dopo", + [StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]), + new(EarningsEntry, "Trimestrale in ingresso", "Niente mean reversion su un titolo con i conti in arrivo entro tre sedute", [StrategyNames.EquityMeanrev]), + new(EarningsExit, "Trimestrale in uscita", "La mean reversion esce alla chiusura prima dei conti", [StrategyNames.EquityMeanrev]), + ]; + + /// The rules that look only at stocks: without the Alpaca keys they have nothing to measure. + public static bool StocksOnly(string rule) => rule is EarningsEntry or EarningsExit; +} + +/// What a rule would have done to one purchase or one stop (ADR 0027 point 13). +public enum RuleEffect +{ + None, + Postponed, + Dropped, + StopKept, +} + +/// The answer of one rule on one symbol of a decision, given by the live engine. +public sealed record RuleAnswer(string Rule, string Symbol, RuleEffect Effect, News.EntryHold? Hold); + +/// What a rule case is beside a plain entry: only counted, never valued. +public static class ShadowKinds +{ + public const string Postponed = "postponed"; + public const string Increase = "increase"; + public const string Stop = "stop"; +} + /// What an improvement would have done with a signal. A factor of 1 leaves it as it is. public sealed record ShadowCase(string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, IReadOnlyDictionary Numbers) { @@ -51,6 +111,20 @@ public sealed record ShadowCase(string Improvement, string Strategy, string Symb /// Measured later on prices (the entry time), not on the outcome of the signal. public bool OnPrices { get; init; } + + /// A rule case only counted (); null for an entry it judges. + public string? Kind { get; init; } + + /// The earnings date known at the entry, for the rule of the exit. + public DateOnly? Report { get; init; } + + /// The story or the figure behind a rule case, and when its hold would have ended. + public string? Motive { get; init; } + + public DateTimeOffset? Until { get; init; } + + /// Counted at once: an increase or a stop has no example of its own to measure. + public bool Settled => Kind is ShadowKinds.Increase or ShadowKinds.Stop; } public sealed record ShadowEntry(string Symbol, decimal Weight, decimal? StopOffset, string Reason, double? EarningsDays); @@ -119,6 +193,12 @@ public sealed record ShadowInput(IReadOnlyList OtherBooks, IReadOnly /// False when what another strategy held on that day is no longer known: the portfolio cannot be judged. public bool Whole { get; init; } = true; + + /// True when news, calendar and earnings are only measured: then their rules go to the shadow (ADR 0027 point 12). + public bool RulesMeasured { get; init; } + + /// The next earnings date of each stock known at the decision; null when the calendar is not fresh. + public IReadOnlyDictionary? Earnings { get; init; } } /// @@ -189,6 +269,56 @@ internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, Ca } Choice(context, intents, fresh); + if (input.RulesMeasured && input.Earnings is { } earnings) + { + Earnings(context, fresh, earnings); + } + } + } + + // The two rules of the earnings (ADR 0027 points 14 and 15), with the dates known at the decision. The exit is noted at + // the entry, once for the operation, and measured when the operation has its label. + private void Earnings(StrategyContext context, HashSet fresh, IReadOnlyDictionary earnings) + { + if (context.NextSession is not { } entry) + { + return; + } + + var sessions = create() is EquityMeanrev rules ? rules.EarningsSessions : new EquityMeanrevSettings().EarningsSessions; + foreach (var symbol in fresh.Order(StringComparer.Ordinal)) + { + var report = earnings.TryGetValue(symbol, out var date) && date >= day ? date : (DateOnly?)null; + var ahead = report is { } r && EquityMeanrev.EarningsAhead(day, entry, r, sessions); + _cases.Add(new ShadowCase(ShadowRules.EarningsEntry, strategy, symbol, day, ahead ? 0 : 1, Days(report)) { Report = report }); + _cases.Add(new ShadowCase(ShadowRules.EarningsExit, strategy, symbol, day, report is null ? 1 : 0, Days(report)) { Report = report }); + } + } + + private Dictionary Days(DateOnly? report) => + report is { } r ? new Dictionary(StringComparer.Ordinal) { ["report_days"] = r.DayNumber - day.DayNumber } : new Dictionary(StringComparer.Ordinal); + + /// + /// What the rules of the news and of the figures would have done to the purchases and stops of this decision (ADR 0027 + /// point 13). A new entry is judged; an increase and a stop kept are only counted. + /// + public void Rules(IReadOnlyList answers) + { + if (!input.RulesMeasured) + { + return; + } + + var fresh = collector.Cases.Where(c => c.Day == day).Select(c => c.Symbol).ToHashSet(StringComparer.Ordinal); + foreach (var a in answers) + { + var numbers = new Dictionary(StringComparer.Ordinal); + var found = new ShadowCase(a.Rule, strategy, a.Symbol, day, 1, numbers) { Motive = a.Hold?.Motive, Until = a.Effect == RuleEffect.None ? null : a.Hold?.Until }; + _cases.Add(a.Effect == RuleEffect.StopKept ? found with { Kind = ShadowKinds.Stop } + : !fresh.Contains(a.Symbol) ? found with { Kind = ShadowKinds.Increase, Factor = a.Effect == RuleEffect.None ? 1 : 0 } + : a.Effect == RuleEffect.Dropped ? found with { Factor = 0 } + : a.Effect == RuleEffect.Postponed ? found with { Kind = ShadowKinds.Postponed } + : found); } } @@ -301,14 +431,17 @@ internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, Ca /// How many signals an improvement changed and what it would have been worth, on one alternative. public sealed record ImprovementLine(string? Label, int Cases, int Months, double? Mean, double? Error) { + /// How often the interval holds the true mean: 95 times in 100 for the improvements, 99 for the rules of ADR 0023. + public double Level { get; init; } = 0.95; + /// Fewer months than these give no interval: the signals of a month move together, so a month counts as one. public const int MinMonths = 6; /// What is missing for an interval, in words; null when nothing is. public string? Missing => Cases > 0 && Months < MinMonths ? $"troppo pochi mesi per un intervallo: {Months}, ne servono {MinMonths}" : null; - /// The interval that holds the mean effect 95 times in 100; null with too few months. - public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile(0.975, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null; + /// The interval that holds the mean effect of the times; null with too few months. + public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile((1 + Level) / 2, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null; } /// An improvement as the pages show it. @@ -318,6 +451,17 @@ public sealed record ImprovementView(Improvement Improvement, int Examined, IRea public string Trust => Discovery.TrustOf(Lines.Where(l => l.Missing is null).Select(l => l.Cases).DefaultIfEmpty(0).Max()); } +/// +/// A rule of ADR 0023 as the Laboratory and the quarterly review show it: what it would have touched, what it would have been +/// worth at 99%, and whether the criterion to switch it back on is met. +/// +public sealed record ShadowRuleView(Improvement Rule, int Examined, int Changed, int Postponed, int Increases, int StopsKept, ImprovementLine Line, DateOnly? Since, + string State, bool Waiting, bool Met) +{ + /// The day the judgement can come, six months after the first case. + public DateOnly? JudgedFrom => Since?.AddMonths(ShadowRules.Months); +} + /// Saves the shadow of each decision, measures it when the outcomes are known and sums it up. public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) { @@ -364,6 +508,18 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) public IReadOnlyDictionary Numbers { get; init; } = new Dictionary(); public ShadowEntry? Instead { get; init; } + + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? Kind { get; init; } + + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public DateOnly? Report { get; init; } + + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public string? Motive { get; init; } + + [System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)] + public DateTimeOffset? Until { get; init; } } internal static async Task WriteAsync(DbSession s, IClock clock, Guid decisionId, ShadowTurn turn, string strategy, CancellationToken cancellationToken) @@ -371,13 +527,14 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) var now = clock.UtcNow; foreach (var c in turn.Cases) { - // A signal the improvement leaves alone needs no outcome: its effect is nothing. - var known = c.Factor >= 1 && !c.OnPrices; + // A signal the improvement leaves alone needs no outcome: its effect is nothing. A case only counted has none. + var known = c.Factor >= 1 && !c.OnPrices && !c.Settled; await s.ExecuteAsync( "INSERT INTO shadow_cases (id, improvement, strategy, symbol, decided_day, decision_id, factor, data, effect, measured_at, created_at, updated_at) " + "VALUES (@id, @i, @s, @sy, @d, @dec, @f, @data, @e, @m, @now, @now) ON CONFLICT (improvement, strategy, symbol, decided_day) DO NOTHING", cancellationToken, ("id", Ids.NewId(clock)), ("i", c.Improvement), ("s", c.Strategy), ("sy", c.Symbol), ("d", BarStore.DayText(c.Day)), ("dec", decisionId), ("f", c.Factor), - ("data", new DbJson(JsonSerializer.Serialize(new Stored { Numbers = c.Numbers, Instead = c.Instead }))), ("e", known ? 0.0 : null), ("m", known ? now : null), ("now", now)) + ("data", new DbJson(JsonSerializer.Serialize(new Stored { Numbers = c.Numbers, Instead = c.Instead, Kind = c.Kind, Report = c.Report, Motive = c.Motive, Until = c.Until }))), + ("e", known ? 0.0 : null), ("m", known || c.Settled ? now : null), ("now", now)) .ConfigureAwait(false); } @@ -443,6 +600,11 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) return true; } + if (o.Improvement == ShadowRules.EarningsExit && o.Data.Report is { } report) + { + return await EarningsExitAsync(o, example, result, report, dataOf, cancellationToken).ConfigureAwait(false); + } + if (o.Data.Instead is not { } entry) { await SaveAsync(o, (o.Factor - 1) * result, null, cancellationToken).ConfigureAwait(false); @@ -461,6 +623,22 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) return true; } + // The operation again with the report it knew at the entry: when the rule would have taken it out before the report, the + // effect is what that exit would have made more than the real one (ADR 0027 point 15). Otherwise it changed nothing. + private async Task EarningsExitAsync(Open o, Example example, double result, DateOnly report, + Func, CancellationToken, Task> dataOf, CancellationToken cancellationToken) + { + if (await dataOf(o.Strategy, [example], cancellationToken).ConfigureAwait(false) is not { } source || source.Data[example.Symbol] is not { } instrument + || instrument.IndexOf(example.Day) < 0 || CaseLabels.Of(example, source.Create, source.Data, source.Through, earnings: report) is not { } with) + { + return false; + } + + var exited = with.ExitReason == EquityMeanrev.Reasons.ExitEarnings && with.Result is not null; + await SaveAsync(o, exited ? with.Result!.Value - result : 0, null, cancellationToken, exited ? 0 : 1).ConfigureAwait(false); + return true; + } + private async Task EntryTimeAsync(Open o, IMarketCalendar calendar, Func>> minutes, CancellationToken cancellationToken) { @@ -498,10 +676,10 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) return true; } - private Task SaveAsync(Open o, double? effect, IReadOnlyDictionary? numbers, CancellationToken cancellationToken) => - db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET effect = @e, data = @d, measured_at = @now, updated_at = @now WHERE id = @id AND measured_at IS NULL", cancellationToken, - ("e", effect is { } e ? Math.Round(e, 8) : null), ("d", new DbJson(JsonSerializer.Serialize(numbers is null ? o.Data : o.Data with { Numbers = numbers }))), ("now", clock.UtcNow), ("id", o.Id)), - cancellationToken); + private Task SaveAsync(Open o, double? effect, IReadOnlyDictionary? numbers, CancellationToken cancellationToken, double? factor = null) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET effect = @e, data = @d, factor = @f, measured_at = @now, updated_at = @now WHERE id = @id AND measured_at IS NULL", + cancellationToken, ("e", effect is { } e ? Math.Round(e, 8) : null), ("d", new DbJson(JsonSerializer.Serialize(numbers is null ? o.Data : o.Data with { Numbers = numbers }))), + ("f", factor ?? o.Factor), ("now", clock.UtcNow), ("id", o.Id)), cancellationToken); // ---- Page --------------------------------------------------------------------------------------------------- @@ -534,6 +712,50 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store) ]; } + /// + /// The rules of ADR 0023 measured in the shadow, with the criterion to switch one back on (ADR 0027 point 16). The bot only + /// says whether it is met: switching a rule back on is the user's. + /// + public async Task> LoadRulesAsync(bool alpacaKeys, bool finnhubKey, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync("SELECT improvement, decided_day, factor, effect, data FROM shadow_cases WHERE improvement LIKE 'rule_%'", + r => new Row(r.Text("improvement"), BarStore.ParseDay(r.Text("decided_day")), r.Measure("factor"), r.IsNull("effect") ? null : r.Measure("effect"), + JsonSerializer.Deserialize(r.Json("data").Text) ?? new Stored())), cancellationToken).ConfigureAwait(false); + var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + return [.. ShadowRules.All.Select(rule => RuleView(rule, rows.Where(r => r.Improvement == rule.Key).ToList(), + rule.Key == ShadowRules.NewsSevere ? rows.Count(r => r.Improvement == ShadowRules.SevereStop) : 0, today, alpacaKeys, finnhubKey))]; + } + + private static ShadowRuleView RuleView(Improvement rule, List mine, int stops, DateOnly today, bool alpacaKeys, bool finnhubKey) + { + var valued = mine.Where(r => r is { Factor: < 1, Effect: not null } && r.Data.Kind is null).Select(r => (r.Day, r.Effect!.Value)).ToList(); + var line = Summary(null, valued) with { Level = ShadowRules.Level }; + var first = mine.Count > 0 ? mine.Min(r => r.Day) : (DateOnly?)null; + string state; + var waiting = false; + var met = false; + if (first is not { } since) + { + waiting = ShadowRules.StocksOnly(rule.Key) && (!alpacaKeys || !finnhubKey); + state = !ShadowRules.StocksOnly(rule.Key) ? "Nessun caso finora" + : !alpacaKeys ? "In attesa delle chiavi Alpaca" + : !finnhubKey ? "In attesa della chiave Finnhub" + : "Nessun caso finora"; + } + else if (today < since.AddMonths(ShadowRules.Months)) + { + state = "Troppo presto"; + } + else + { + met = valued.Count >= ShadowRules.MinChanged && line.Interval is { Low: > 0 }; + state = met ? "Criterio raggiunto" : "Criterio non raggiunto"; + } + + return new ShadowRuleView(rule, mine.Count, valued.Count, mine.Count(r => r.Data.Kind == ShadowKinds.Postponed), mine.Count(r => r.Data.Kind == ShadowKinds.Increase && r.Factor < 1), + stops, line, first, state, waiting, met); + } + private static IReadOnlyList EntryLines(List rows) => [ .. new[] { ("A 15 minuti", "gain15"), ("A 30 minuti", "gain30") }.Select(x => diff --git a/src/Anubis/Learning/Training.cs b/src/Anubis/Learning/Training.cs index 014c163..7002681 100644 --- a/src/Anubis/Learning/Training.cs +++ b/src/Anubis/Learning/Training.cs @@ -74,6 +74,9 @@ public sealed record TrainingInput(IReadOnlyList Examples) public MultiplierRule Rule { get; init; } = MultiplierRule.Standard; public long Seed { get; init; } = 11; + + /// False while news, calendar and earnings are only measured: the outside clues stay out (ADR 0027 point 18). + public bool ExternalClues { get; init; } = true; } public sealed record TrainingResult(TrainedModel Model, ModelReport Report); @@ -106,12 +109,14 @@ public static class Trainer /// The clues that enter (SPEC 11.2): those rebuilt from the history, and those without one only when at least /// live examples contain them. A clue that never changes tells nothing. /// - public static IReadOnlyList CluesOf(IReadOnlyList examples) + /// With false the outside clues never enter, however many live examples carry them. + public static IReadOnlyList CluesOf(IReadOnlyList examples, bool external = true) { ArgumentNullException.ThrowIfNull(examples); return [ - .. Clues.All.Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive) + .. Clues.All.Where(c => external || !c.External) + .Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive) .Select(c => c.Key) .Where(key => examples.Where(e => e.Features.ContainsKey(key)).Select(e => e.Features[key]).Distinct().Take(2).Count() > 1), ]; @@ -122,7 +127,7 @@ public static class Trainer { ArgumentNullException.ThrowIfNull(input); var cases = input.Examples.Where(e => e.IsLabelled).OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal).ToList(); - var clues = CluesOf(cases); + var clues = CluesOf(cases, input.ExternalClues); if (cases.Count < MinExamples || clues.Count == 0 || !BothOutcomes(cases)) { return null; diff --git a/src/Anubis/News/ExternalRules.cs b/src/Anubis/News/ExternalRules.cs new file mode 100644 index 0000000..14b3dca --- /dev/null +++ b/src/Anubis/News/ExternalRules.cs @@ -0,0 +1,87 @@ +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.News; + +/// +/// Whether news, the economic calendar and the earnings dates change decisions (ADR 0023, 0027): «misurate», the default, +/// leaves every decision to the numbers and only records what each rule would have done; «attive» is the behaviour of +/// Phase 7. It stands above the five rows of SPEC 10.5, which act only with «attive». +/// +public static class ExternalRules +{ + public const string Measured = "misurate"; + public const string Active = "attive"; + + /// The code of the diary line each real change writes. + public const string Changed = "external_rules_changed"; + + public static readonly SettingDefinition Setting = new("decisions.external_rules", "Notizie, calendario e trimestrali", Measured, [Measured, Active]); + + /// + /// Whether the rules are only measured now. Without settings, which happens only in tests that build a part alone, they + /// act, as the five rows are all on without settings. + /// + public static async Task MeasuredAsync(SettingsStore? settings, CancellationToken cancellationToken) => + settings is not null && (await settings.GetAsync(Setting.Key, cancellationToken).ConfigureAwait(false)).Value == Measured; + + /// Whether the rules were only measured at , from the change log: a decision redone later reads them as they were. + public static async Task MeasuredAtAsync(SettingsStore? settings, DateTimeOffset at, CancellationToken cancellationToken) => + settings is not null && await settings.ValueAtAsync(Setting.Key, at, cancellationToken).ConfigureAwait(false) == Measured; + + /// The value in the words of the Impostazioni page. + public static string Label(string value) => value switch + { + Measured => "solo misurate", + Active => "attive", + _ => value, + }; + + /// + /// Writes the switch once, at the first start of this version (ADR 0027 point 22). On an installation that already + /// decided something the rules acted until now: the change log gets «attive» → «misurate» at this instant, so a + /// decision redone later reads the rules as they were, and the diary says it once. A new installation only gets the + /// row, so a copy moved elsewhere carries it. Returns true when it recorded an upgrade. + /// + public static Task SettleAsync(Database db, IClock clock, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(clock); + return db.WriteAsync(async s => + { + if (await s.CountAsync("SELECT COUNT(*) FROM config WHERE key = @k", ("k", Setting.Key)).ConfigureAwait(false) > 0) + { + return false; + } + + var now = clock.UtcNow; + var measured = new DbJson(System.Text.Json.JsonSerializer.Serialize(Measured)); + await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", Setting.Key), ("v", measured), ("t", now)).ConfigureAwait(false); + if (await s.CountAsync("SELECT COUNT(*) FROM engine_runs").ConfigureAwait(false) == 0) + { + return false; + } + + await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", Setting.Key), ("o", new DbJson(System.Text.Json.JsonSerializer.Serialize(Active))), ("n", measured), ("by", Upgrade), ("t", now)) + .ConfigureAwait(false); + await Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.System, Changed, + "Con questa versione notizie, calendario e trimestrali sono solo misurate: da ora non cambiano nessuna decisione, registro solo cosa avrebbe fatto ogni regola. " + + "Per farle tornare ad agire: Impostazioni → Notizie.", new { from = Active, to = Measured, by = Upgrade }, cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + } + + /// Who changed the switch when this version found an installation where the rules acted. + public const string Upgrade = "aggiornamento"; + + /// The diary line of a change, in the same transaction as the change itself (ADR 0027 point 5). No Telegram. + public static Task WriteChangeAsync(DbSession s, IClock clock, string from, string to, string by, CancellationToken cancellationToken) + { + var text = to == Measured + ? $"Notizie, calendario e trimestrali da «{Label(from)}» a «{Label(to)}»: da ora non cambiano nessuna decisione, registro solo cosa avrebbe fatto ogni regola. Cambiato da {by}." + : $"Notizie, calendario e trimestrali da «{Label(from)}» a «{Label(to)}»: da ora le regole accese possono fermare o rinviare un acquisto. Cambiato da {by}."; + return Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.System, Changed, text, new { from, to }, cancellationToken); + } +} diff --git a/src/Anubis/News/NewsBoard.cs b/src/Anubis/News/NewsBoard.cs index e955f77..eeee19d 100644 --- a/src/Anubis/News/NewsBoard.cs +++ b/src/Anubis/News/NewsBoard.cs @@ -27,7 +27,14 @@ public sealed record NewsBoardRow( } /// The stories of the last 24 hours with what the bot did, and the three counts of the filters. -public sealed record NewsBoardResult(IReadOnlyList Rows, int Read, int OnPositions, int Active); +public sealed record NewsBoardResult(IReadOnlyList Rows, int Read, int OnPositions, int Active) +{ + /// + /// True when news, calendar and earnings are only measured (ADR 0023): says what the rule + /// would have done, and counts the stories a rule would act on now. + /// + public bool Measured { get; init; } +} /// /// What the Notizie e mercato screen lists (SPEC 13.6): every story read in the last 24 hours, plus older ones whose @@ -43,6 +50,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings var now = clock.UtcNow; var since = now - Window; var switches = await NewsRuleSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + var measured = await ExternalRules.MeasuredAsync(settings, cancellationToken).ConfigureAwait(false); // A restriction lasts at most 72 hours from an article, and articles join a story for 48: older ones are never in force. var oldest = since - NewsRules.Longest - NewsMatching.StoryWindow; var (all, links, notes, held) = await db.ReadAsync(async s => @@ -93,7 +101,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings })]; // Older stories stay while their effect is in force: from a note, or from the rules for an instrument nobody watches. var stories = all.Select(a => a.Fact).Where(st => st.FirstSeenAt >= since || notesOf["story:" + st.Id].Any(n => n.Until > now) || - (linksOf[st.Id].Any(l => l.Scope == LinkScopes.Instrument) && NewsRules.Active([st], now, switches).Count > 0)).ToList(); + (linksOf[st.Id].Any(l => l.Scope == LinkScopes.Instrument) && NewsRules.Active([st], now, measured ? NewsRuleSwitches.AllOn : switches).Count > 0)).ToList(); var rows = new List(); foreach (var story in stories) @@ -108,9 +116,13 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings _ => holding.Count > 0, }); - var (action, active) = Act(story, instruments, storyNotes.Select(n => (n.Kind, n.Action, n.Until)).ToList(), heldTargets, switches, now); - var verdict = verdicts[story.Id]; var coming = storyNotes.Any(n => n.Kind == NewsReasons.Earnings) || instruments.Any(reporting.Contains); + // Measured: the rule of the story first; the filter of the earnings speaks only for a story no rule of 10.5 meets. + var rule = measured ? ByRule(story, instruments, heldTargets, NewsRuleSwitches.AllOn, now, true) : default; + var (action, active) = !measured ? Act(story, instruments, storyNotes.Select(n => (n.Kind, n.Action, n.Until)).ToList(), heldTargets, switches, now) + : !rule.Active && instruments.FirstOrDefault(reporting.Contains) is { } report ? (NewsActions.WouldSkipEarnings(report[(report.IndexOf(':', StringComparison.Ordinal) + 1)..]), true) + : rule; + var verdict = verdicts[story.Id]; // An Italian title has no tone of the classifier: the direction of the model, when there is one, takes its place. var modelDirection = verdict.Importance is null ? null : verdict.Direction; var tone = (story.Score is null && modelDirection is not null ? ModelToneText(modelDirection) : ToneText(story.Score)) + @@ -124,7 +136,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings rows = [.. rows.OrderByDescending(r => r.Active).ThenByDescending(r => r.At).ThenBy(r => r.Id)]; var read = stories.Count(st => st.FirstSeenAt >= since); - return new NewsBoardResult(rows, read, rows.Count(r => r.OnPositions), rows.Count(r => r.Active)); + return new NewsBoardResult(rows, read, rows.Count(r => r.OnPositions), rows.Count(r => r.Active)) { Measured = measured }; } /// The five grades of SPEC 10.2 point 4 in words; an Italian title without the model has no tone. @@ -217,6 +229,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings return (unconfirmed, false); } + return ByRule(story, instruments, held, switches, now, false); + } + + // The rule of 10.5 the story meets, or why it meets none. Measured: what the rule would have done, never done (ADR 0027). + private static (string Action, bool Active) ByRule(StoryFact story, List instruments, HashSet held, NewsRuleSwitches switches, DateTimeOffset now, bool measured) + { if (instruments.Count == 0) { return story.Score is <= -0.2 @@ -239,6 +257,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings var target = instruments[0]; var symbol = target[(target.IndexOf(':', StringComparison.Ordinal) + 1)..]; + if (measured) + { + var would = NewsActions.WouldRestrict(matched, symbol, held.Contains(target)); + return matched.Until > now ? (would + " Solo registrato.", true) : (would + " Sarebbe già finita.", false); + } + var text = NewsActions.Restriction(matched, symbol, held.Contains(target)); return matched.Until > now ? (text, true) : (text + " Restrizione finita.", false); } diff --git a/src/Anubis/News/NewsDesk.cs b/src/Anubis/News/NewsDesk.cs index c819001..e64cbe7 100644 --- a/src/Anubis/News/NewsDesk.cs +++ b/src/Anubis/News/NewsDesk.cs @@ -156,12 +156,34 @@ public interface IEntryGate Task KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken); } +/// What each rule of 10.5 that stops a purchase would say of it, each on its own and with every row on (ADR 0027 point 7). +public sealed record RuleHolds(EntryHold? Severe, EntryHold? Negative, EntryHold? Macro) +{ + public static readonly RuleHolds None = new(null, null, null); +} + +/// +/// The gate asked rule by rule, for the measure in the shadow when the rules are only measured (ADR 0023 point 4). It +/// answers whatever the rows say: a row switched off is still measured. +/// +public interface IRuleShadowGate +{ + /// + /// The holds of the three rules on a purchase decided at and due at : the + /// news as they are at the decision, the figures around the time the order would go (ADR 0027 point 8). + /// + Task ByRuleAsync(InstrumentSpec spec, DateTimeOffset at, DateTimeOffset due, CancellationToken cancellationToken); + + /// The serious event that would keep the stop of a position where it is, or null. + Task WouldKeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken); +} + /// /// The rows of 10.5 that act on a single purchase: the news on the instrument (first two rows) and the high-impact /// figures (fifth row), the strictest of them. The earnings row acts inside equity_meanrev, which knows its /// sessions; the third row never stops anything. /// -public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings = null) : IEntryGate +public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings = null) : IEntryGate, IRuleShadowGate { private readonly NewsDesk _desk = new(db, clock, settings); private readonly CalendarEventStore _calendar = new(db, clock); @@ -197,6 +219,33 @@ public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings : null; } + public async Task ByRuleAsync(InstrumentSpec spec, DateTimeOffset at, DateTimeOffset due, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(spec); + var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.Longest, cancellationToken).ConfigureAwait(false); + var all = NewsRules.Active(stories, at, NewsRuleSwitches.AllOn); + EntryHold? Of(string code) => NewsRules.Strictest(all.Where(r => r.Code == code)) is { } r ? new EntryHold(r.Code, r.Until, Motive(r.Story)) : null; + + EntryHold? macro = null; + var events = await _calendar.BetweenAsync(due - TimeSpan.FromHours(3), due + TimeSpan.FromHours(3), cancellationToken).ConfigureAwait(false); + if (CalendarBlocks.BlockedUntil(due, events) is { } until) + { + var named = events.Where(e => CalendarBlocks.Window(e) is { } w && w.From <= due && w.To > due).OrderByDescending(e => CalendarBlocks.Window(e)!.Value.To).First(); + macro = new EntryHold(CorrectiveReasons.CalendarEvent, until, named.Title); + } + + return new RuleHolds(Of(NewsReasons.Severe), Of(NewsReasons.Negative), macro); + } + + public async Task WouldKeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(spec); + var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.Longest, cancellationToken).ConfigureAwait(false); + return NewsRules.KeepsStop(NewsRules.Active(stories, at, NewsRuleSwitches.AllOn)) is { } severe + ? new EntryHold(NewsReasons.KeepStop, severe.Until, Motive(severe.Story)) + : null; + } + /// The story as the diary names it: its title in quotes and who published it. public static string Motive(StoryFact story) { @@ -221,9 +270,17 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin /// Whether the earnings calendar is fresh, as the strategies ask (4.4): without it their row does nothing and the diary says nothing. public Func>? EarningsActive { get; init; } - /// One round over the instruments watched now: those held by any strategy and those of the latest universes. + /// + /// One round over the instruments watched now: those held by any strategy and those of the latest universes. With the + /// rules only measured it says nothing at all: no note, no diary line, no notice (ADR 0023 point 2). + /// public async Task RunOnceAsync(CancellationToken cancellationToken) { + if (await ExternalRules.MeasuredAsync(settings, cancellationToken).ConfigureAwait(false)) + { + return 0; + } + var now = clock.UtcNow; var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false); var watched = await WatchedAsync(db, cancellationToken).ConfigureAwait(false); @@ -332,6 +389,11 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin return 1; }, cancellationToken); + /// The stocks held or candidates of a strategy: the ones whose earnings the filter of the mean reversion reads. + public static async Task> WatchedStocksAsync(Database db, CancellationToken cancellationToken) => + (await WatchedAsync(db, cancellationToken).ConfigureAwait(false)).Where(w => w.Target.StartsWith(Venues.Alpaca + ":", StringComparison.Ordinal)) + .Select(w => w.Target[(Venues.Alpaca.Length + 1)..]).ToHashSet(StringComparer.Ordinal); + internal static async Task> WatchedAsync(Database db, CancellationToken cancellationToken) { var held = await db.ReadAsync(s => s.QueryAsync("SELECT i.venue, i.symbol, p.quantity FROM positions p JOIN instruments i ON i.id = p.instrument_id", @@ -363,6 +425,23 @@ public static class NewsActions return held ? $"Per 24 ore non aumento la posizione su {shown}." : $"Per 24 ore non compro {shown}."; } + /// The same rule as when the rules are only measured: what it would have done (ADR 0027). + public static string WouldRestrict(NewsRestriction r, string symbol, bool held) + { + ArgumentNullException.ThrowIfNull(r); + var shown = Trading.DiaryText.Coin(symbol); + if (r.Code == NewsReasons.Severe) + { + return held ? $"Avrebbe fermato per 72 ore i nuovi acquisti di {shown} e tenuto fermo lo stop." : $"Avrebbe fermato per 72 ore i nuovi acquisti di {shown}."; + } + + return held ? $"Avrebbe fermato per 24 ore gli aumenti della posizione su {shown}." : $"Avrebbe fermato per 24 ore gli acquisti di {shown}."; + } + + /// What the filter of the earnings would have done on a stock that reports soon, with the rules only measured (ADR 0027). + public static string WouldSkipEarnings(string symbol) => + $"Con le regole attive niente nuovi acquisti di mean reversion su {symbol} prima dei conti. Solo registrato."; + public static string Unconfirmed(DateTimeOffset recheck, TimeZoneInfo zone) => $"Niente, perché nessun'altra fonte la riportava. La ricontrollo alle {TimeZoneInfo.ConvertTime(recheck, zone):HH:mm}."; diff --git a/src/Anubis/Strategies/EquityStrategies.cs b/src/Anubis/Strategies/EquityStrategies.cs index 60691c5..a6526fd 100644 --- a/src/Anubis/Strategies/EquityStrategies.cs +++ b/src/Anubis/Strategies/EquityStrategies.cs @@ -344,6 +344,9 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr public string Version => EquityMeanrevFamily.FamilyVersion; + /// Sessions after the entry in which a report keeps the strategy out. + public int EarningsSessions => _settings.EarningsSessions; + public EquityMeanrevSettings Settings => _settings; public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; @@ -489,20 +492,23 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr /// Earnings in the entry session or the three after it, or out after today's close (live only: the backtest has no /// earnings calendar, SPEC 8.3). /// - private bool EarningsAhead(StrategyContext context, string symbol) - { - if (!context.EarningsEntries || context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry) - { - return false; - } + private bool EarningsAhead(StrategyContext context, string symbol) => + context.EarningsEntries && context.NextEarnings?.Invoke(symbol) is { } earnings && context.NextSession is { } entry + && EarningsAhead(context.Day, entry, earnings, _settings.EarningsSessions); + /// + /// The entry filter as a pure rule: a report from through the entry session and the + /// after it (weekends skipped, holidays not). The shadow of ADR 0027 point 14 reads the same rule. + /// + public static bool EarningsAhead(DateOnly day, DateOnly entry, DateOnly earnings, int sessions) + { var last = entry; - for (var i = 0; i < _settings.EarningsSessions; i++) + for (var i = 0; i < sessions; i++) { last = last.AddDays(last.DayOfWeek == DayOfWeek.Friday ? 3 : 1); } - return earnings >= context.Day && earnings <= last; + return earnings >= day && earnings <= last; } public static class Reasons diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 97f9ea0..38b16c3 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -156,6 +156,15 @@ public sealed partial class LiveEngine : IDisposable /// public Func>? Earnings { get; init; } + /// + /// Whether news, calendar and earnings were only measured at an instant (ADR 0023, 0027): then nothing is held back, no + /// date reaches the strategies, and the gate is asked rule by rule for the shadow only. Null: they act, as in Phase 7. + /// + public Func>? RulesMeasured { get; init; } + + private async Task MeasuredAsync(DateTimeOffset at, CancellationToken cancellationToken) => + RulesMeasured is not null && await RulesMeasured(at, cancellationToken).ConfigureAwait(false); + /// Learning (SPEC 11): notes the examples of each decision. Null in tests that do not look at it. public Anubis.Learning.LearningDesk? Learning { get; init; } @@ -563,11 +572,13 @@ public sealed partial class LiveEngine : IDisposable var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters); var data = loaded.Data; - var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false); + // Read once: one decision never mixes the two ways (ADR 0027 point 2). + var measured = await MeasuredAsync(m.Now, cancellationToken).ConfigureAwait(false); + var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, measured, cancellationToken).ConfigureAwait(false); var turn = Learning is null ? null : await Learning.PrepareAsync(m.Strategy, stage.Stage, m.Day, m.Due, data, () => CreateStrategy(m.Strategy, stage.Qualification?.Parameters), await EarningsOfAsync(m, cancellationToken) - .ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + .ConfigureAwait(false), measured, cancellationToken).ConfigureAwait(false); if (turn is not null) { options = options with { Correctives = turn.Around(options.Correctives) }; @@ -596,7 +607,7 @@ public sealed partial class LiveEngine : IDisposable plan = plan with { Working = await WorkingAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false) }; } - plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false); + plan = measured ? await MeasureRulesAsync(m, mode, plan, data, turn, cancellationToken).ConfigureAwait(false) : await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false); var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false); var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, turn, cancellationToken).ConfigureAwait(false); @@ -635,10 +646,13 @@ public sealed partial class LiveEngine : IDisposable } } - /// The earnings calendar as the decision of reads it (SPEC 10.5, fourth row; 8.3). - private async Task WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, CancellationToken cancellationToken) + /// + /// The earnings calendar as the decision of reads it (SPEC 10.5, fourth row; 8.3). With the rules + /// only measured no date reaches the strategy: it decides as every backtest always did (ADR 0027 point 9). + /// + private async Task WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, bool measured, CancellationToken cancellationToken) { - if (Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings) + if (measured || Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings) { return options; } @@ -775,6 +789,66 @@ public sealed partial class LiveEngine : IDisposable return plan with { Orders = orders, Stops = stops, Holds = holds, KeptStops = kept }; } + /// + /// The rules of 10.5 with the rules only measured (ADR 0027 points 7 and 8): the gate is asked rule by rule and with + /// every row on, what each rule would have done goes to the shadow, and the plan goes out as the strategy made it. + /// + private async Task MeasureRulesAsync(Moment m, string mode, PlanResult plan, BacktestDataset data, Anubis.Learning.LearningTurn? turn, CancellationToken cancellationToken) + { + if (Gate is not IRuleShadowGate gate || turn is null) + { + return plan; + } + + var answers = new List(); + try + { + foreach (var order in plan.Orders.Where(o => o.Side == OrderSide.Buy)) + { + if (data[order.Symbol]?.Spec is not { } spec) + { + continue; + } + + var holds = await gate.ByRuleAsync(spec, m.Now, order.Due, cancellationToken).ConfigureAwait(false); + foreach (var (rule, hold) in new[] { (Anubis.Learning.ShadowRules.NewsSevere, holds.Severe), (Anubis.Learning.ShadowRules.NewsNegative, holds.Negative), + (Anubis.Learning.ShadowRules.Macro, holds.Macro) }) + { + answers.Add(new Anubis.Learning.RuleAnswer(rule, order.Symbol, EffectOf(order, hold), hold)); + } + } + + foreach (var (symbol, from, to) in plan.Stops) + { + if (mode != DecisionModes.Observation && from > 0m && to < from && data[symbol]?.Spec is { } spec + && await gate.WouldKeepStopAsync(spec, m.Now, cancellationToken).ConfigureAwait(false) is { } keep) + { + answers.Add(new Anubis.Learning.RuleAnswer(Anubis.Learning.ShadowRules.SevereStop, symbol, Anubis.Learning.RuleEffect.StopKept, keep)); + } + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // The measure is apart: a failure of it never changes the decision. + LogShadowFailed(_logger, ex, m.Strategy); + return plan; + } + + turn.Rules(answers); + return plan; + } + + // What a hold would have done to one purchase: nothing, put it off within its deadline, or left it out (SPEC 5.6). + private Anubis.Learning.RuleEffect EffectOf(PlannedOrder order, EntryHold? hold) + { + if (hold is null || ReleaseAt(order.Crypto, hold.Until) is var release && release <= order.Due) + { + return Anubis.Learning.RuleEffect.None; + } + + return order.ValidUntil is { } until && release > until ? Anubis.Learning.RuleEffect.Dropped : Anubis.Learning.RuleEffect.Postponed; + } + /// /// The intents become orders as the backtest plans them (BacktestEngine.Plan): target quantity from the weight and /// the equity at the close, the difference bought or sold, a full exit when the weight is zero, stops moved on what @@ -893,7 +967,8 @@ public sealed partial class LiveEngine : IDisposable var currency = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(m.Strategy)); await _db.WriteAsync(async s => { - if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken).ConfigureAwait(false)) + // The run carries the instant the decision read the switch: the one-step check reads it as it was then. + if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken, now).ConfigureAwait(false)) { return; } @@ -1064,8 +1139,9 @@ public sealed partial class LiveEngine : IDisposable private async Task<(Guid, bool, IReadOnlyList)?> OneStepAsync(string strategyName, IStrategy strategy, BacktestDataset data, CancellationToken cancellationToken) { var previous = await _db.ReadAsync(s => s.FirstOrDefaultAsync( - "SELECT decision_day, decision_id, state, proposed FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1", - r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed")), ("s", strategyName)), + "SELECT decision_day, decision_id, state, proposed, created_at FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1", + r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed"), At: r.Moment("created_at")), + ("s", strategyName)), cancellationToken).ConfigureAwait(false); if (previous.State is null || previous.Proposed is null || data.Instruments.All(i => i.IndexOf(previous.Day) < 0)) { @@ -1080,7 +1156,9 @@ public sealed partial class LiveEngine : IDisposable } var state = snapshot.ToState(); - var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, cancellationToken).ConfigureAwait(false); + // The earnings as that decision read them: a change of the switch in between is no difference (ADR 0027 point 2). + var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, await MeasuredAsync(previous.At, cancellationToken).ConfigureAwait(false), + cancellationToken).ConfigureAwait(false); var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day, options).Proposed; var different = OneStep.Compare(state, recorded.Select(p => (p.Symbol, p.Weight)).ToList(), again.Select(i => (i.Symbol, i.TargetWeight)).ToList(), data, previous.Day); return (previous.Id, different.Count == 0, different); @@ -1089,7 +1167,11 @@ public sealed partial class LiveEngine : IDisposable // ---- Releasing planned orders ------------------------------------------------------------------------------- private sealed record Planned(Guid Id, Guid DecisionId, string Strategy, Guid AccountId, Guid InstrumentId, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, - decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, DateTimeOffset? FirstDue = null); + decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, DateTimeOffset? FirstDue = null) + { + /// When the decision behind it was taken: the switch of the outside rules is read as it was then (ADR 0027 point 2). + public DateTimeOffset DecidedAt { get; init; } = Due; + } /// /// The planned orders whose time has come go to the order manager, sales first (SPEC 5.5). An entry past its @@ -1151,7 +1233,9 @@ public sealed partial class LiveEngine : IDisposable return; } - if (order.Side == OrderSide.Buy && Gate is not null && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold) + // The gate at send time belongs to a decision taken with the rules acting: the switch is read as that decision read it. + if (order.Side == OrderSide.Buy && Gate is not null && !await MeasuredAsync(order.DecidedAt, cancellationToken).ConfigureAwait(false) + && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold) { await HoldAsync(order, instrument.Symbol, hold with { Until = ReleaseAt(instrument.IsCrypto, hold.Until) }, now, cancellationToken).ConfigureAwait(false); return; @@ -1267,13 +1351,16 @@ public sealed partial class LiveEngine : IDisposable private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked); + // decided_at is the first row of its decision: an order planned again after a restart keeps the instant of the decision. private const string PlannedColumns = - "p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until, p.first_due_at"; + "p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until, p.first_due_at, " + + "(SELECT MIN(x.created_at) FROM planned_orders x WHERE x.decision_id = p.decision_id) AS decided_at"; private static Planned ReadPlanned(DbRow r) => new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"), - r.MomentOrNull("valid_until"), r.MomentOrNull("first_due_at")); + r.MomentOrNull("valid_until"), r.MomentOrNull("first_due_at")) + { DecidedAt = r.Moment("decided_at") }; /// /// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between @@ -1545,12 +1632,12 @@ public sealed partial class LiveEngine : IDisposable _db.WriteAsync(s => ClaimAsync(s, strategy, key, day, Guid.Empty, "none", null, null, cancellationToken), cancellationToken); private async Task ClaimAsync(DbSession s, string strategy, string key, DateOnly day, Guid decisionId, string mode, string? state, string? proposed, - CancellationToken cancellationToken) => + CancellationToken cancellationToken, DateTimeOffset? at = null) => await s.ExecuteAsync( "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, @st, @p, @now) " + "ON CONFLICT (run_key) DO NOTHING", cancellationToken, ("id", Ids.NewId(_clock)), ("s", strategy), ("k", key), ("d", BarStore.DayText(day)), ("dec", decisionId), ("m", mode), - ("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0; + ("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", at ?? _clock.UtcNow)).ConfigureAwait(false) > 0; public void Dispose() => _gate.Dispose(); @@ -1562,6 +1649,9 @@ public sealed partial class LiveEngine : IDisposable [LoggerMessage(Level = LogLevel.Error, Message = "Planned order {Id} could not be released")] private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id); + + [LoggerMessage(Level = LogLevel.Error, Message = "The shadow of the news rules of {Strategy} was left out")] + private static partial void LogShadowFailed(ILogger logger, Exception exception, string strategy); } /// The comparison of two sets of intents (SPEC 12.3): same action and size within 10%, for what is held and what either version enters. diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 4bda061..ebe48ba 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -200,6 +200,7 @@ public sealed partial class TradingService : IDisposable { WantData = market is null ? null : _ => market.WakeWorker(), Gate = new News.EntryGate(db, clock, settings), + RulesMeasured = (at, ct) => News.ExternalRules.MeasuredAtAsync(settings, at, ct), Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct), Ready = () => _started, AccountReady = AccountReady, diff --git a/tests/Anubis.Tests/DatabaseTests.cs b/tests/Anubis.Tests/DatabaseTests.cs index 239b547..39675d0 100644 --- a/tests/Anubis.Tests/DatabaseTests.cs +++ b/tests/Anubis.Tests/DatabaseTests.cs @@ -17,9 +17,26 @@ public sealed class DatabaseTests { var test = await TestDb.CreateAsync().ConfigureAwait(false); await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false); + + // The rules of the news act in the tests of Phase 7 (ADR 0027 point 3): set here, without a change in the log. A + // test of «misurate» asks for it. + await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)", CancellationToken.None, + ("id", Ids.NewId(_clock)), ("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Active))), ("t", _clock.UtcNow))) + .ConfigureAwait(false); return test; } + /// + /// Puts the rules of the news back to the default of ADR 0023, «misurate», in a database of ; + /// is when the switch was written, as on a new installation. + /// + internal static Task MeasuredAsync(Database db, DateTimeOffset? since = null) => + db.WriteAsync(s => since is { } at + ? s.ExecuteAsync("UPDATE config SET value = @v, created_at = @t, updated_at = @t WHERE key = @k", CancellationToken.None, + ("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Measured))), ("t", at)) + : s.ExecuteAsync("UPDATE config SET value = @v WHERE key = @k", CancellationToken.None, + ("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Measured))))); + [TestMethod] [TestCategory(Category.Integration)] public async Task MigrationsCreateTheSchemaAndRunOnce() diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs index e7fbfdd..f6fb5c1 100644 --- a/tests/Anubis.Tests/LaboratoryScreenTests.cs +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -121,7 +121,7 @@ public sealed class LaboratoryScreenTests { "1º trimestre 2027", "Non superata", "Non superata, resta in simulazione e non può passare ai soldi veri", $"href=\"/laboratorio/{trial}\"", "calo massimo 38,2%, oltre il 25%", "Variante in uso: coin_vol 15", "Non cambia da sola", "Risultato +3,1%; il backtest negli stessi giorni circa +2,5%.", "Scostamento dei prezzi 6,2 punti base, atteso 7 punti base.", "decisioni identiche al backtest del giorno dopo 90,0%", - "In attesa dei dati", "Non riprovata", "Non riprovata: il protocollo per le azioni arriva con una versione successiva", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}", + "In attesa dei dati", "Non riprovata", "Non riprovata: il protocollo per le azioni arriva con una versione successiva", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "Le trimestrali sono misurate nella tabella delle regole in ombra", $"/laboratorio/revisione/{first}", }) { StringAssert.Contains(page, part, $"Missing \"{part}\"."); diff --git a/tests/Anubis.Tests/LearningScreenTests.cs b/tests/Anubis.Tests/LearningScreenTests.cs index d255859..aeed698 100644 --- a/tests/Anubis.Tests/LearningScreenTests.cs +++ b/tests/Anubis.Tests/LearningScreenTests.cs @@ -44,7 +44,7 @@ public sealed class LearningScreenTests "Non potrà mai ingrandirle, né aprirne di sue.", "212 su 300 necessari", "Al ritmo attuale, tra tre e quattro settimane.", "56%", "Tirando a caso sarebbe il 50%", "Domenica 4 ottobre, versione 3", "Prossima verifica dello sfidante", "Domenica 11 ottobre, 03:00", "54% su 61 casi", "71% su 14 casi", "Stima perfetta", "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato.", "troppo pochi casi per contarci", - "Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "insieme a paura e avidità pesano 17 su 100.", + "Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "Notizie, trimestrali, paura e avidità non entrano nel modello: le decisioni guardano solo i numeri del mercato.", "In carica, versione 2", "Sfidante, versione 3", "16 agosto", "2.152", "2.332", "0,241", "0,239", "(senza filtro: +5,84", "+7,90", "+8,10", "non serve", "14 su 100", "La versione 3 è ancora in prova.", "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100", "Fino ad allora gira in ombra accanto alla 2.", "Nessuna anomalia", "Il mercato di oggi somiglia a quello su cui ha studiato", "Precisione sugli ultimi 60 casi: 55%, in linea con il 56% atteso", diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs index e42be0c..9d4d3fc 100644 --- a/tests/Anubis.Tests/LiveStockSupport.cs +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -118,6 +118,24 @@ internal sealed class StockRig : IAsyncDisposable Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Learning = learning }; } + /// + /// The engine again with news, calendar and earnings only measured (ADR 0023): the earnings calendar, the learning and the + /// gate it asks for the shadow. + /// + /// says whether they were measured at an instant (the change log); without it, always. + public void UseMeasured(Func> earnings, Learning.LearningDesk learning, News.IEntryGate? gate = null, + Func? measuredAt = null) + { + Engine.Dispose(); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) + { + Earnings = earnings, + Learning = learning, + Gate = gate, + RulesMeasured = (at, _) => Task.FromResult(measuredAt?.Invoke(at) ?? true), + }; + } + /// The engine again, with the rules of SPEC 10.5 on single purchases. public void UseGate(News.IEntryGate gate) { diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index 6bac5df..414e905 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -111,9 +111,21 @@ internal sealed class LiveRig : IAsyncDisposable AccountReady = _ => AccountStarted, Gate = Gate, Learning = Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock) { First = First }, + RulesMeasured = Measured ? (_, _) => Task.FromResult(true) : null, }; } + /// News, calendar and earnings only measured (ADR 0023): the default of a real installation, asked by the tests of Phase 11. + public bool Measured { get; private set; } + + /// The engine again, with the rules of 10.5 only measured. + public void UseMeasured() + { + Measured = true; + Engine.Dispose(); + Build(); + } + public Anubis.Learning.LearningDesk Learning { get; private set; } = null!; /// The first model and the base rates the engine starts from. diff --git a/tests/Anubis.Tests/MeasuredRulesTests.cs b/tests/Anubis.Tests/MeasuredRulesTests.cs new file mode 100644 index 0000000..fea53d0 --- /dev/null +++ b/tests/Anubis.Tests/MeasuredRulesTests.cs @@ -0,0 +1,472 @@ +using System.Net.Http.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Learning; +using Anubis.News; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// Phase 11 (ADR 0023, 0027): news, calendar and earnings only measured. By default nothing they say changes a decision, +/// and each rule writes in the shadow what it would have done. +/// +[TestClass] +public sealed class MeasuredRulesTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + // ---- The switch --------------------------------------------------------------------------------------------- + + /// + /// A new installation starts with the rules only measured; a part built without settings (only tests do that) lets them + /// act. A change writes its line once, in the same transaction, and the value of an earlier moment is read back. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSwitchStartsMeasuredAndRemembersWhatItWas() + { + await using var test = await TestDb.CreateAsync(); + var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero)); + await Migrations.MigrateAsync(test.Db, clock, null, _none); + var settings = new SettingsStore(test.Db, clock, new EventBus()); + Assert.AreEqual(ExternalRules.Measured, (await settings.GetAsync(ExternalRules.Setting.Key)).Value); + Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none)); + Assert.IsFalse(await ExternalRules.MeasuredAsync(null, _none), "without settings the rules act, as the five rows are on"); + + var before = clock.UtcNow; + clock.Advance(TimeSpan.FromHours(1)); + async Task SetAsync(string value) => await settings.SetAsync(ExternalRules.Setting.Key, value, "admin", + (s, old) => ExternalRules.WriteChangeAsync(s, clock, old, value, "admin", _none), _none); + Assert.IsTrue(await SetAsync(ExternalRules.Active)); + Assert.IsFalse(await SetAsync(ExternalRules.Active), "nothing changed: no line"); + var lines = await NewsRulesTests.DiaryAsync(test.Db); + Assert.HasCount(1, lines); + StringAssert.StartsWith(lines[0], "Notizie, calendario e trimestrali da «solo misurate» a «attive»"); + Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none), "no Telegram"); + + Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none)); + Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, before, _none), "an hour ago they were only measured"); + Assert.IsFalse(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none)); + } + + /// The tests of Phase 7 run with the rules acting: the support of the tests sets «attive», without a change in the log. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSupportOfTheTestsSetsTheRulesActing() + { + await using var test = await DatabaseTests.MigratedAsync(); + var settings = new SettingsStore(test.Db, new ManualClock(DateTimeOffset.UnixEpoch), new EventBus()); + Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none)); + Assert.IsEmpty(await settings.HistoryAsync(ExternalRules.Setting.Key)); + await DatabaseTests.MeasuredAsync(test.Db); + Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none)); + } + + // ---- The decisions ------------------------------------------------------------------------------------------ + + /// + /// The scene of NewsRulesTests: a confirmed serious event on ETH and a negative story on SOL before the crypto close. With + /// the rules measured both purchases go, nothing is held, nothing is said, and each rule leaves one case in the shadow. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AConfirmedSevereStoryChangesNothingAndIsMeasuredInTheShadow() + { + var day = new DateOnly(2026, 9, 1); + await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)); + live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock)); + live.UseMeasured(); + await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9, + "CoinDesk", trusted: true); + await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero), + 3, -0.8, "CoinDesk", trusted: true); + + await live.DayAsync(day); + + var fills = await live.LiveFillsAsync(); + Assert.IsTrue(fills.Any(f => f is { Symbol: "ETH-EUR", Side: OrderSide.Buy }), string.Join(", ", fills)); + Assert.IsTrue(fills.Any(f => f is { Symbol: "SOL-EUR", Side: OrderSide.Buy }), string.Join(", ", fills)); + var held = (await live.Rig.QueryAsync("SELECT symbol, reasons FROM decisions WHERE outcome IN (@r, @p)", r => (Symbol: r.TextOrNull("symbol"), Reasons: r.Text("reasons")), + ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed))).Where(d => d.Reasons.Contains("news_", StringComparison.Ordinal) || d.Reasons.Contains("calendar", StringComparison.Ordinal)); + Assert.IsFalse(held.Any(), "no row of a block"); + var diary = await NewsRulesTests.DiaryAsync(live.Rig.Db); + Assert.IsFalse(diary.Any(l => l.Contains("Non compro", StringComparison.Ordinal) || l.Contains("Motivo: «", StringComparison.Ordinal)), string.Join(" | ", diary)); + Assert.AreEqual(0L, await live.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind LIKE 'news%'"), _none), "no notice of the news"); + + var cases = await live.Rig.QueryAsync("SELECT improvement, symbol, decided_day, factor FROM shadow_cases WHERE improvement LIKE 'rule_%'", + r => (Rule: r.Text("improvement"), Symbol: r.Text("symbol"), Day: r.Text("decided_day"), Factor: r.Measure("factor"))); + Assert.IsFalse(cases.GroupBy(c => (c.Rule, c.Symbol, c.Day)).Any(g => g.Count() > 1), "one case per rule, strategy, instrument and day"); + // The crypto close of 31 August is decided just after midnight UTC: the case carries the day of the bar. + double Factor(string rule, string symbol) => + cases.SingleOrDefault(c => c.Rule == rule && c.Symbol == symbol && c.Day == "2026-08-31") is { Rule: not null } found ? found.Factor + : throw new AssertFailedException($"No case {rule} on {symbol}: " + string.Join(", ", cases)); + Assert.AreEqual(0, Factor(ShadowRules.NewsSevere, "ETH-EUR"), "the serious event would have left ETH out"); + Assert.AreEqual(1, Factor(ShadowRules.NewsSevere, "SOL-EUR")); + Assert.AreEqual(0, Factor(ShadowRules.NewsNegative, "SOL-EUR"), "the negative story would have left SOL out"); + Assert.AreEqual(1, Factor(ShadowRules.Macro, "ETH-EUR"), "no figure that morning"); + } + + /// The same scene with the rules acting writes no case in the shadow: the balance of the restrictions measures them. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task WithTheRulesActingNothingGoesToTheShadow() + { + var day = new DateOnly(2026, 9, 1); + await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)); + live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock)); + await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9, + "CoinDesk", trusted: true); + + await live.DayAsync(day); + + Assert.IsEmpty(await live.Rig.QueryAsync("SELECT id FROM shadow_cases WHERE improvement LIKE 'rule_%'", r => r.Id("id"))); + } + + /// + /// The scene of the earnings: the close of 1 September plans BBB, which reports on 3 September before the open. With the + /// rules measured the purchase goes, the strategy never leaves for the report, and both rules of the earnings are noted + /// at the entry. Once the operation has its label, the exit is measured against the label made with the report. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task MeanReversionEntersBeforeEarningsAndNeverLeavesForThem() + { + var day = new DateOnly(2026, 9, 1); + await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)); + await new CalendarEventStore(stocks.Rig.Db, stocks.Rig.Clock).UpsertAsync( + [new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale BBB", new DateTimeOffset(2026, 9, 3, 11, 0, 0, TimeSpan.Zero), false, "test", "earnings:BBB") + { Symbol = "BBB", TimeHint = "bmo" }], _none); + var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock); + var learning = new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null }; + stocks.UseMeasured(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct), true), learning); + + await stocks.SessionAsync(day); + var planned = await stocks.Rig.QueryAsync("SELECT i.symbol FROM planned_orders p JOIN instruments i ON i.id = p.instrument_id WHERE p.side = 'buy'", r => r.Text("symbol")); + CollectionAssert.Contains(planned.ToList(), "BBB", "the report tomorrow keeps nothing out"); + var example = (await learning.Store.LiveAsync(StrategyNames.EquityMeanrev, _none)).Single(e => e.Symbol == "BBB"); + Assert.IsFalse(example.Features.ContainsKey(Clues.EarningsDays), "no earnings clue: the label never leaves before a report"); + + for (var d = day.AddDays(1); d <= day.AddDays(20); d = d.AddDays(1)) + { + await stocks.SessionAsync(d); + } + + Assert.IsFalse((await stocks.Rig.QueryAsync("SELECT reasons FROM decisions", r => r.Text("reasons"))).Any(r => r.Contains(EquityMeanrev.Reasons.ExitEarnings, StringComparison.Ordinal)), + "never the exit for the report"); + var cases = await stocks.Rig.QueryAsync("SELECT improvement, factor, data FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement LIKE 'rule_earnings%'", + r => (Rule: r.Text("improvement"), Factor: r.Measure("factor"), Data: r.Json("data").Text)); + Assert.AreEqual(0, cases.Single(c => c.Rule == ShadowRules.EarningsEntry).Factor, "the filter would have kept BBB out"); + var exit = cases.Single(c => c.Rule == ShadowRules.EarningsExit); + StringAssert.Contains(exit.Data, "\"Report\":\"2026-09-03\""); + + await new LearningCycle(stocks.Rig.Db, stocks.Rig.Clock, learning, stocks.Engine.LabelDataAsync).LabelAsync(_none); + await learning.Shadow.MeasureAsync(stocks.Engine.LabelDataAsync, null, null, _none); + var measured = await stocks.Rig.QueryAsync("SELECT factor, effect, measured_at FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement = @i", + r => (Factor: r.Measure("factor"), Effect: r.IsNull("effect") ? (double?)null : r.Measure("effect"), Done: !r.IsNull("measured_at")), ("i", ShadowRules.EarningsExit)); + Assert.IsTrue(measured.Single().Done); + Assert.AreEqual(0, measured.Single().Factor, "with the report the label leaves on the close before it"); + Assert.IsNotNull(measured.Single().Effect); + } + + /// + /// A purchase decided with the rules measured goes at the open as it was decided, even when they act again in the + /// evening: the gate at send time belongs to the decisions taken with «attive» (ADR 0027 point 2). + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task APurchaseDecidedWithTheRulesMeasuredGoesEvenIfTheyActBeforeItLeaves() + { + var day = new DateOnly(2026, 9, 1); + await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)); + var switched = new DateTimeOffset(2026, 9, 1, 23, 0, 0, TimeSpan.Zero); + stocks.UseMeasured((_, _) => Task.FromResult(null), new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null }, + new HoldingGate(new EntryHold(NewsReasons.Severe, new DateTimeOffset(2026, 9, 9, 0, 0, 0, TimeSpan.Zero), "fatto")), at => at < switched); + + await stocks.SessionAsync(day); + await stocks.SessionAsync(day.AddDays(1)); + + var fills = await stocks.LiveFillsAsync(); + Assert.IsTrue(fills.Any(f => f is { Symbol: "BBB", Side: OrderSide.Buy }), string.Join(", ", fills)); + Assert.IsEmpty(await stocks.Rig.QueryAsync("SELECT id FROM decisions WHERE stage = @o AND outcome IN (@r, @p)", r => r.Id("id"), + ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed)), "nothing held at the open"); + } + + // A rule that would hold every purchase, asked only with the rules acting. + private sealed class HoldingGate(EntryHold hold) : IEntryGate + { + public Task HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(at < hold.Until ? hold : null); + + public Task KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(null); + } + + /// + /// The first start of this version writes the switch: on a new installation only the row; on one that already decided, + /// «attive» until now in the change log and one line in the diary, never twice. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheFirstStartWritesTheSwitchAndRemembersTheRulesActedBefore() + { + foreach (var decided in new[] { false, true }) + { + await using var test = await TestDb.CreateAsync(); + var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero)); + await Migrations.MigrateAsync(test.Db, clock, null, _none); + var before = clock.UtcNow.AddDays(-1); + if (decided) + { + await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) " + + "VALUES (@id, 'crypto_trend', 'k', '2026-12-02', @d, 'observation', NULL, NULL, @t)", _none, ("id", Ids.NewId(clock)), ("d", Guid.NewGuid()), ("t", before)), _none); + } + + Assert.AreEqual(decided, await ExternalRules.SettleAsync(test.Db, clock, _none)); + clock.Advance(TimeSpan.FromHours(1)); + Assert.IsFalse(await ExternalRules.SettleAsync(test.Db, clock, _none), "once"); + var settings = new SettingsStore(test.Db, clock, new EventBus()); + Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none)); + Assert.AreEqual(!decided, await ExternalRules.MeasuredAtAsync(settings, before, _none), "before the upgrade the rules acted"); + Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none)); + var history = await settings.HistoryAsync(ExternalRules.Setting.Key); + Assert.HasCount(decided ? 1 : 0, history); + var lines = await NewsRulesTests.DiaryAsync(test.Db); + Assert.HasCount(decided ? 1 : 0, lines); + if (decided) + { + Assert.AreEqual(ExternalRules.Upgrade, history[0].ChangedBy); + StringAssert.StartsWith(lines[0], "Con questa versione notizie, calendario e trimestrali sono solo misurate"); + } + } + } + + /// With the rules measured the watcher of the news writes nothing: no note, no line, no notice. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheWatcherIsSilentWhileTheRulesAreMeasured() + { + await using var test = await DatabaseTests.MigratedAsync(); + var (clock, settings, specs) = await NewsAnalystTests.SetUpAsync(test.Db); + await DatabaseTests.MeasuredAsync(test.Db); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana upgrade delayed by a week", clock.UtcNow.AddHours(-1), 3, -0.7, "CoinDesk", trusted: true); + + Assert.AreEqual(0, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none)); + Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_notes"), _none), "no note"); + Assert.IsEmpty(await NewsRulesTests.DiaryAsync(test.Db)); + Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none)); + + // The same story with the rules acting: the line of Phase 7. + await settings.SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin"); + Assert.AreEqual(1, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none)); + Assert.HasCount(1, await NewsRulesTests.DiaryAsync(test.Db)); + } + + // ---- The model ---------------------------------------------------------------------------------------------- + + /// The seven outside clues stay out of a training with the rules measured, however many live examples carry them; VIX goes in. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheOutsideCluesStayOutOfTraining() + { + CollectionAssert.AreEquivalent( + new[] { Clues.Tone1, Clues.Tone3, Clues.Count1, Clues.Count3, Clues.WorstEvent, Clues.FearGreed, Clues.EarningsDays }, Clues.External.ToList()); + Assert.IsFalse(Clues.IsExternal(Clues.Vix) || Clues.IsExternal(Clues.Funding) || Clues.IsExternal(Clues.OpenInterest), "market numbers stay"); + Assert.IsFalse(Clues.HasExternal(FirstModel.Embedded!.Model!.Clues), "the first model uses none of them"); + + var history = LearningModelTests.Cases(300, _ => 0.5); + IReadOnlyList examples = + [ + .. history, .. LearningModelTests.Cases(400, _ => 0.5, 8, source: CaseSources.Live).Select((c, i) => c with + { + Features = new Dictionary(c.Features) { [Clues.FearGreed] = i, [Clues.Tone3] = i % 5, [Clues.EarningsDays] = i % 31, [Clues.Vix] = 10 + (i % 20) }, + }), + ]; + var with = Trainer.CluesOf(examples); + var without = Trainer.CluesOf(examples, external: false); + Assert.Contains(Clues.FearGreed, with); + Assert.Contains(Clues.Vix, without); + Assert.IsFalse(without.Any(Clues.IsExternal), string.Join(", ", without)); + } + + /// + /// A model in charge that uses fear and greed counts with the rules acting; with them measured it is set aside at the very + /// next decision, for that reason, and goes on estimating. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AModelWithAnOutsideClueIsSetAsideAtOnce() + { + await using var test = await DatabaseTests.MigratedAsync(); + var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero)); + var model = LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.FearGreed] }; + await LearningCycleTests.AddModelAsync(test.Db, clock, model, ModelStatuses.Champion); + await test.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { ActivatedAt = clock.UtcNow }, _none), _none); + var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus())); + + var acting = await desk.GateAsync(_none); + Assert.IsTrue(acting.Counts); + Assert.IsFalse(acting.OutsideClues); + + await DatabaseTests.MeasuredAsync(test.Db); + var measured = await desk.GateAsync(_none); + Assert.IsFalse(measured.Counts); + Assert.IsTrue(measured.Aside); + Assert.IsTrue(measured.OutsideClues); + Assert.IsNotNull(measured.Champion, "it keeps estimating"); + } + + /// + /// The first night with the rules measured writes the day of the change in the history of the models, once; a model in + /// charge with an outside clue is set aside with its own words and nothing goes to the phone. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheFirstNightWritesTheDayOfTheChangeOnce() + { + await using var test = await DatabaseTests.MigratedAsync(); + var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 2, 0, 0, TimeSpan.Zero)); + // The switch written with the first start of this version, the evening before: the event says that day, not the night of the check. + await DatabaseTests.MeasuredAsync(test.Db, new DateTimeOffset(2026, 12, 2, 18, 0, 0, TimeSpan.Zero)); + await LearningCycleTests.AddModelAsync(test.Db, clock, LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.Tone3] }, ModelStatuses.Champion); + var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus())) { First = null }; + var cycle = new LearningCycle(test.Db, clock, desk, (_, _, _) => Task.FromResult(null)); + + await cycle.CheckAsync(_none); + clock.Advance(TimeSpan.FromDays(1)); + await cycle.CheckAsync(_none); + + var events = await desk.Models.EventsAsync(_none); + Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesMeasured).ToList()); + StringAssert.StartsWith(events.Single(e => e.Kind == ModelEvents.RulesMeasured).Text, "Dal mercoledì 2 dicembre notizie, calendario e trimestrali non cambiano le decisioni"); + Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesAside).ToList()); + Assert.IsFalse(events.Any(e => e.Kind == ModelEvents.SetAside), "not an alarm"); + Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none)); + Assert.IsNull((await desk.CycleAsync(_none)).ActivatedAt, "a model that cannot count does not start counting"); + StringAssert.Contains(events.Single(e => e.Kind == ModelEvents.RulesAside).Text, "La domenica ne addestro una senza, che entra in prova come sfidante."); + + // The rules act again: the model is back for that reason, and the words say why. + await new SettingsStore(test.Db, clock, new EventBus()).SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin"); + clock.Advance(TimeSpan.FromDays(1)); + await cycle.CheckAsync(_none); + StringAssert.StartsWith((await desk.Models.EventsAsync(_none)).Single(e => e.Kind == ModelEvents.RulesBack).Text, + "Notizie, calendario e trimestrali sono di nuovo attive: la versione"); + } + + // ---- The shadow --------------------------------------------------------------------------------------------- + + /// + /// Under six months from the first case a rule says «troppo presto»; then the criterion of ADR 0023 at 99%: 30 entries + /// changed and the whole interval above zero. Postponed entries are counted, not valued. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheRulesSayTooEarlyUnderSixMonthsAndAreJudgedAt99() + { + await using var test = await DatabaseTests.MigratedAsync(); + var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero)); + var desk = new LearningDesk(test.Db, clock); + async Task CaseAsync(string rule, string symbol, DateOnly day, double factor, double? effect, string? kind = null) => + await test.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO shadow_cases (id, improvement, strategy, symbol, decided_day, decision_id, factor, data, effect, measured_at, created_at, updated_at) " + + "VALUES (@id, @i, @s, @sy, @d, @dec, @f, @data, @e, @now, @now, @now)", _none, ("id", Ids.NewId(clock)), ("i", rule), ("s", StrategyNames.CryptoTrend), ("sy", symbol), + ("d", BarStore.DayText(day)), ("dec", Guid.NewGuid()), ("f", factor), ("data", new DbJson(kind is null ? "{}" : "{\"Kind\":\"" + kind + "\"}")), ("e", effect), ("now", clock.UtcNow)), _none); + + // Eight months of a rule that avoids a loss of about 2% each time, five times a month; one entry only postponed. + var first = new DateOnly(2026, 4, 1); + for (var m = 0; m < 8; m++) + { + for (var i = 0; i < 5; i++) + { + await CaseAsync(ShadowRules.NewsNegative, "C" + i, first.AddMonths(m).AddDays(i), 0, 0.02 + (0.001 * ((m + i) % 3))); + } + } + + await CaseAsync(ShadowRules.NewsNegative, "P", first.AddDays(20), 1, 0, ShadowKinds.Postponed); + await CaseAsync(ShadowRules.NewsNegative, "I", first.AddDays(21), 0, null, ShadowKinds.Increase); + await CaseAsync(ShadowRules.NewsSevere, "Q", new DateOnly(2026, 11, 2), 0, -0.01); + + var rules = await desk.Shadow.LoadRulesAsync(alpacaKeys: false, finnhubKey: false, _none); + var negative = rules.Single(r => r.Rule.Key == ShadowRules.NewsNegative); + Assert.AreEqual(42, negative.Examined); + Assert.AreEqual(40, negative.Changed); + Assert.AreEqual(1, negative.Postponed); + Assert.AreEqual(1, negative.Increases, "an increase held back is counted, not valued"); + Assert.AreEqual(0.99, negative.Line.Level); + Assert.IsGreaterThan(0, negative.Line.Interval!.Value.Low); + Assert.AreEqual("Criterio raggiunto", negative.State); + Assert.IsTrue(negative.Met); + + var severe = rules.Single(r => r.Rule.Key == ShadowRules.NewsSevere); + Assert.AreEqual("Troppo presto", severe.State); + Assert.AreEqual(new DateOnly(2027, 5, 2), severe.JudgedFrom); + Assert.AreEqual("In attesa delle chiavi Alpaca", rules.Single(r => r.Rule.Key == ShadowRules.EarningsEntry).State); + Assert.AreEqual("Nessun caso finora", rules.Single(r => r.Rule.Key == ShadowRules.Macro).State); + + // At 95% the same months would give a narrower interval: the rules ask for more. + var at95 = negative.Line with { Level = 0.95 }; + Assert.IsLessThan(negative.Line.Interval!.Value.High - negative.Line.Interval.Value.Low, at95.Interval!.Value.High - at95.Interval.Value.Low); + } + + /// The entry filter of the strategy as a pure rule: three sessions after the entry, the weekend skipped. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEarningsRuleSkipsTheWeekend() + { + var thursday = new DateOnly(2026, 9, 3); + var friday = thursday.AddDays(1); + Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 9), 3), "Friday, Monday, Tuesday, Wednesday"); + Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 10), 3)); + Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, thursday.AddDays(-1), 3), "a report already out"); + Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, thursday, 3), "out after today's close"); + } + + // ---- The page ----------------------------------------------------------------------------------------------- + + /// + /// The switch changes only from the settings form: the programs' interface refuses it; with real money, only measuring + /// asks for the phrase and the password; acting again is free; each change writes one line in the diary. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSwitchChangesOnlyFromTheSettingsWithTheProtectionsOfTheRows() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true); + var password = await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + async Task Switch(string value, params (string, string)[] more) + { + using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + ExternalRules.Setting.Key, [("ritorno", "/impostazioni#notizie"), ("valore", value), .. more]); + return ServerHarness.Location(answer); + } + + var page = await server.TextAsync("/impostazioni"); + StringAssert.Contains(page, "Notizie, calendario e trimestrali"); + StringAssert.Contains(page, "Le righe qui sotto valgono quando le regole sono attive."); + StringAssert.Contains(await server.TextAsync("/notizie"), "Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola."); + + Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Active), "acting is always free"); + Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value); + Assert.DoesNotContain("Archivio: le notizie", await server.TextAsync("/notizie")); + + await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'")); + StringAssert.Contains(await server.TextAsync("/impostazioni"), "per misurare soltanto le regole servono la frase e la password"); + StringAssert.Contains(await Switch(ExternalRules.Measured), "errore=frase-rischio"); + StringAssert.Contains(await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio"); + Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value); + Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", password))); + Assert.AreEqual(ExternalRules.Measured, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value); + + var lines = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = @c ORDER BY occurred_at, id", r => r.Text("message"), ("c", ExternalRules.Changed))); + Assert.HasCount(2, lines); + StringAssert.Contains(lines[1], "da «attive» a «solo misurate»"); + + var csrf = await server.Http.GetFromJsonAsync>(new Uri("/api/antiforgery", UriKind.Relative)); + using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + ExternalRules.Setting.Key, UriKind.Relative)) + { Content = JsonContent.Create(new { value = ExternalRules.Active }) }; + request.Headers.Add(csrf!["header"], csrf["token"]); + using var put = await server.Http.SendAsync(request); + Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, put.StatusCode); + StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni"); + } +} diff --git a/tests/Anubis.Tests/NewsAnalystTests.cs b/tests/Anubis.Tests/NewsAnalystTests.cs index 9bcdc47..7365f85 100644 --- a/tests/Anubis.Tests/NewsAnalystTests.cs +++ b/tests/Anubis.Tests/NewsAnalystTests.cs @@ -527,7 +527,7 @@ public sealed partial class NewsAnalystTests } // SOL held on OKX, ETH and ADA in the catalog and not watched. - private static async Task<(ManualClock Clock, SettingsStore Settings, Dictionary Specs)> SetUpAsync(Database db) + internal static async Task<(ManualClock Clock, SettingsStore Settings, Dictionary Specs)> SetUpAsync(Database db) { var clock = new ManualClock(Now); var specs = new[] { "SOL-EUR", "ETH-EUR", "ADA-EUR" }.ToDictionary(s => s[..3], s => MarketDataStoreTests.Okx(s)); diff --git a/tests/Anubis.Tests/NewsScreenTests.cs b/tests/Anubis.Tests/NewsScreenTests.cs index 6f9f1f2..afb1d6e 100644 --- a/tests/Anubis.Tests/NewsScreenTests.cs +++ b/tests/Anubis.Tests/NewsScreenTests.cs @@ -104,16 +104,16 @@ public sealed class NewsScreenTests var page = await server.TextAsync("/notizie"); foreach (var text in new[] { - "312 notizie lette nelle ultime 24 ore, 2 con un effetto in corso.", "Con effetto, 2", "Sulle tue posizioni, 9", "Tutte, 312", - "Oggi 06:10, da CoinDesk", "Cosa ho fatto: per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.", - "Neutra, evento in arrivo", "niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.", + "312 notizie lette nelle ultime 24 ore, 2 su cui una regola avrebbe agito.", "Con una regola, 2", "Archivio: le notizie non cambiano nessuna decisione.", "Sulle tue posizioni, 9", "Tutte, 312", + "Oggi 06:10, da CoinDesk", "Cosa avrebbe fatto la regola: avrebbe fermato per 24 ore gli aumenti della posizione su SOL/EUR. Solo registrato.", + "Neutra, evento in arrivo", "con le regole attive niente nuovi acquisti di mean reversion su JPM prima dei conti. Solo registrato.", "Mercato USA", "Una sola fonte", "Negativa, non confermata", "Leggermente positiva", "Importanza 3 su 5", "Importanza 2 su 5", - "niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", "Mostra le altre 3", + "niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", "Mostra le altre 3", "Crypto: paura o avidità", "su 100, paura", "17,8", "calmo", "+0,006%", "nella norma", "Oggi, 16:00", "Fiducia dei consumatori USA", "Impatto medio: nessun blocco", - "Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: niente mean reversion fino a martedì", - "Mercoledì 14 ottobre, 14:30", "Impatto alto: nessun nuovo ingresso dalle 14:00 alle 15:00", - "Mercoledì 28 ottobre, 19:00", "Impatto alto: nessun nuovo ingresso dalle 18:30 alle 20:00", + "Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: con le regole attive niente mean reversion fino a martedì. Solo registrato.", + "Mercoledì 14 ottobre, 14:30", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 14:00 alle 15:00. Solo registrato.", + "Mercoledì 28 ottobre, 19:00", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 18:30 alle 20:00. Solo registrato.", "Alpaca News", "in tempo reale", "14 testate e banche centrali", "Comunicati alla SEC", "aggiornato alle 08:00", "oggi è costato 0,04 € su un tetto di 0,50 €", }) @@ -156,7 +156,7 @@ public sealed class NewsScreenTests // A new installation without market data: the screen says what is missing. var empty = await server.TextAsync("/notizie"); - StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna con un effetto in corso."); + StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna su cui una regola avrebbe agito."); StringAssert.Contains(empty, "Non leggo ancora notizie"); var store = new NewsStore(services.Db, server.Host.Clock); diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs index 03f88f4..0825b84 100644 --- a/tests/Anubis.Tests/OverviewScreenTests.cs +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -33,7 +33,7 @@ public sealed class OverviewScreenTests "BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6", "In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)", "Nessuna strategia usa soldi veri.", - "Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL", + "Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: la regola l'avrebbe fermata, solo registrato", "Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00", "connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00", }) @@ -61,8 +61,8 @@ public sealed class OverviewScreenTests var all = await server.TextAsync("/diario"); StringAssert.Contains(all, "Oggi, venerdì 9 ottobre"); StringAssert.Contains(all, "Ieri, giovedì 8 ottobre"); - StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:"); - StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana."); + StringAssert.Contains(all, "Comprate 2 AAPL a 259,80 $."); + Assert.IsFalse(all.Contains("Ho cambiato una regola", StringComparison.Ordinal), "With the rules only measured the news write no line (ADR 0027)."); StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\""); StringAssert.Contains(all, "Perché l'ho comprata e venduta"); Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown."); @@ -79,10 +79,10 @@ public sealed class OverviewScreenTests StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora."); // The search ignores case and accents, and keeps the kind chosen. - var search = await server.TextAsync("/diario?cerca=MARTEDI"); - StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:"); + var search = await server.TextAsync("/diario?cerca=NON%20E%20ANCORA"); + StringAssert.Contains(search, "non è ancora tornata sopra la media"); Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal)); - StringAssert.Contains(search, "Una voce con «MARTEDI»"); + StringAssert.Contains(search, "Una voce con «NON E ANCORA»"); var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana"); StringAssert.Contains(none, "Nessuna voce con «solana»"); } diff --git a/tests/Anubis.Tests/QuarterlyReviewTests.cs b/tests/Anubis.Tests/QuarterlyReviewTests.cs index 57e1c3c..b50777f 100644 --- a/tests/Anubis.Tests/QuarterlyReviewTests.cs +++ b/tests/Anubis.Tests/QuarterlyReviewTests.cs @@ -859,6 +859,10 @@ public sealed class QuarterlyReviewTests Assert.AreEqual(1, report.RestrictionsEver.Lines.Single().Increases); Assert.AreEqual(report.RestrictionsEver.Lines.Single(), report.Restrictions.Lines.SingleOrDefault()); Assert.AreEqual(new DateOnly(2026, 8, 15), report.RestrictionsFrom); + + // Beside the balance of the period when the rules acted, the five rules measured in the shadow (ADR 0027 point 17). + CollectionAssert.AreEqual(ShadowRules.All.Select(r => r.Key).ToList(), report.ShadowRules.Select(r => r.Key).ToList()); + Assert.AreEqual("Nessun caso finora", report.ShadowRules[0].State); } /// The decisions of the live engine, as they are written, give the balance.