Fix what the independent review of Phase 7 found and close the phase (refs #61)
ci / test (postgres) (push) Successful in 4m14s
ci / test (sqlite) (push) Successful in 4m41s
ci / test (postgres) (pull_request) Successful in 4m22s
ci / test (sqlite) (pull_request) Successful in 4m33s
ci / image (push) Successful in 2m51s
ci / image (pull_request) Successful in 50s
ci / test (postgres) (push) Successful in 4m14s
ci / test (sqlite) (push) Successful in 4m41s
ci / test (postgres) (pull_request) Successful in 4m22s
ci / test (sqlite) (pull_request) Successful in 4m33s
ci / image (push) Successful in 2m51s
ci / image (pull_request) Successful in 50s
Linking missed Italian elisions, "The" names and common aliases; keywords missed words after an apostrophe; stories about two companies merged and confirmed each other; a story that became serious late was measured from its first article. The news round delayed the engine and the risk check, and the classifier ran inside the database writer. The earnings row started and ended on the wrong sessions, the one-step comparison ignored it, and a purchase was said to be put off when it was not, or sent at the open. ADR 0017 records the choices; what depends on the user is in #107 and #55. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
61878c2023
commit
a3ff8ea6b7
22 files changed
+862
-123
No files matched your search
@@ -131,6 +131,7 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio
|
||||
| M3 | 10–20 ms per titolo su CPU | misurato | Il 15/11/2026, con ONNX Runtime 1.31.1 per .NET e il modello quantizzato su un solo thread: 23–24 ms per titolo sul PC di sviluppo (test `TheModelReadsTheToneOfFinancialHeadlines`). Con più thread scende, ma Anubis ne usa uno (ADR 0014, punto 8). | — |
|
||||
| M4 | Claude Haiku 5.5: 0,10 $ in ingresso e 0,50 $ in uscita per milione di token (fino a 100.000 token); batch a metà prezzo; non ancora nella panoramica dei modelli | cambiato | Ora **è** nella panoramica, con identificativo `claude-haiku-5-5`. Prezzi confermati. Oltre i 100.000 token costa 0,50 $ e 2,50 $. | https://platform.claude.com/docs/en/about-claude/models/overview · https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
| M5 | Claude Haiku 4.5: 1 $ e 5 $ | confermato | Ora è un modello "legacy", ancora disponibile. | https://platform.claude.com/docs/en/about-claude/pricing |
|
||||
| M6 | API Messages di Anthropic: intestazioni `x-api-key` e `anthropic-version` | confermato | Anubis manda `anthropic-version: 2026-10-21`, la più recente alla verifica del 01/12/2026. Questa versione rifiuta `temperature`, `top_p` e `top_k`: Anubis non li manda ad Anthropic. Non è stata provata con una chiave vera: i test usano risposte d'esempio. | https://platform.claude.com/docs/en/api/versioning |
|
||||
|
||||
L'identificativo del modello resta una voce di configurazione, mai una costante nel codice (SPEC 4.5).
|
||||
|
||||
|
||||
+15
-15
@@ -212,24 +212,24 @@ Le notizie usate per evitare guai, mai per comprare.
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013)
|
||||
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013)
|
||||
- [ ] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
|
||||
- [ ] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
|
||||
- [ ] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
|
||||
- [ ] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza
|
||||
- [ ] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario
|
||||
- [ ] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7`
|
||||
- [x] [#95](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/95) Raccolta dei dati per l'analisi e release di prova su Gitea (ADR 0013)
|
||||
- [ ] [#55](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/55) Verifica del rapporto della prova di durata: dal rapporto della release incollato dall'utente (ADR 0013) — **in attesa dell'utente**
|
||||
- [x] [#56](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/56) Raccolta, deduplica e collegamento delle notizie agli strumenti
|
||||
- [x] [#57](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/57) Classificatore locale ONNX e regole sulle parole chiave
|
||||
- [x] [#58](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/58) Analista con modello linguistico facoltativo, sicurezza e tetto di spesa
|
||||
- [x] [#59](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/59) Stato per strumento, regole di 10.5, umore del mercato e recupero dopo un'assenza
|
||||
- [x] [#60](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/60) Schermata Notizie e mercato; Impostazioni su notizie e calendario
|
||||
- [x] [#61](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/61) Chiusura della fase, revisione indipendente e tag `fase-7`
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013)
|
||||
- [ ] Su un archivio di notizie registrate la deduplica e il collegamento superano i test
|
||||
- [ ] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (test dedicato)
|
||||
- [ ] Senza chiave del modello linguistico tutto funziona
|
||||
- [ ] Il tetto di spesa viene rispettato
|
||||
- [ ] Ogni restrizione generata da una notizia compare nel diario con il suo motivo
|
||||
- [ ] La schermata Notizie e mercato corrisponde al mockup
|
||||
- [ ] Il rapporto della prova di durata è in `docs/` e non riporta ordini duplicati né differenze non spiegate (dalla release, ADR 0013) — **in attesa dell'utente** (#55)
|
||||
- [x] Su un archivio di notizie registrate la deduplica e il collegamento superano i test (`TheRecordedArchiveIsGroupedAndLinkedOnBothEngines`, `NamesAreFoundInTheWaysNewspapersWriteThem`, `StoriesAboutDifferentInstrumentsAreNotOne`)
|
||||
- [x] Un testo con istruzioni malevole non produce alcun effetto fuori dallo schema (`MaliciousInstructionsInTheNewsHaveNoEffectOutsideTheSchema`, `BrokenUnicodeInAnAnswerIsRefusedNotThrown`, `AServiceAnswerOfAnyShapeNeverThrows`, `TheSummaryHasNoAddressAndNoInvisibleCharacter`)
|
||||
- [x] Senza chiave del modello linguistico tutto funziona (`WithoutAKeyNothingIsAskedAndEverythingWorks`)
|
||||
- [x] Il tetto di spesa viene rispettato (`TheDailyCapIsNeverExceeded`, `ABrokenAnswerIsPaidOnceAndNeverStopsTheDiary`, `AStopDuringARequestKeepsItsCost`)
|
||||
- [x] Ogni restrizione generata da una notizia compare nel diario con il suo motivo (`TheDiarySaysEachRestrictionOnceAndChecksARumourTwoHoursLater`, `ARestrictionLeavesOutThePurchaseAndTheDiarySaysWhy`)
|
||||
- [x] La schermata Notizie e mercato corrisponde al mockup (`TheDemoShowsTheNewsAndTheMarketAsInTheMockup` e confronto a 1440 e 390 px con il mockup 05)
|
||||
|
||||
## Fase 8 — Apprendimento
|
||||
|
||||
|
||||
+8
-5
@@ -1,10 +1,10 @@
|
||||
# Stato del progetto
|
||||
|
||||
Aggiornato: 2026-11-28
|
||||
Aggiornato: 2026-12-01
|
||||
|
||||
## Fase corrente
|
||||
|
||||
**Fase 7 — Notizie: in corso.** La Fase 6 è completata. La sua prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto. 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 7 — Notizie: completata**, tranne un criterio in attesa dell'utente: il rapporto della prova di durata (#55). La prossima è la Fase 8 — Apprendimento. La prova di durata di 48 ore in casa è stata interrotta più volte dal computer, mai da Anubis, e il 14 novembre l'utente ha scelto un'altra strada (ADR 0013). Ora il bot raccoglie da solo i dati per l'analisi (issue #95). L'utente fa girare la release di prova `v0.7.0` pubblicata su Gitea per il tempo che vuole, poi incolla in chat il rapporto. Il controllo della prova (#55) si fa su quel rapporto e non tiene aperta la fase (`docs/SVILUPPO.md`). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
|
||||
|
||||
## Fatto
|
||||
|
||||
@@ -85,7 +85,7 @@ Aggiornato: 2026-11-28
|
||||
- Telegram: coda con stato, nuovi tentativi e abbandono dopo un giorno; comandi dal telefono solo dalla chat configurata e solo se recenti, `/ferma` con `/conferma`; riepilogo del mattino, stato facoltativo, segnale di vita ogni minuto. Sezione in Impostazioni.
|
||||
- Schermate Panoramica e Diario e sistema come i mockup 01, 08 e 09.
|
||||
- `anubis soak`: il rapporto di una prova di durata, letto dai registri del bot mentre lavora.
|
||||
- **Fase 7, in corso** (ADR 0013):
|
||||
- **Fase 7** (ADR 0013, 0014, 0015, 0016 e 0017):
|
||||
- Raccolta dei dati per l'analisi (#95). Ogni 5 minuti, e a ogni avvio, il bot scrive una fotografia del processo in `diagnostic_samples`: memoria, GC, thread, handle, CPU, eccezioni, dimensione del database, avvisi ed errori dei registri, chiamate HTTP in uscita per destinazione con le durate. Ogni esecuzione di ogni lavoro va in `job_runs`. Si tiene tutto per 30 giorni.
|
||||
- Il rapporto da incollare, in Markdown fino a 60 KB e senza segreti, si ottiene in tre modi: dal pulsante «Scarica i dati per l'analisi» in Diario e sistema, da `/api/diagnostica.md` e da `anubis diagnostics`.
|
||||
- Release di prova per Windows con `tasks release-win`: uno zip con il server, `Avvia Anubis.cmd`, `Prepara i dati da incollare.cmd` e un `LEGGIMI.txt`.
|
||||
@@ -111,6 +111,8 @@ Aggiornato: 2026-11-28
|
||||
- il testo delle notizie viaggia come dato; della risposta vale solo lo schema dell'appendice B, e un giudizio può solo aggiungere una restrizione;
|
||||
- tetto di spesa giornaliero controllato sul costo peggiore prima di ogni richiesta, cache per hash, otto storie per richiesta;
|
||||
- senza chiave non parte nessuna richiesta e tutto funziona come prima.
|
||||
- Esercitazione della guardia: aspetta che la vendita sia partita (#100) e il motore della prova non esce mai dal computer (#102, ADR 0016).
|
||||
- Correzioni della revisione indipendente (#61, ADR 0017): risposte malformate del modello e tetto di spesa, giro delle notizie accanto alla coda dei lavori, nomi e parole chiave, storie di società diverse, inizio delle finestre, trimestrali, acquisti rimandati, confronto a un passo.
|
||||
|
||||
## In corso
|
||||
|
||||
@@ -119,7 +121,7 @@ Nulla.
|
||||
## Prossimo passo
|
||||
|
||||
1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55.
|
||||
2. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56), primo giudizio con il classificatore (#57), analista facoltativo (#58), regole di 10.5 (#59) e schermata Notizie (#60) sono fatti. Resta la chiusura della fase (#61), dopo il controllo della prova (#55).
|
||||
2. La Fase 8 — Apprendimento, in una nuova sessione, sul branch `fase-8` da `main`.
|
||||
3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
|
||||
|
||||
## Da sapere
|
||||
@@ -149,12 +151,13 @@ Nulla.
|
||||
| Cosa | Da quando serve | Senza |
|
||||
|---|---|---|
|
||||
| Far girare la release `v0.7.0` e incollare il rapporto in chat | Ora, per il tempo che vuoi | La prova di durata (#55) resta aperta |
|
||||
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa |
|
||||
| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria e Alpaca News (#107) spente; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa |
|
||||
| Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa |
|
||||
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
|
||||
| Token del bot Telegram e chat autorizzata (facoltativi), da Impostazioni → Telegram | Fase 6 | Nessun avviso sul telefono; comandi provati con un finto server |
|
||||
| Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme |
|
||||
| Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
|
||||
| Se mandare alla SEC un nome e un contatto, e quali (facoltativo, #107) | Fase 7 | Niente comunicati EDGAR dei singoli titoli; resta il feed generale della SEC |
|
||||
| Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale |
|
||||
| Prova del template su Unraid | Fase 9 | Criterio in attesa |
|
||||
| Permesso per ogni componente esterno non elencato nell'ADR 0004 | Quando serve | Si scrive in casa |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 0014 — Scelte della Fase 7: raccolta e collegamento delle notizie
|
||||
|
||||
Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5, 10.2, 10.5 e 5.6 per le issue #56–#60. Usa solo i componenti già ammessi dall'ADR 0004
|
||||
Data: 2026-11-14 · Stato: accettata · Precisa SPEC 4.4, 4.5, 10.2, 10.5 e 5.6 per le issue #56–#60. Usa solo i componenti già ammessi dall'ADR 0004 · Punti 3, 4, 7, 9, 10, 13 e 15 precisati dall'ADR 0017
|
||||
|
||||
## Contesto
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# 0017 — Correzioni della revisione indipendente della Fase 7
|
||||
|
||||
Data: 2026-12-01 · Stato: accettata · Precisa l'ADR 0014 (punti 3, 4, 7, 9, 10, 13 e 15) e SPEC 4.4, 5.5, 8.3, 10.2, 10.3, 10.5 e 12.3
|
||||
|
||||
## Contesto
|
||||
|
||||
La revisione con un subagent a contesto pulito (issue #61) ha letto tutto il codice della Fase 7 dopo l'unione di #58 in `main`. Ha trovato difetti veri, alcuni dei quali smentivano le prove date per #58. Ogni difetto è stato riprodotto con un test che falliva, oppure verificato leggendo il codice, e poi corretto.
|
||||
|
||||
## Decisione
|
||||
|
||||
**1. L'analista con il modello linguistico (ADR 0014, punto 15).**
|
||||
- Una risposta che è JSON valido ma non testo valido (mezzo carattere Unicode, una forma inattesa) si scarta come ogni valore fuori dallo schema. Prima generava un'eccezione: la richiesta si ripagava a ogni giro fuori dal tetto e il diario delle notizie si fermava.
|
||||
- Il costo stimato si scrive **prima** della richiesta e si sostituisce con quello vero alla risposta. Uno spegnimento a metà conta la stima.
|
||||
- La stima conta un token per ogni byte mandato, più 1.000 token di margine del servizio. Il costo vero si registra sempre intero, anche se supera la stima: prima veniva tagliato alla stima e la spesa poteva superare il tetto senza che si vedesse.
|
||||
- Qualunque guasto dell'analista o di una fonte resta suo: le altre fonti si leggono e il diario si scrive.
|
||||
- Il riassunto rifiuta anche gli indirizzi senza `http` e i caratteri invisibili o che invertono il testo.
|
||||
|
||||
**2. Il giro delle notizie non rallenta il motore.**
|
||||
- Il lavoro "notizie" gira accanto alla coda dei lavori e mai due volte insieme. Prima una fonte lenta o il modello ritardavano il battito del motore e il controllo del rischio di diversi minuti. Alla chiusura del bot si aspetta che finisca.
|
||||
- Il classificatore legge gli articoli prima di prendere la scrittura del database, che è una sola per tutto il bot.
|
||||
|
||||
**3. Parole e nomi.**
|
||||
- L'apostrofo separa le parole chiave come ogni altro segno: "un'indagine" e 'fraud' tra apici si trovano.
|
||||
- Un nome si trova anche dopo un articolo con l'apostrofo ("dell'Apple"), con il possessivo inglese e nella prima parte di una parola composta ("Apple-led"). Un nome che contiene il possessivo resta intero: "Wendy's" non è "Wendy".
|
||||
- "The" non fa parte del nome, davanti o tra parentesi. Se dopo "The" resta una parola sola (The Metals Company) il nome non collega da solo: serve il ticker o l'elenco degli alias.
|
||||
- Gli alias sono un elenco breve nel codice dei modi comuni di chiamare le grandi società (Google, Facebook, JPMorgan, Coca-Cola, Boeing…). Valgono solo se il ticker è nel catalogo.
|
||||
- Due classi di azioni con lo stesso nome (Alphabet) si collegano tutte e due.
|
||||
|
||||
**4. Storie.**
|
||||
- Un articolo entra in una storia solo se parla di almeno uno degli stessi strumenti, o se uno dei due non ne nomina nessuno. Prima "Apple batte le stime" e "Microsoft batte le stime" erano la stessa storia, e una confermava l'altra.
|
||||
- Le finestre di 10.5 si contano dal primo articolo con l'importanza della storia, non dal primo in assoluto: una storia diventata grave dopo 40 ore vale 72 ore da allora. Quello che solo il modello alza conta dall'inizio, perché il modello legge la storia com'era al primo arrivo. Il tono resta contato dall'inizio.
|
||||
- Il caso grave mostrato segue l'ordine di 10.2 e non l'alfabeto.
|
||||
- Cambiare l'etichetta "affidabile" di una fonte vale anche per le storie già lette.
|
||||
|
||||
**5. Trimestrali.**
|
||||
- Conti usciti prima dell'apertura o durante la seduta liberano l'ingresso della seduta dopo; quelli dopo la chiusura, o senza orario, lo fermano (10.5). Prima fermavano tutti.
|
||||
- La riga del diario si scrive quando la restrizione comincia davvero: seduta d'ingresso più tre, cioè quattro giorni lavorativi. Una festività in mezzo può ritardare la riga di un giorno, ma non la regola, che conta le sedute di borsa. Senza un calendario fresco di Finnhub la riga non si scrive, come la regola non agisce.
|
||||
- Una notizia su un titolo tenuto o candidato con i conti in arrivo si **mostra** con importanza 3 e "evento in arrivo" (10.2, punto 4). L'importanza salvata non cambia: una notizia con il tono non letto diventerebbe altrimenti "negativa" solo per il calendario.
|
||||
|
||||
**6. Acquisti fermati e confronto a un passo.**
|
||||
- Una restrizione che finisce prima dell'ora dell'acquisto non cambia niente e il diario tace. Quando il giorno è un altro, il diario lo dice.
|
||||
- Un acquisto di azioni rimandato a mercato chiuso va cinque minuti dopo l'apertura, come tutti (5.5), non all'apertura.
|
||||
- Il confronto a un passo (12.3) rifà la decisione con lo stesso calendario delle trimestrali. Prima segnava come differenza ogni acquisto tolto per i conti, e quel conto serve per passare di stadio.
|
||||
|
||||
**7. Quello che manca di 10.2, punto 1.**
|
||||
- Il flusso Alpaca News richiede le chiavi del conto paper, che non ci sono. Resta facoltativo (API-NOTES, A5).
|
||||
- I comunicati SEC dei titoli in portafoglio vengono da EDGAR, che chiede nell'intestazione un nome e un contatto (API-NOTES, F8). Il contatto è un dato dell'utente: non si manda senza il suo permesso. Il feed generale dei comunicati SEC resta tra le fonti.
|
||||
- Le due parti sono nella issue #107, in attesa dell'utente.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Più collegamenti giusti vogliono dire più restrizioni giuste, e anche qualche restrizione in più: la direzione resta prudente.
|
||||
- Gli alias vanno aggiornati a mano se una grande società cambia nome.
|
||||
- Le storie e gli articoli già salvati non si rileggono: valgono le nuove regole per quelli che arrivano.
|
||||
@@ -119,6 +119,12 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche
|
||||
/// </summary>
|
||||
public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15);
|
||||
|
||||
/// <summary>
|
||||
/// A job that can take long (the round of the news): it runs beside the others, never with itself. The queue, where
|
||||
/// the engine and the risk check are, does not wait for it.
|
||||
/// </summary>
|
||||
public bool Beside { get; init; }
|
||||
|
||||
/// <summary>A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job.</summary>
|
||||
public bool IsMove { get; init; }
|
||||
|
||||
@@ -165,6 +171,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
|
||||
private readonly Dictionary<string, (ScheduledJob Job, DateTimeOffset? Due)> _jobs = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, DateTimeOffset> _recovering = new(StringComparer.Ordinal);
|
||||
private readonly List<JobRun> _missed = [];
|
||||
private readonly Dictionary<string, Task> _beside = new(StringComparer.Ordinal);
|
||||
private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
/// <summary>Moment of the last loop iteration; the health check uses it to see the loop is alive.</summary>
|
||||
@@ -230,6 +237,28 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
|
||||
}
|
||||
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await LoopAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The jobs beside the queue stop with it: nothing runs after the loop.
|
||||
await BesideAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for the jobs that run beside the queue.</summary>
|
||||
public Task BesideAsync()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return Task.WhenAll(_beside.Values);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
@@ -308,44 +337,57 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
|
||||
dueAt = recovering ? missedDue : queuedAt;
|
||||
}
|
||||
|
||||
if (recovering)
|
||||
{
|
||||
await RecoverAsync(job, dueAt, started, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (started - dueAt > job.MaxLateness)
|
||||
if (!recovering && started - dueAt > job.MaxLateness)
|
||||
{
|
||||
LogSkipped(_logger, job.Name, dueAt);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, started, JobOutcome.Skipped, "Orario superato di troppo: il lavoro non è stato eseguito."));
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
if (!job.Beside)
|
||||
{
|
||||
await job.Run(cancellationToken).ConfigureAwait(false);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null));
|
||||
await RunOneAsync(job, dueAt, started, recovering, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
LogFailed(_logger, ex, job.Name);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message));
|
||||
if (_beside.TryGetValue(job.Name, out var running) && !running.IsCompleted)
|
||||
{
|
||||
continue; // The round before is not over: this one is not needed.
|
||||
}
|
||||
|
||||
_beside[job.Name] = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunOneAsync(job, dueAt, started, recovering, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A run missed while the bot was off, made once now: never skipped for lateness, reported as recovered.</summary>
|
||||
private async Task RecoverAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, CancellationToken cancellationToken)
|
||||
/// <summary>One run. One missed while the bot was off and made now is reported as recovered.</summary>
|
||||
private async Task RunOneAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, bool recovering, CancellationToken cancellationToken)
|
||||
{
|
||||
void Publish(JobOutcome outcome, string? error) => bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, outcome, error)
|
||||
{
|
||||
Missed = recovering,
|
||||
Description = recovering ? job.Description : null,
|
||||
});
|
||||
try
|
||||
{
|
||||
await job.Run(cancellationToken).ConfigureAwait(false);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null) { Missed = true, Description = job.Description });
|
||||
Publish(JobOutcome.Completed, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogFailed(_logger, ex, job.Name);
|
||||
bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message) { Missed = true, Description = job.Description });
|
||||
Publish(JobOutcome.Failed, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -473,6 +473,9 @@ public static class Zones
|
||||
|
||||
public static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
||||
|
||||
/// <summary>The calendar day of a moment in a zone.</summary>
|
||||
public static DateOnly DayIn(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime);
|
||||
|
||||
public static DateTimeOffset At(DateOnly day, TimeOnly time, TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
|
||||
@@ -80,7 +80,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
News = new News.NewsCollector(_http, db, clock, _logger)
|
||||
{
|
||||
ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"),
|
||||
Watcher = new News.NewsWatcher(db, clock, settings),
|
||||
Watcher = new News.NewsWatcher(db, clock, settings) { EarningsActive = References.EarningsFilterActiveAsync },
|
||||
Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_http, config, key), _logger),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ public static partial class NewsJudge
|
||||
/// <summary>The first serious case named by the text, in the order of 10.2, or null.</summary>
|
||||
public static string? Severe(string title, string? summary)
|
||||
{
|
||||
var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant().Replace('’', '\''), " "), " ") + " ";
|
||||
var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant(), " "), " ") + " ";
|
||||
foreach (var (kind, phrases) in Keywords)
|
||||
{
|
||||
if (phrases.Any(p => text.Contains(" " + p + " ", StringComparison.Ordinal)))
|
||||
@@ -121,7 +121,8 @@ public static partial class NewsJudge
|
||||
return new NewsJudgement(score, severe, importance);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}']+")]
|
||||
// An apostrophe ends a word like any other sign: "un'indagine" and 'fraud' in quotes carry the keyword.
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}]+")]
|
||||
private static partial Regex NonWord();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
|
||||
+115
-23
@@ -65,6 +65,19 @@ public sealed partial class NewsLinker
|
||||
["Arbitrum"] = "ARB",
|
||||
};
|
||||
|
||||
// How newspapers call a company whose name in the catalogue is longer or written in another way. Used only when the
|
||||
// ticker is in the catalogue. Ordinary words are left out: "Metals" or "Joint" would link the wrong stories.
|
||||
private static readonly (string Ticker, string[] Names)[] Aliases =
|
||||
[
|
||||
("ALL", ["Allstate"]), ("AMD", ["AMD"]), ("BA", ["Boeing"]), ("BAC", ["BofA"]), ("C", ["Citi"]), ("CI", ["Cigna"]), ("CLX", ["Clorox"]),
|
||||
("COIN", ["Coinbase"]), ("COST", ["Costco"]), ("DIS", ["Disney"]), ("GM", ["GM"]), ("GOOG", ["Google"]), ("GOOGL", ["Google"]),
|
||||
("GS", ["Goldman Sachs", "Goldman"]), ("HD", ["Home Depot"]), ("HOOD", ["Robinhood"]), ("HSY", ["Hershey"]), ("IBM", ["IBM"]), ("JPM", ["JPMorgan", "J.P. Morgan", "JP Morgan"]),
|
||||
("KHC", ["Kraft Heinz"]), ("KO", ["Coca-Cola", "Coca Cola"]), ("KR", ["Kroger"]), ("LLY", ["Eli Lilly"]), ("MCD", ["McDonald's"]), ("META", ["Meta", "Facebook"]),
|
||||
("MSTR", ["MicroStrategy"]), ("MU", ["Micron"]), ("MRVL", ["Marvell"]), ("PEP", ["Pepsi"]), ("PG", ["Procter & Gamble", "P&G"]), ("PLTR", ["Palantir"]),
|
||||
("RIVN", ["Rivian"]), ("RTX", ["Raytheon"]), ("SCHW", ["Charles Schwab"]), ("SHW", ["Sherwin-Williams"]), ("SMCI", ["Super Micro", "Supermicro"]),
|
||||
("TMUS", ["T-Mobile"]), ("UBER", ["Uber"]), ("VZ", ["Verizon"]), ("WFC", ["Wells Fargo"]), ("XOM", ["Exxon", "ExxonMobil"]),
|
||||
];
|
||||
|
||||
// Words of a theme, lower case: one of them in a title or summary links the story to the class or to the market.
|
||||
private static readonly (string Scope, string Target, string[] Words)[] Themes =
|
||||
[
|
||||
@@ -98,7 +111,7 @@ public sealed partial class NewsLinker
|
||||
private static readonly string[] Suffixes =
|
||||
[
|
||||
", Inc.", " Inc.", " Inc", ", Inc", " Incorporated", " Corporation", " Corp.", " Corp", " Company", " Co.", " Holdings", " Holding", " Group",
|
||||
" Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com",
|
||||
" Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com", " (The)", " -",
|
||||
];
|
||||
|
||||
private readonly Dictionary<string, string> _equityTickers = new(StringComparer.Ordinal);
|
||||
@@ -143,6 +156,17 @@ public sealed partial class NewsLinker
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (ticker, names) in Aliases)
|
||||
{
|
||||
if (dictionary._equityTickers.TryGetValue(ticker, out var target))
|
||||
{
|
||||
foreach (var name in names)
|
||||
{
|
||||
dictionary.AddName(name, target, alias: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (name, coin) in CoinNames)
|
||||
{
|
||||
if (dictionary._coins.TryGetValue(coin, out var targets))
|
||||
@@ -157,7 +181,11 @@ public sealed partial class NewsLinker
|
||||
return dictionary;
|
||||
}
|
||||
|
||||
/// <summary>"Apple Inc. Common Stock" → "Apple"; null when what remains is too short or an ordinary word.</summary>
|
||||
/// <summary>
|
||||
/// "Apple Inc. Common Stock" → "Apple", "The Goldman Sachs Group, Inc." → "Goldman Sachs"; null when what remains is
|
||||
/// too short or an ordinary word. A name with "The" of which one word remains (The Metals Company) is often an ordinary
|
||||
/// word too: it needs its ticker or a place among the aliases.
|
||||
/// </summary>
|
||||
public static string? CompanyName(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
@@ -188,7 +216,13 @@ public sealed partial class NewsLinker
|
||||
}
|
||||
}
|
||||
|
||||
return clean.Length < 3 || Ambiguous.Contains(clean) ? null : clean;
|
||||
var article = name.Contains("(The)", StringComparison.OrdinalIgnoreCase);
|
||||
if (clean.StartsWith("The ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
(clean, article) = (clean[4..].TrimStart(), true);
|
||||
}
|
||||
|
||||
return clean.Length < 3 || Ambiguous.Contains(clean) || (article && !clean.Contains(' ', StringComparison.Ordinal)) ? null : clean;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -234,29 +268,47 @@ public sealed partial class NewsLinker
|
||||
}
|
||||
}
|
||||
|
||||
var words = Words().Matches(text).Select(m => Possessive().Replace(m.Value, "").TrimEnd('.')).Where(w => w.Length > 0).ToList();
|
||||
var words = Tokens(text);
|
||||
for (var i = 0; i < words.Count; i++)
|
||||
{
|
||||
// A coin's ticker in capitals (BTC, ETH, SOL) is a link: news write them that way.
|
||||
if (words[i].Length >= 3 && words[i].All(char.IsUpper) && _coins.TryGetValue(words[i], out var coins))
|
||||
foreach (var form in words[i])
|
||||
{
|
||||
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
|
||||
}
|
||||
|
||||
if (!char.IsUpper(words[i][0]) || !_names.TryGetValue(words[i], out var candidates))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var (nameWords, target) in candidates.OrderByDescending(c => c.Words.Length))
|
||||
{
|
||||
if (i + nameWords.Length <= words.Count
|
||||
&& nameWords.Select((w, k) => string.Equals(w, words[i + k], StringComparison.OrdinalIgnoreCase)).All(x => x))
|
||||
if (form.Length >= 3 && form.All(char.IsUpper) && _coins.TryGetValue(form, out var coins))
|
||||
{
|
||||
Add(LinkScopes.Instrument, target, LinkVia.Name);
|
||||
break;
|
||||
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
|
||||
}
|
||||
}
|
||||
|
||||
var longest = 0;
|
||||
var found = new List<string>();
|
||||
foreach (var form in words[i].Where(f => char.IsUpper(f[0]) && _names.ContainsKey(f)))
|
||||
{
|
||||
foreach (var (nameWords, target) in _names[form])
|
||||
{
|
||||
// Two share classes have the same name (Alphabet): the longest name wins, with every instrument it names.
|
||||
if (nameWords.Length >= longest && i + nameWords.Length <= words.Count
|
||||
&& !nameWords.Where((w, k) => !words[i + k].Contains(w, StringComparer.OrdinalIgnoreCase)).Any())
|
||||
{
|
||||
if (nameWords.Length > longest)
|
||||
{
|
||||
longest = nameWords.Length;
|
||||
found.Clear();
|
||||
}
|
||||
|
||||
found.Add(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "Apple-led", "Nvidia-backed": the first part, when it is a whole name of its own.
|
||||
if (longest == 0 && words[i][^1].IndexOf('-', StringComparison.Ordinal) is var dash and > 0 && char.IsUpper(words[i][^1][0])
|
||||
&& _names.TryGetValue(words[i][^1][..dash], out var parts))
|
||||
{
|
||||
found.AddRange(parts.Where(p => p.Words.Length == 1).Select(p => p.Target));
|
||||
}
|
||||
|
||||
found.ForEach(t => Add(LinkScopes.Instrument, t, LinkVia.Name));
|
||||
}
|
||||
|
||||
// "(NASDAQ: AAPL)" names the listing of one company, not the stock market as a whole.
|
||||
@@ -278,10 +330,44 @@ public sealed partial class NewsLinker
|
||||
return links;
|
||||
}
|
||||
|
||||
private void AddName(string name, string target)
|
||||
/// <summary>
|
||||
/// The words of a text, each in the forms a name can have in it: as written ("McDonald's"), without the Italian article
|
||||
/// before the apostrophe ("dell'Apple" is also "Apple"), without the possessive ("Apple's" is also "Apple").
|
||||
/// </summary>
|
||||
private static List<string[]> Tokens(string text)
|
||||
{
|
||||
var words = Words().Matches(name).Select(m => m.Value.TrimEnd('.')).Where(w => w.Length > 0).ToArray();
|
||||
if (words.Length == 0 || (words.Length == 1 && (words[0].Length < 3 || Ambiguous.Contains(words[0]))))
|
||||
var tokens = new List<string[]>();
|
||||
foreach (Match match in Words().Matches(Curly().Replace(text, "'")))
|
||||
{
|
||||
var forms = new List<string>();
|
||||
void Form(string form)
|
||||
{
|
||||
if (form.TrimEnd('.', '-', '\'') is { Length: > 0 } clean && !forms.Contains(clean))
|
||||
{
|
||||
forms.Add(clean);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var form in new[] { match.Value, Elision().Replace(match.Value, "") })
|
||||
{
|
||||
Form(form);
|
||||
Form(Possessive().Replace(form, ""));
|
||||
}
|
||||
|
||||
if (forms.Count > 0)
|
||||
{
|
||||
tokens.Add([.. forms]);
|
||||
}
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private void AddName(string name, string target, bool alias = false)
|
||||
{
|
||||
// The name as the catalogue writes it: "Wendy's" is never just "Wendy".
|
||||
var words = Words().Matches(Curly().Replace(name, "'")).Select(m => m.Value.TrimEnd('.', '-', '\'')).Where(w => w.Length > 0).ToArray();
|
||||
if (words.Length == 0 || (words.Length == 1 && ((words[0].Length < 3 && !alias) || Ambiguous.Contains(words[0]))))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -306,9 +392,15 @@ public sealed partial class NewsLinker
|
||||
[GeneratedRegex(@"[\p{L}\p{N}][\p{L}\p{N}&'.\-]*")]
|
||||
private static partial Regex Words();
|
||||
|
||||
[GeneratedRegex(@"['’]s$")]
|
||||
[GeneratedRegex(@"'s$")]
|
||||
private static partial Regex Possessive();
|
||||
|
||||
[GeneratedRegex(@"^(?:l|un|dell|all|nell|dall|sull|coll|quest|quell|d)'(?=.)", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex Elision();
|
||||
|
||||
[GeneratedRegex("[’‘`´]")]
|
||||
private static partial Regex Curly();
|
||||
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}&]+")]
|
||||
private static partial Regex NonWord();
|
||||
|
||||
|
||||
@@ -43,13 +43,13 @@ 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);
|
||||
// A restriction lasts at most 72 hours: stories older than that and the window are never in force.
|
||||
var oldest = since - NewsRules.Longest;
|
||||
// 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 =>
|
||||
{
|
||||
const string Recent = "st.first_seen_at >= @oldest";
|
||||
var st = await s.QueryAsync(
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " +
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + NewsDesk.RaisedAt +
|
||||
"v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, v.summary AS model_summary, " +
|
||||
"(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id ORDER BY i.created_at, i.id LIMIT 1) AS publisher " +
|
||||
"FROM news_stories st LEFT JOIN news_verdicts v ON v.id = st.verdict_id WHERE " + Recent,
|
||||
@@ -70,6 +70,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
|
||||
return (st, l, n, h);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// An event in the calendar about a held or candidate stock is worth 3 (10.2 point 4). Only what is shown: the rules of
|
||||
// 10.5 for a report are their own row, and a story with an unread tone must not restrict because of the calendar.
|
||||
var watched = (await NewsWatcher.WatchedAsync(db, cancellationToken).ConfigureAwait(false)).Select(w => w.Target).ToHashSet(StringComparer.Ordinal);
|
||||
var reporting = (await NewsDesk.NearEarningsAsync(db, clock, now, cancellationToken).ConfigureAwait(false)).Select(e => Venues.Alpaca + ":" + e.Symbol)
|
||||
.Where(watched.Contains).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var holding = held.Where(h => h.Quantity > 0m).ToList();
|
||||
var heldTargets = holding.Select(h => h.Target).ToHashSet(StringComparer.Ordinal);
|
||||
var heldClasses = holding.Select(h => h.Class).ToHashSet(StringComparer.Ordinal);
|
||||
@@ -104,12 +110,13 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
|
||||
|
||||
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);
|
||||
// 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)) +
|
||||
(NewsRules.Unconfirmed(story) ? ", non confermata" : "") + (storyNotes.Any(n => n.Kind == NewsReasons.Earnings) ? ", evento in arrivo" : "");
|
||||
(NewsRules.Unconfirmed(story) ? ", non confermata" : "") + (coming ? ", evento in arrivo" : "");
|
||||
// The importance shown is the one the rules use: the model's counts only when negative and about this story's instruments.
|
||||
var importance = story.RuleImportance;
|
||||
var importance = coming ? Math.Max(3, story.RuleImportance) : story.RuleImportance;
|
||||
rows.Add(new NewsBoardRow(story.Id, story.Start, story.Publisher, About(own, instruments), story.Sources <= 1 && !story.Trusted, story.Title, tone,
|
||||
story.Score is null && modelDirection is not null ? ModelDirection(modelDirection) : Direction(story.Score), Math.Clamp(importance, 1, 5), action, active, onPositions)
|
||||
{ Summary = verdict.Summary });
|
||||
@@ -222,7 +229,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
|
||||
return ("Niente, perché nessun'altra fonte la riportava.", false);
|
||||
}
|
||||
|
||||
var matched = NewsRules.Active([story], story.Start, NewsRuleSwitches.AllOn) is { Count: > 0 } found ? found[0] : null;
|
||||
var matched = NewsRules.Active([story], story.EffectStart > story.FirstSeenAt ? story.EffectStart : story.FirstSeenAt, NewsRuleSwitches.AllOn) is { Count: > 0 } found ? found[0] : null;
|
||||
if (matched is not null)
|
||||
{
|
||||
if (matched.Code == NewsReasons.Severe ? !switches.Severe : !switches.Negative)
|
||||
|
||||
@@ -92,7 +92,7 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
|
||||
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval };
|
||||
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval, Beside = true };
|
||||
|
||||
/// <summary>One round over the sources that are due.</summary>
|
||||
public async Task RunOnceAsync(CancellationToken cancellationToken)
|
||||
|
||||
+46
-10
@@ -24,7 +24,7 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
|
||||
/// <summary>The stories linked to <paramref name="target"/> seen since <paramref name="since"/>, oldest first.</summary>
|
||||
public async Task<IReadOnlyList<StoryFact>> StoriesAsync(string target, DateTimeOffset since, CancellationToken cancellationToken) =>
|
||||
await db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " +
|
||||
"SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + RaisedAt +
|
||||
"v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, " +
|
||||
"(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id ORDER BY i.created_at, i.id LIMIT 1) AS publisher " +
|
||||
"FROM news_stories st JOIN news_links l ON l.story_id = st.id LEFT JOIN news_verdicts v ON v.id = st.verdict_id " +
|
||||
@@ -49,8 +49,9 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next earnings date of each stock from <paramref name="from"/> on, as the calendar of 4.4 has it: the day in
|
||||
/// New York. <c>equity_meanrev</c> reads it (10.5, fourth row; 8.3 for its exit).
|
||||
/// The next earnings date of each stock after the close of <paramref name="from"/>, as the calendar of 4.4 has it: the
|
||||
/// day in New York. <c>equity_meanrev</c> reads it (10.5, fourth row; 8.3 for its exit). A report of that day before the
|
||||
/// open or during the session is already out: the next session is free.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyDictionary<string, DateOnly>> EarningsAsync(DateOnly from, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -59,18 +60,51 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
|
||||
var next = new Dictionary<string, DateOnly>(StringComparer.Ordinal);
|
||||
foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { Length: > 0 }).OrderBy(e => e.OccursAt))
|
||||
{
|
||||
next.TryAdd(e.Symbol!, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime));
|
||||
var day = Zones.DayIn(e.OccursAt, Zones.NewYork);
|
||||
if (day > from || e.TimeHint is not ("bmo" or "dmh"))
|
||||
{
|
||||
next.TryAdd(e.Symbol!, day);
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The last day of a report that already keeps <c>equity_meanrev</c> out at <paramref name="now"/>: the entry session
|
||||
/// and the three after it, so four working days from today in New York. A holiday in between only delays the line of
|
||||
/// the diary by a day: the strategy counts from the sessions of the broker's calendar.
|
||||
/// </summary>
|
||||
public static DateOnly EarningsReach(DateTimeOffset now)
|
||||
{
|
||||
var day = Zones.DayIn(now, Zones.NewYork);
|
||||
for (var sessions = 0; sessions < 4;)
|
||||
{
|
||||
day = day.AddDays(1);
|
||||
sessions += day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday ? 0 : 1;
|
||||
}
|
||||
|
||||
return day;
|
||||
}
|
||||
|
||||
/// <summary>The reports from <paramref name="now"/> on that keep <c>equity_meanrev</c> out already.</summary>
|
||||
internal static async Task<IReadOnlyList<CalendarEvent>> NearEarningsAsync(Database db, IClock clock, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var reach = EarningsReach(now);
|
||||
var events = await new CalendarEventStore(db, clock).BetweenAsync(now, now.AddDays(8), cancellationToken).ConfigureAwait(false);
|
||||
return [.. events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { Length: > 0 } && Zones.DayIn(e.OccursAt, Zones.NewYork) <= reach)];
|
||||
}
|
||||
|
||||
/// <summary>When the first article with the story's own importance came out (<see cref="StoryFact.RaisedAt"/>).</summary>
|
||||
internal const string RaisedAt = "(SELECT MIN(i.published_at) FROM news_items i WHERE i.story_id = st.id AND i.importance = st.importance) AS raised_at, ";
|
||||
|
||||
/// <summary>A story with the verdict of the model joined as model_direction, model_importance, model_instruments, model_problem.</summary>
|
||||
internal static StoryFact ReadStory(DbRow r, IReadOnlyCollection<string> targets) => new(r.Id("id"), r.Text("title"), r.TextOrNull("publisher") ?? "",
|
||||
r.Moment("published_at"), r.Moment("first_seen_at"), (int)r.Number("sources"), r.Bool("trusted"), r.IsNull("score") ? null : r.Measure("score"),
|
||||
r.TextOrNull("severe"), (int)r.Number("importance"),
|
||||
Escalation(r.TextOrNull("model_direction"), r.IsNull("model_importance") ? null : (int)r.Number("model_importance"), r.TextOrNull("model_instruments"),
|
||||
r.TextOrNull("model_problem"), targets));
|
||||
r.TextOrNull("model_problem"), targets))
|
||||
{ RaisedAt = r.MomentOrNull("raised_at") };
|
||||
|
||||
/// <summary>
|
||||
/// What a verdict adds for an instrument: its importance when it is valid, negative and names one of
|
||||
@@ -164,6 +198,9 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
|
||||
|
||||
public TimeZoneInfo Zone { get; init; } = Zones.Rome;
|
||||
|
||||
/// <summary>Whether the earnings calendar is fresh, as the strategies ask (4.4): without it their row does nothing and the diary says nothing.</summary>
|
||||
public Func<CancellationToken, Task<bool>>? EarningsActive { get; init; }
|
||||
|
||||
/// <summary>One round over the instruments watched now: those held by any strategy and those of the latest universes.</summary>
|
||||
public async Task<int> RunOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -204,7 +241,7 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
|
||||
}
|
||||
}
|
||||
|
||||
if (switches.Earnings)
|
||||
if (switches.Earnings && (EarningsActive is null || await EarningsActive(cancellationToken).ConfigureAwait(false)))
|
||||
{
|
||||
written += await EarningsAsync(watched, now, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -225,7 +262,7 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
|
||||
return $"Ho cambiato una regola per 24 ore: {what}. Motivo: {EntryGate.Motive(r.Story)}.";
|
||||
}
|
||||
|
||||
// Earnings of a watched stock in the next five days (three sessions and a weekend): said once, with the day.
|
||||
// Earnings of a watched stock that already keep mean reversion out: said once, with the day.
|
||||
private async Task<int> EarningsAsync(IReadOnlyList<(string Target, string Symbol, bool Held)> watched, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var stocks = watched.Where(w => w.Target.StartsWith(Venues.Alpaca + ":", StringComparison.Ordinal)).ToDictionary(w => w.Symbol, w => w.Target, StringComparer.Ordinal);
|
||||
@@ -235,10 +272,9 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
|
||||
}
|
||||
|
||||
var written = 0;
|
||||
var events = await new CalendarEventStore(db, clock).BetweenAsync(now, now.AddDays(5), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var e in events.Where(e => e.Kind == CalendarEventKinds.Earnings && e.Symbol is { } s && stocks.ContainsKey(s)))
|
||||
foreach (var e in (await NewsDesk.NearEarningsAsync(db, clock, now, cancellationToken).ConfigureAwait(false)).Where(e => stocks.ContainsKey(e.Symbol!)))
|
||||
{
|
||||
var dayText = Format.Day(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime));
|
||||
var dayText = Format.Day(Zones.DayIn(e.OccursAt, Zones.NewYork));
|
||||
var (when, until) = e.TimeHint switch
|
||||
{
|
||||
"bmo" => (" prima dell'apertura", $"fino a {dayText}"),
|
||||
|
||||
@@ -48,6 +48,16 @@ public sealed record StoryFact(Guid Id, string Title, string Publisher, DateTime
|
||||
/// </summary>
|
||||
public DateTimeOffset Start => PublishedAt < FirstSeenAt ? PublishedAt : FirstSeenAt;
|
||||
|
||||
/// <summary>When the first article with the importance of the story came out, when a later one raised it.</summary>
|
||||
public DateTimeOffset? RaisedAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// From when the windows of 10.5 count: the article that made the story what it is. The verdict of the model is about
|
||||
/// the story as first read, so what only the model raises counts from the start; a case the keywords call serious
|
||||
/// counts from its article whatever the model says.
|
||||
/// </summary>
|
||||
public DateTimeOffset EffectStart => RaisedAt is { } raised && raised > Start && Importance >= Math.Min(4, ModelImportance ?? 0) ? raised : Start;
|
||||
|
||||
/// <summary>The importance the rules use: the higher of the two judgements (10.2 point 5).</summary>
|
||||
public int RuleImportance => Math.Max(Importance, ModelImportance ?? 0);
|
||||
|
||||
@@ -118,10 +128,11 @@ public static class NewsRules
|
||||
}
|
||||
|
||||
var (on, code, window) = story.IsSevere ? (switches.Severe, NewsReasons.Severe, SevereWindow) : (switches.Negative, NewsReasons.Negative, NegativeWindow);
|
||||
var until = story.Start + window;
|
||||
if (on && story.Start <= now && now < until)
|
||||
var from = story.EffectStart;
|
||||
var until = from + window;
|
||||
if (on && from <= now && now < until)
|
||||
{
|
||||
active.Add(new NewsRestriction(code, story.Start, until, story));
|
||||
active.Add(new NewsRestriction(code, from, until, story));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,13 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
|
||||
await s.ExecuteAsync("UPDATE news_sources SET enabled = @e, trusted = @t, updated_at = @now WHERE id = @id", cancellationToken,
|
||||
("e", enabled), ("t", trusted), ("now", now), ("id", id)).ConfigureAwait(false);
|
||||
if (before.Trusted != trusted)
|
||||
{
|
||||
// The stories already read count the label as it is now.
|
||||
await s.ExecuteAsync("UPDATE news_stories SET updated_at = @now, trusted = " + TrustedNow + " WHERE id IN (SELECT story_id FROM news_items WHERE source_id = @id)",
|
||||
cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
static string Words(bool on, bool sure) => (on ? "attiva" : "spenta") + (sure ? ", affidabile" : ", non affidabile");
|
||||
if (before.Enabled != enabled || before.Trusted != trusted)
|
||||
{
|
||||
@@ -141,31 +148,62 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
ArgumentNullException.ThrowIfNull(dictionary);
|
||||
var now = clock.UtcNow;
|
||||
|
||||
// The judgement first: the classifier takes its time, and the single writer of the database is the engine's too.
|
||||
int old = 0, known = 0;
|
||||
var fresh = new List<(FeedItem Item, string Key, DateTimeOffset Published, string Language, IReadOnlyList<NewsLink> Links, NewsJudgement Judgement)>();
|
||||
foreach (var item in items.OrderBy(i => i.PublishedAt ?? now))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var published = item.PublishedAt is { } p && p <= now ? p : now;
|
||||
if (now - published > MaxAge)
|
||||
{
|
||||
old++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = NewsMatching.UrlKey(item.Link);
|
||||
if (fresh.Any(f => f.Key == key) ||
|
||||
await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
known++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary);
|
||||
var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic);
|
||||
fresh.Add((item, key, published, language, links,
|
||||
NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier)));
|
||||
}
|
||||
|
||||
if (fresh.Count == 0)
|
||||
{
|
||||
return new IngestResult(0, known, 0, old);
|
||||
}
|
||||
|
||||
return await db.WriteAsync(async s =>
|
||||
{
|
||||
int added = 0, duplicates = 0, old = 0;
|
||||
int added = 0, duplicates = known;
|
||||
var touched = new HashSet<Guid>();
|
||||
var stories = await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t",
|
||||
r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")),
|
||||
("t", now - MaxAge - NewsMatching.StoryWindow)).ConfigureAwait(false);
|
||||
foreach (var item in items.OrderBy(i => i.PublishedAt ?? now))
|
||||
var since = now - MaxAge - NewsMatching.StoryWindow;
|
||||
var about = (await s.QueryAsync("SELECT l.story_id, l.target FROM news_links l JOIN news_stories st ON st.id = l.story_id WHERE l.scope = @sc AND st.published_at >= @t",
|
||||
r => (Story: r.Id("story_id"), Target: r.Text("target")), ("sc", LinkScopes.Instrument), ("t", since)).ConfigureAwait(false)).ToLookup(l => l.Story, l => l.Target);
|
||||
var stories = (await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t",
|
||||
r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")), ("t", since)).ConfigureAwait(false))
|
||||
.Select(st => (st.Id, st.Words, st.Published, Instruments: about[st.Id].ToHashSet(StringComparer.Ordinal))).ToList();
|
||||
foreach (var (item, key, published, language, links, judgement) in fresh)
|
||||
{
|
||||
var published = item.PublishedAt is { } p && p <= now ? p : now;
|
||||
if (now - published > MaxAge)
|
||||
{
|
||||
old++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = NewsMatching.UrlKey(item.Link);
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)).ConfigureAwait(false) > 0)
|
||||
{
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The same words about two companies are two stories: one must never confirm or restrict the other.
|
||||
var words = NewsMatching.Words(item.Title);
|
||||
var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words))
|
||||
var instruments = links.Where(l => l.Scope == LinkScopes.Instrument).Select(l => l.Target).ToHashSet(StringComparer.Ordinal);
|
||||
var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words)
|
||||
&& (instruments.Count == 0 || st.Instruments.Count == 0 || instruments.Overlaps(st.Instruments)))
|
||||
.OrderByDescending(st => NewsMatching.Score(words, st.Words)).Select(st => (Guid?)st.Id).FirstOrDefault();
|
||||
if (story is null)
|
||||
{
|
||||
@@ -175,12 +213,13 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
"VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, 1, @now, @now)", cancellationToken,
|
||||
("id", story), ("title", item.Title), ("key", NewsMatching.TitleKey(item.Title)), ("p", published), ("now", now), ("trusted", source.Trusted))
|
||||
.ConfigureAwait(false);
|
||||
stories.Add((story.Value, words, published));
|
||||
stories.Add((story.Value, words, published, instruments));
|
||||
}
|
||||
else
|
||||
{
|
||||
stories.Single(st => st.Id == story).Instruments.UnionWith(instruments);
|
||||
}
|
||||
|
||||
var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary);
|
||||
var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic);
|
||||
var judgement = NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, score, severe, importance, created_at) " +
|
||||
"VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @score, @severe, @importance, @now)", cancellationToken,
|
||||
@@ -204,9 +243,9 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
await s.ExecuteAsync(
|
||||
"UPDATE news_stories SET last_seen_at = @now, updated_at = @now, " +
|
||||
"sources = (SELECT COUNT(DISTINCT publisher) FROM news_items WHERE story_id = @id), " +
|
||||
"trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0, " +
|
||||
"trusted = " + TrustedNow + ", " +
|
||||
"score = (SELECT AVG(score) FROM news_items WHERE story_id = @id), " +
|
||||
"severe = (SELECT MIN(severe) FROM news_items WHERE story_id = @id), " +
|
||||
"severe = (SELECT i.severe FROM news_items i WHERE i.story_id = @id AND i.severe IS NOT NULL ORDER BY " + SevereOrder + ", i.id LIMIT 1), " +
|
||||
"importance = (SELECT MAX(importance) FROM news_items WHERE story_id = @id) " +
|
||||
"WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false);
|
||||
}
|
||||
@@ -215,6 +254,15 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Whether a trusted source told the story, in an UPDATE of news_stories.
|
||||
private const string TrustedNow =
|
||||
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0";
|
||||
|
||||
// The serious cases in the order of 10.2.
|
||||
private const string SevereOrder =
|
||||
"CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" +
|
||||
SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END";
|
||||
|
||||
private static NewsSource Rss(string url, string name, bool trusted, string? topic) =>
|
||||
new(Guid.Empty, url, name, NewsSourceKinds.Rss, trusted, Enabled: true, topic);
|
||||
|
||||
|
||||
@@ -148,8 +148,12 @@ public static class DiaryText
|
||||
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
|
||||
|
||||
/// <summary>A purchase a rule of SPEC 10.5 put off: it goes when the restriction ends.</summary>
|
||||
public static string EntryPostponed(string symbol, DateTimeOffset until, TimeZoneInfo zone, string reason, string motive) =>
|
||||
$"Ho rimandato l'acquisto di {Shown(symbol)} alle {TimeZoneInfo.ConvertTime(until, zone):HH:mm}. {reason} Motivo: {motive}.";
|
||||
public static string EntryPostponed(string symbol, DateTimeOffset until, DateTimeOffset now, TimeZoneInfo zone, string reason, string motive)
|
||||
{
|
||||
var day = Data.Zones.DayIn(until, zone);
|
||||
var when = day == Data.Zones.DayIn(now, zone) ? "" : $"a {Format.Day(day)} ";
|
||||
return $"Ho rimandato l'acquisto di {Shown(symbol)} {when}alle {TimeZoneInfo.ConvertTime(until, zone):HH:mm}. {reason} Motivo: {motive}.";
|
||||
}
|
||||
|
||||
/// <summary>A purchase a rule of SPEC 10.5 left out: the restriction lasts past its deadline (SPEC 5.6).</summary>
|
||||
public static string EntryRestricted(string symbol, string reason, string motive) => $"Non compro {Shown(symbol)}. {reason} Motivo: {motive}.";
|
||||
|
||||
@@ -492,16 +492,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters);
|
||||
var data = loaded.Data;
|
||||
var options = StrategyPipeline.For(m.Strategy, data, new BacktestOptions());
|
||||
if (Earnings is not null && m.Strategy != StrategyNames.CryptoTrend && await Earnings(m.Day, cancellationToken).ConfigureAwait(false) is { } earnings)
|
||||
{
|
||||
options = options with
|
||||
{
|
||||
NextEarnings = symbol => earnings.Next.TryGetValue(symbol, out var date) ? date : null,
|
||||
EarningsEntries = earnings.BlockEntries,
|
||||
};
|
||||
}
|
||||
|
||||
var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false);
|
||||
DecisionRecord record;
|
||||
if (observation)
|
||||
{
|
||||
@@ -561,6 +552,42 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The earnings calendar as the decision of <paramref name="day"/> reads it (SPEC 10.5, fourth row; 8.3).</summary>
|
||||
private async Task<BacktestOptions> WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Earnings is null || strategy == StrategyNames.CryptoTrend || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
|
||||
{
|
||||
return options;
|
||||
}
|
||||
|
||||
return options with
|
||||
{
|
||||
NextEarnings = symbol => earnings.Next.TryGetValue(symbol, out var date) ? date : null,
|
||||
EarningsEntries = earnings.BlockEntries,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When a purchase held until <paramref name="until"/> can go. A stock goes five minutes after the open at the
|
||||
/// earliest, as every purchase (SPEC 5.5): a restriction that ends with the market closed leaves it to the next open.
|
||||
/// </summary>
|
||||
private DateTimeOffset ReleaseAt(bool crypto, DateTimeOffset until)
|
||||
{
|
||||
if (crypto || _calendar is null)
|
||||
{
|
||||
return until;
|
||||
}
|
||||
|
||||
var day = Zones.DayIn(until, Zones.NewYork);
|
||||
if (_calendar.SessionOn(day) is { } session && until < session.CloseUtc)
|
||||
{
|
||||
var first = session.OpenUtc + Options.OrdersAfterOpen;
|
||||
return until > first ? until : first;
|
||||
}
|
||||
|
||||
return NextSession(day) is { } next ? next.OpenUtc + Options.OrdersAfterOpen : until;
|
||||
}
|
||||
|
||||
private async Task NoDataAsync(Moment m, StrategyStage stage, CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = stage.Stage == StrategyStages.Observation;
|
||||
@@ -627,11 +654,19 @@ public sealed partial class LiveEngine : IDisposable
|
||||
continue;
|
||||
}
|
||||
|
||||
var dropped = order.ValidUntil is { } until && hold.Until > until;
|
||||
holds.Add((order.Symbol, hold, dropped));
|
||||
var release = ReleaseAt(order.Crypto, hold.Until);
|
||||
if (release <= order.Due)
|
||||
{
|
||||
// The restriction is over before the purchase is due: nothing changes, and nothing is said.
|
||||
orders.Add(order);
|
||||
continue;
|
||||
}
|
||||
|
||||
var dropped = order.ValidUntil is { } until && release > until;
|
||||
holds.Add((order.Symbol, hold with { Until = release }, dropped));
|
||||
if (!dropped)
|
||||
{
|
||||
orders.Add(hold.Until > order.Due ? order with { Due = hold.Until, FirstDue = order.Due } : order);
|
||||
orders.Add(order with { Due = release, FirstDue = order.Due });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -812,7 +847,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
if (!observation)
|
||||
{
|
||||
var text = dropped ? DiaryText.EntryRestricted(symbol, ReasonCatalog.Text(hold.Code), hold.Motive)
|
||||
: DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive);
|
||||
: DiaryText.EntryPostponed(symbol, hold.Until, now, Zone, ReasonCatalog.Text(hold.Code), hold.Motive);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, text, new { decision = decisionId, symbol }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -945,7 +980,8 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
|
||||
var state = snapshot.ToState();
|
||||
var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day).Proposed;
|
||||
var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, 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);
|
||||
}
|
||||
@@ -1017,7 +1053,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
if (order.Side == OrderSide.Buy && Gate is not null && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold)
|
||||
{
|
||||
await HoldAsync(order, instrument.Symbol, hold, now, cancellationToken).ConfigureAwait(false);
|
||||
await HoldAsync(order, instrument.Symbol, hold with { Until = ReleaseAt(instrument.IsCrypto, hold.Until) }, now, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1181,7 +1217,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
|
||||
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, symbol, DecisionStages.Order, DecisionOutcomes.Postponed,
|
||||
[hold.Code], new Dictionary<string, object?> { ["planned"] = order.Id, ["until"] = hold.Until, ["motive"] = hold.Motive }, now), cancellationToken).ConfigureAwait(false);
|
||||
await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, DiaryText.EntryPostponed(symbol, hold.Until, Zone, ReasonCatalog.Text(hold.Code), hold.Motive),
|
||||
await Diary.WriteAsync(s, _clock, DiaryKind(hold.Code), hold.Code, DiaryText.EntryPostponed(symbol, hold.Until, now, Zone, ReasonCatalog.Text(hold.Code), hold.Motive),
|
||||
new { planned = order.Id }, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -218,6 +218,51 @@ public sealed class SchedulerTests
|
||||
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
|
||||
}
|
||||
|
||||
/// <summary>A long job beside the queue (the news) never delays the others, never runs twice at once, and is waited for.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task AJobBesideTheQueueNeverDelaysTheOthers()
|
||||
{
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
||||
var bus = new EventBus();
|
||||
using var runs = bus.Subscribe<JobRun>();
|
||||
var scheduler = new Scheduler(clock, bus);
|
||||
int slow = 0, quick = 0;
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
scheduler.Add(new ScheduledJob("a-notizie", "Lunga", Schedule.Every(TimeSpan.FromMinutes(1)), async ct =>
|
||||
{
|
||||
Interlocked.Increment(ref slow);
|
||||
await release.Task.WaitAsync(ct).ConfigureAwait(false);
|
||||
})
|
||||
{ Beside = true });
|
||||
scheduler.Add(new ScheduledJob("rischio", "Breve", Schedule.Every(TimeSpan.FromMinutes(1)), _ =>
|
||||
{
|
||||
quick++;
|
||||
return Task.CompletedTask;
|
||||
}));
|
||||
for (var minute = 22; minute <= 24; minute++)
|
||||
{
|
||||
clock.Set(new DateTimeOffset(2026, 10, 9, 6, minute, 0, TimeSpan.Zero));
|
||||
await scheduler.RunDueAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WaitUntil(() => Volatile.Read(ref slow) == 1).ConfigureAwait(false);
|
||||
Assert.AreEqual((1, 3), (slow, quick));
|
||||
release.SetResult();
|
||||
await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
|
||||
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, slow);
|
||||
var done = new List<JobRun>();
|
||||
while (runs.TryRead(out var run))
|
||||
{
|
||||
done.Add(run!);
|
||||
}
|
||||
|
||||
Assert.AreEqual(2, done.Count(r => r.Name == "a-notizie" && r.Outcome == JobOutcome.Completed));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task LoopWaitsOnTheInjectedClock()
|
||||
|
||||
@@ -111,6 +111,13 @@ internal sealed class StockRig : IAsyncDisposable
|
||||
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Earnings = earnings };
|
||||
}
|
||||
|
||||
/// <summary>The engine again, with the rules of SPEC 10.5 on single purchases.</summary>
|
||||
public void UseGate(News.IEntryGate gate)
|
||||
{
|
||||
Engine.Dispose();
|
||||
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Gate = gate };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the
|
||||
/// close under its 5-session average, so equity_meanrev buys and sells a few sessions later.
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.News;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The findings of the independent review of Phase 7 (issue #61): names and keywords the text writes in other ways,
|
||||
/// stories that become serious later, stories about two companies, the earnings row, the trusted label.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class NewsReviewTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static InstrumentSpec Stock(string symbol, string name) => new(Venues.Alpaca, symbol, name, AssetClasses.Equity, "USD");
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void KeywordsAfterAnApostropheOrInQuotesAreFound()
|
||||
{
|
||||
Assert.AreEqual(SevereKinds.Investigation, NewsJudge.Severe("Aperta un'indagine sulla banca", null));
|
||||
Assert.AreEqual(SevereKinds.Investigation, NewsJudge.Severe("Le carte dell’inchiesta", null));
|
||||
Assert.AreEqual(SevereKinds.Bankruptcy, NewsJudge.Severe("Il rischio dell'insolvenza", null));
|
||||
Assert.AreEqual(SevereKinds.Fraud, NewsJudge.Severe("Regulator alleges 'fraud' at the lender", null));
|
||||
Assert.IsNull(NewsJudge.Severe("Life hacks for investors", null), "Whole words only, as before.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void NamesAreFoundInTheWaysNewspapersWriteThem()
|
||||
{
|
||||
var linker = NewsLinker.Build(
|
||||
[
|
||||
Stock("AAPL", "Apple Inc. Common Stock"), Stock("GS", "The Goldman Sachs Group, Inc. Common Stock"), Stock("JPM", "JPMorgan Chase & Co. Common Stock"),
|
||||
Stock("MCD", "McDonald's Corporation Common Stock"), Stock("WEN", "Wendy's Company Common Stock"), Stock("META", "Meta Platforms, Inc. Class A Common Stock"),
|
||||
Stock("GOOGL", "Alphabet Inc. Class A Common Stock"), Stock("GOOG", "Alphabet Inc. Class C Capital Stock"), Stock("BA", "Boeing Company (The) Common Stock"),
|
||||
Stock("COIN", "Coinbase Global, Inc. Class A Common Stock"), Stock("SO", "The Southern Company Common Stock"), Stock("NVDA", "NVIDIA Corporation Common Stock"),
|
||||
Stock("TGT", "Target Corporation Common Stock"), Stock("TMC", "The Metals Company Common Stock"), Stock("KO", "Coca-Cola Company (The) Common Stock"),
|
||||
Stock("LLY", "Eli Lilly and Company Common Stock"), Stock("XOM", "Exxon Mobil Corporation Common Stock"),
|
||||
]);
|
||||
string[] Targets(string title) => [.. linker.Link(title, null).Where(l => l.Scope == LinkScopes.Instrument).Select(l => l.Target[7..]).Order(StringComparer.Ordinal)];
|
||||
void Is(string title, params string[] expected) => CollectionAssert.AreEqual(expected, Targets(title), $"{title}: {string.Join(", ", Targets(title))}");
|
||||
|
||||
Is("L'Apple rinvia il nuovo telefono", "AAPL");
|
||||
Is("I conti dell’Apple battono le attese", "AAPL");
|
||||
Is("Un'indagine sull'Apple", "AAPL");
|
||||
Is("Apple’s suppliers rebound", "AAPL");
|
||||
Is("Apple-led rally lifts the market", "AAPL");
|
||||
Is("Nvidia-backed startup raises money", "NVDA");
|
||||
Is("Goldman Sachs cuts jobs", "GS");
|
||||
Is("Goldman Sachs' profit falls", "GS");
|
||||
Is("JPMorgan raises its outlook", "JPM");
|
||||
Is("J.P. Morgan raises its outlook", "JPM");
|
||||
Is("McDonald's recalls a burger", "MCD");
|
||||
Is("McDonald’s recalls a burger", "MCD");
|
||||
Is("Meta faces a fine", "META");
|
||||
Is("Facebook faces a fine", "META");
|
||||
Is("Google loses an appeal", "GOOG", "GOOGL");
|
||||
Is("Alphabet loses an appeal", "GOOG", "GOOGL");
|
||||
Is("Boeing delays a delivery", "BA");
|
||||
Is("Coinbase suspends withdrawals", "COIN");
|
||||
Is("Coca-Cola raises prices", "KO");
|
||||
Is("Eli Lilly halts a trial", "LLY");
|
||||
Is("Exxon Mobil cuts spending", "XOM");
|
||||
Is("Exxon cuts spending", "XOM");
|
||||
|
||||
Is("Wendy Williams talks about her show");
|
||||
Is("McDonald wins the race");
|
||||
Is("Southern states vote");
|
||||
Is("The Southern district opens a case");
|
||||
Is("Metals rally on demand from China");
|
||||
Is("Target-date funds see inflows");
|
||||
Is("why your apple-pie recipe needs more cinnamon");
|
||||
}
|
||||
|
||||
/// <summary>A story that becomes serious with a later article restricts for 72 hours from that article, not from the first one.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheWindowStartsFromTheArticleThatMakesTheStorySerious()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(Now);
|
||||
var linker = NewsLinker.Build([MarketDataStoreTests.Okx("SOL-EUR")]);
|
||||
var (trusted, _) = await SourcesAsync(test.Db, clock).ConfigureAwait(false);
|
||||
var store = new NewsStore(test.Db, clock);
|
||||
await store.IngestAsync(trusted, [Item("Solana exchange Alpha reports an outage of its wallets", "1", Now)], linker, _none).ConfigureAwait(false);
|
||||
clock.Set(Now.AddHours(40));
|
||||
var later = await store.IngestAsync(trusted, [Item("Solana exchange Alpha reports an outage of its wallets, hacked", "2", clock.UtcNow)], linker, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_stories")).ConfigureAwait(false), $"The same story: {later}");
|
||||
|
||||
var desk = new NewsDesk(test.Db, clock);
|
||||
clock.Set(Now.AddHours(111));
|
||||
var active = (await desk.RestrictionsAsync("okx:SOL-EUR", clock.UtcNow, _none).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual(Now.AddHours(40), active.From);
|
||||
Assert.AreEqual(Now.AddHours(112), active.Until);
|
||||
var row = (await new NewsBoard(test.Db, clock).LoadAsync(_none).ConfigureAwait(false)).Rows.Single();
|
||||
Assert.IsTrue(row.Active, row.Action);
|
||||
Assert.IsEmpty(await desk.RestrictionsAsync("okx:SOL-EUR", Now.AddHours(112), _none).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
/// <summary>Two companies told with the same words are two stories: one's trouble never confirms nor restricts the other's.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task StoriesAboutDifferentInstrumentsAreNotOne()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(Now);
|
||||
var linker = NewsLinker.Build([Stock("AAPL", "Apple Inc. Common Stock"), Stock("MSFT", "Microsoft Corporation Common Stock")]);
|
||||
var (trusted, other) = await SourcesAsync(test.Db, clock).ConfigureAwait(false);
|
||||
var store = new NewsStore(test.Db, clock);
|
||||
await store.IngestAsync(trusted, [Item("Apple beats quarterly revenue estimates on cloud demand", "1", Now)], linker, _none).ConfigureAwait(false);
|
||||
await store.IngestAsync(other,
|
||||
[
|
||||
Item("Microsoft beats quarterly revenue estimates on cloud demand", "2", Now),
|
||||
Item("Apple beats quarterly revenue estimates on cloud demand, shares up", "3", Now),
|
||||
Item("Quarterly revenue estimates on cloud demand beats", "4", Now),
|
||||
], linker, _none).ConfigureAwait(false);
|
||||
|
||||
var stories = await test.Db.ReadAsync(s => s.QueryAsync(
|
||||
"SELECT l.target, COUNT(DISTINCT i.id) AS n FROM news_stories st JOIN news_links l ON l.story_id = st.id JOIN news_items i ON i.story_id = st.id " +
|
||||
"WHERE l.scope = 'instrument' GROUP BY st.id, l.target", r => (Target: r.Text("target"), Items: r.Number("n")))).ConfigureAwait(false);
|
||||
Assert.HasCount(2, stories, string.Join(", ", stories));
|
||||
Assert.AreEqual(2, stories.Select(s => s.Target).Distinct().Count());
|
||||
Assert.AreEqual(4L, stories.Sum(s => s.Items), "An article that names no instrument still joins one of the two.");
|
||||
Assert.IsTrue(stories.Single(s => s.Target == "alpaca:AAPL").Items >= 2);
|
||||
}
|
||||
|
||||
/// <summary>The classifier works before the database writer is taken: a slow one never holds back the engine's writes.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheClassifierNeverHoldsTheDatabaseWriter()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(Now);
|
||||
var (trusted, _) = await SourcesAsync(test.Db, clock).ConfigureAwait(false);
|
||||
using var classifier = new BlockedClassifier();
|
||||
var ingest = Task.Run(() => new NewsStore(test.Db, clock).IngestAsync(trusted, [Item("Solana network slows", "1", Now)], NewsLinker.Build([]), _none, classifier));
|
||||
Assert.IsTrue(await classifier.Started.Task.WaitAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false));
|
||||
var write = test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_sources SET failures = 0", _none), _none);
|
||||
var won = await Task.WhenAny(write, Task.Delay(TimeSpan.FromSeconds(3))).ConfigureAwait(false);
|
||||
classifier.Release.Set();
|
||||
await ingest.ConfigureAwait(false);
|
||||
await write.ConfigureAwait(false);
|
||||
Assert.AreSame(write, won, "The write went while the classifier was still reading.");
|
||||
Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items WHERE score IS NOT NULL")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
/// <summary>The label of a source counts for the stories already read; the serious case shown is the first of 10.2.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheTrustedLabelAndTheSeriousCaseFollowTheRules()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(Now);
|
||||
var linker = NewsLinker.Build([MarketDataStoreTests.Okx("SOL-EUR")]);
|
||||
var (_, untrusted) = await SourcesAsync(test.Db, clock).ConfigureAwait(false);
|
||||
var store = new NewsStore(test.Db, clock);
|
||||
await store.IngestAsync(untrusted,
|
||||
[
|
||||
Item("Solana lender Alpha files for bankruptcy after a week of losses", "1", Now),
|
||||
Item("Solana lender Alpha files for bankruptcy after a week of losses, hacked", "2", Now),
|
||||
], linker, _none).ConfigureAwait(false);
|
||||
|
||||
async Task<(bool Trusted, string? Severe)> StoryAsync() => (await test.Db.ReadAsync(s => s.QueryAsync("SELECT trusted, severe FROM news_stories",
|
||||
r => (r.Bool("trusted"), r.TextOrNull("severe")))).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual((false, SevereKinds.Cyberattack), await StoryAsync().ConfigureAwait(false), "The order of 10.2: the cyberattack first, not the alphabet.");
|
||||
await store.SetSourceAsync(untrusted.Id, enabled: true, trusted: true, "test", _none).ConfigureAwait(false);
|
||||
Assert.IsTrue((await StoryAsync().ConfigureAwait(false)).Trusted);
|
||||
Assert.HasCount(1, await new NewsDesk(test.Db, clock).RestrictionsAsync("okx:SOL-EUR", Now, _none).ConfigureAwait(false));
|
||||
await store.SetSourceAsync(untrusted.Id, enabled: true, trusted: false, "test", _none).ConfigureAwait(false);
|
||||
Assert.IsFalse((await StoryAsync().ConfigureAwait(false)).Trusted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A report before the open or during the session frees the next session, one after the close or without a time
|
||||
/// blocks it too (10.5, fourth row); the diary says the row only when it is in force, weekends included.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheEarningsRowStartsAndEndsWithItsSessions()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
// Friday 20 November, 17:00 in New York: the entry is on Monday, so the row reaches Thursday 26.
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 20, 22, 0, 0, TimeSpan.Zero));
|
||||
var catalog = new InstrumentCatalog(test.Db, clock);
|
||||
string[] symbols = ["AAA", "BBB", "CCC", "DDD", "EEE"];
|
||||
await catalog.SyncAsync(Venues.Alpaca, [.. symbols.Select(s => Stock(s, s + " Corp"))], complete: false, _none).ConfigureAwait(false);
|
||||
foreach (var i in await catalog.ListAsync(Venues.Alpaca, _none).ConfigureAwait(false))
|
||||
{
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, '2026-11-16', @i, 1, @now)",
|
||||
_none, ("id", Ids.NewId(clock)), ("u", Universes.Equity), ("i", i.Id), ("now", clock.UtcNow)), _none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
static CalendarEvent Report(string symbol, int day, int hour, string? hint) =>
|
||||
new(CalendarEventKinds.Earnings, "Trimestrale " + symbol, new DateTimeOffset(2026, 11, day, hour, 0, 0, TimeSpan.Zero), false, "test", "earnings:" + symbol)
|
||||
{ Symbol = symbol, TimeHint = hint };
|
||||
await new CalendarEventStore(test.Db, clock).UpsertAsync(
|
||||
[Report("AAA", 26, 21, "amc"), Report("BBB", 27, 12, "bmo"), Report("CCC", 20, 12, "bmo"), Report("DDD", 20, 21, "amc"), Report("EEE", 20, 18, "dmh")], _none).ConfigureAwait(false);
|
||||
|
||||
var desk = new NewsDesk(test.Db, clock);
|
||||
var next = await desk.EarningsAsync(new DateOnly(2026, 11, 20), _none).ConfigureAwait(false);
|
||||
CollectionAssert.AreEquivalent(new[] { "AAA", "BBB", "DDD" }, next.Keys.ToList(), "CCC and EEE published before today's close: the next session is free.");
|
||||
|
||||
await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false);
|
||||
var diary = await NewsRulesTests.DiaryAsync(test.Db).ConfigureAwait(false);
|
||||
Assert.HasCount(1, diary, string.Join(" | ", diary));
|
||||
StringAssert.Contains(diary[0], "niente mean reversion su AAA");
|
||||
|
||||
clock.Set(new DateTimeOffset(2026, 11, 23, 22, 0, 0, TimeSpan.Zero));
|
||||
var off = new NewsWatcher(test.Db, clock) { EarningsActive = _ => Task.FromResult(false) };
|
||||
Assert.AreEqual(0, await off.RunOnceAsync(_none).ConfigureAwait(false), "Without a fresh calendar the strategies ignore the row, and so does the diary.");
|
||||
Assert.AreEqual(1, await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false), "BBB, when its row starts.");
|
||||
}
|
||||
|
||||
/// <summary>A story on a held or candidate stock whose report is near is shown with importance 3 (10.2 point 4), and restricts nothing for that.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AStoryOnAStockWithAReportNearIsShownWithImportanceThree()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var clock = new ManualClock(Now);
|
||||
var (jpm, gs) = (Stock("JPM", "JPMorgan Chase & Co. Common Stock"), Stock("GS", "The Goldman Sachs Group, Inc. Common Stock"));
|
||||
var catalog = new InstrumentCatalog(test.Db, clock);
|
||||
await catalog.SyncAsync(Venues.Alpaca, [jpm, gs], complete: false, _none).ConfigureAwait(false);
|
||||
var id = (await catalog.ListAsync(Venues.Alpaca, _none).ConfigureAwait(false)).Single(i => i.Symbol == "JPM").Id;
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, '2026-11-16', @i, 1, @now)",
|
||||
_none, ("id", Ids.NewId(clock)), ("u", Universes.Equity), ("i", id), ("now", Now)), _none).ConfigureAwait(false);
|
||||
foreach (var (spec, title) in new[] { (jpm, "JPMorgan opens a branch"), (gs, "Goldman opens a branch") })
|
||||
{
|
||||
await NewsRulesTests.StoryAsync(test.Db, clock, spec, title, Now.AddHours(-1), 2, 0.1, "CNBC", trusted: true).ConfigureAwait(false);
|
||||
await new CalendarEventStore(test.Db, clock).UpsertAsync(
|
||||
[new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale", Now.AddDays(2), false, "test", "earnings:" + spec.Symbol) { Symbol = spec.Symbol, TimeHint = "bmo" }], _none)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var rows = (await new NewsBoard(test.Db, clock).LoadAsync(_none).ConfigureAwait(false)).Rows.ToDictionary(r => r.Title);
|
||||
Assert.AreEqual(3, rows["JPMorgan opens a branch"].Importance);
|
||||
Assert.AreEqual("Neutra, evento in arrivo", rows["JPMorgan opens a branch"].Tone);
|
||||
Assert.IsFalse(rows["JPMorgan opens a branch"].Active);
|
||||
Assert.AreEqual(2, rows["Goldman opens a branch"].Importance, "Neither held nor a candidate.");
|
||||
Assert.IsEmpty(await new NewsDesk(test.Db, clock).RestrictionsAsync("alpaca:JPM", Now, _none).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private static FeedItem Item(string title, string id, DateTimeOffset at) =>
|
||||
new(title, "https://www.example.test/" + id) { PublishedAt = at, Language = "en" };
|
||||
|
||||
private static async Task<(NewsSource Trusted, NewsSource Other)> SourcesAsync(Database db, IClock clock)
|
||||
{
|
||||
var store = new NewsStore(db, clock);
|
||||
await store.EnsureDefaultsAsync(_none).ConfigureAwait(false);
|
||||
var sources = await store.ListSourcesAsync(_none).ConfigureAwait(false);
|
||||
return (sources.Single(s => s.Name == "CNBC"), sources.Single(s => s.Name == "Investing.com"));
|
||||
}
|
||||
|
||||
private sealed class BlockedClassifier : IToneClassifier, IDisposable
|
||||
{
|
||||
public TaskCompletionSource<bool> Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public ManualResetEventSlim Release { get; } = new(false);
|
||||
|
||||
public ToneScore Classify(string text)
|
||||
{
|
||||
Started.TrySetResult(true);
|
||||
Release.Wait(TimeSpan.FromSeconds(30));
|
||||
return new ToneScore(0.2, 0.2, 0.6);
|
||||
}
|
||||
|
||||
public void Dispose() => Release.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -306,6 +306,81 @@ public sealed class NewsRulesTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The decision of the day before, made again for the one-step comparison (SPEC 12.3), reads the same earnings: a
|
||||
/// purchase left out for a report is not a difference.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheOneStepComparisonReadsTheSameEarnings()
|
||||
{
|
||||
var day = new DateOnly(2026, 9, 1);
|
||||
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)).ConfigureAwait(false);
|
||||
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).ConfigureAwait(false);
|
||||
var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock);
|
||||
stocks.UseEarnings(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct).ConfigureAwait(false), true));
|
||||
await stocks.SessionAsync(day).ConfigureAwait(false);
|
||||
await stocks.SessionAsync(day.AddDays(1)).ConfigureAwait(false);
|
||||
|
||||
var checks = await stocks.Rig.QueryAsync("SELECT outcome, data FROM decisions WHERE stage = @st", r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")),
|
||||
("st", DecisionStages.OneStep)).ConfigureAwait(false);
|
||||
Assert.AreNotEqual(0, checks.Count);
|
||||
Assert.IsTrue(checks.All(c => c.Outcome == DecisionOutcomes.Same), string.Join(" | ", checks));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A restriction that ends before the purchase is due changes nothing and the diary is silent; one that ends while the
|
||||
/// market is closed or opening sends it five minutes after the open, as every other purchase (5.5).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task OnlyAPurchaseReallyPutOffIsSaidToBe()
|
||||
{
|
||||
var day = new DateOnly(2026, 9, 1);
|
||||
var due = new DateTimeOffset(2026, 9, 2, 13, 35, 0, TimeSpan.Zero);
|
||||
foreach (var (until, expected) in new[] { (due.AddHours(-12), due), (due.AddMinutes(-2), due), (due.AddMinutes(10), due.AddMinutes(10)) })
|
||||
{
|
||||
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)).ConfigureAwait(false);
|
||||
stocks.UseGate(new FixedGate(new EntryHold(CorrectiveReasons.CalendarEvent, until, "Inflazione USA")));
|
||||
await stocks.SessionAsync(day).ConfigureAwait(false);
|
||||
var planned = await stocks.Rig.QueryAsync("SELECT due_at, first_due_at FROM planned_orders WHERE side = 'buy'", r => (Due: r.Moment("due_at"), First: r.MomentOrNull("first_due_at")))
|
||||
.ConfigureAwait(false);
|
||||
Assert.AreEqual(1, planned.Count);
|
||||
Assert.AreEqual(expected, planned[0].Due);
|
||||
Assert.AreEqual(expected > due ? due : null, planned[0].First);
|
||||
var diary = await DiaryAsync(stocks.Rig.Db).ConfigureAwait(false);
|
||||
Assert.AreEqual(expected > due, diary.Any(d => d.StartsWith("Ho rimandato", StringComparison.Ordinal)), string.Join(" | ", diary));
|
||||
if (expected > due)
|
||||
{
|
||||
Assert.IsTrue(diary.Any(d => d.StartsWith("Ho rimandato l'acquisto di BBB a mercoledì 2 settembre alle 15:45.", StringComparison.Ordinal)), string.Join(" | ", diary));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A restriction that ends at night sends a weekly purchase five minutes after the next open, not at the open.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task APurchaseHeldWithTheMarketClosedGoesFiveMinutesAfterTheOpen()
|
||||
{
|
||||
var friday = new DateOnly(2026, 9, 4);
|
||||
await using var stocks = await StockRig.CreateAsync(friday, friday.AddDays(20), StrategyNames.EquityMomentum).ConfigureAwait(false);
|
||||
stocks.UseGate(new FixedGate(new EntryHold(CorrectiveReasons.CalendarEvent, new DateTimeOffset(2026, 9, 7, 23, 0, 0, TimeSpan.Zero), "Inflazione USA")));
|
||||
await stocks.SessionAsync(friday).ConfigureAwait(false);
|
||||
var planned = await stocks.Rig.QueryAsync("SELECT due_at FROM planned_orders WHERE side = 'buy'", r => r.Moment("due_at")).ConfigureAwait(false);
|
||||
Assert.AreNotEqual(0, planned.Count);
|
||||
Assert.IsTrue(planned.All(d => d == new DateTimeOffset(2026, 9, 8, 13, 35, 0, TimeSpan.Zero)), string.Join(", ", planned));
|
||||
Assert.IsTrue((await DiaryAsync(stocks.Rig.Db).ConfigureAwait(false)).Any(d => d.Contains("a martedì 8 settembre alle 15:35.", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
private sealed class FixedGate(EntryHold hold) : IEntryGate
|
||||
{
|
||||
public Task<EntryHold?> HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(at < hold.Until ? hold : null);
|
||||
|
||||
public Task<EntryHold?> KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult<EntryHold?>(null);
|
||||
}
|
||||
|
||||
/// <summary>A story linked to one instrument, with one article from the named publisher.</summary>
|
||||
internal static async Task<Guid> StoryAsync(Database db, IClock clock, InstrumentSpec spec, string title, DateTimeOffset published, int importance, double? score,
|
||||
string publisher, bool trusted, int sources = 1, DateTimeOffset? seen = null)
|
||||
|
||||
@@ -241,6 +241,7 @@ public sealed class NewsTests
|
||||
});
|
||||
http.On(u => u.Host != "search.cnbc.com", _ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
||||
var collector = new NewsCollector(http.Client(), test.Db, clock) { Pause = TimeSpan.Zero };
|
||||
Assert.IsTrue(collector.Job().Beside, "The round of the news never delays the engine and the risk check.");
|
||||
|
||||
await collector.RunOnceAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.HasCount(NewsStore.Defaults.Count, http.Requests, "One request per source.");
|
||||
|
||||
Reference in new issue
Block a user