diff --git a/src/Anubis/Db/Migrations/0008_news.sql b/src/Anubis/Db/Migrations/0008_news.sql index 2a6579f..912dbf6 100644 --- a/src/Anubis/Db/Migrations/0008_news.sql +++ b/src/Anubis/Db/Migrations/0008_news.sql @@ -23,7 +23,9 @@ CREATE TABLE news_sources ( ){strict}; -- One story, told by one or more articles. sources counts the independent publishers (two feeds of the same --- newspaper count once); trusted says whether at least one article came from a trusted source. +-- newspaper count once); trusted says whether at least one article came from a trusted source. score, severe and +-- importance sum up the first judgement of its articles (10.2 point 4): the mean score, a serious case if any +-- article names one, the highest importance. CREATE TABLE news_stories ( id {uuid} PRIMARY KEY, title TEXT NOT NULL, @@ -33,6 +35,9 @@ CREATE TABLE news_stories ( last_seen_at {timestamp} NOT NULL, sources INTEGER NOT NULL, trusted {bool} NOT NULL, + score {float}, + severe TEXT, + importance INTEGER NOT NULL, created_at {timestamp} NOT NULL, updated_at {timestamp} NOT NULL ){strict}; @@ -40,7 +45,8 @@ CREATE TABLE news_stories ( CREATE INDEX news_stories_published ON news_stories (published_at); -- One article. url_key is the address without tracking parameters, fragments and the other differences that do --- not change the article: the same article is never stored twice. +-- not change the article: the same article is never stored twice. score is the tone of the local classifier, from +-- -1 to +1, for English titles only (null otherwise); severe the serious case found by the keywords; importance 1 to 4. CREATE TABLE news_items ( id {uuid} PRIMARY KEY, story_id {uuid} NOT NULL REFERENCES news_stories (id), @@ -52,6 +58,9 @@ CREATE TABLE news_items ( summary TEXT, language TEXT NOT NULL, published_at {timestamp} NOT NULL, + score {float}, + severe TEXT, + importance INTEGER NOT NULL, created_at {timestamp} NOT NULL ){strict}; diff --git a/src/Anubis/News/Judgement.cs b/src/Anubis/News/Judgement.cs new file mode 100644 index 0000000..63e8137 --- /dev/null +++ b/src/Anubis/News/Judgement.cs @@ -0,0 +1,129 @@ +using System.Text.RegularExpressions; + +namespace Anubis.News; + +/// The serious cases of SPEC 10.2 point 4, found by keywords in English and in Italian. +public static class SevereKinds +{ + public const string Cyberattack = "cyberattack"; + public const string Suspension = "suspension"; + public const string Fraud = "fraud"; + public const string Bankruptcy = "bankruptcy"; + public const string Investigation = "investigation"; + public const string Delisting = "delisting"; +} + +/// The five grades of tone of SPEC 10.2 point 4. +public enum Tone +{ + Negative = -2, + SlightlyNegative = -1, + Neutral = 0, + SlightlyPositive = 1, + Positive = 2, +} + +/// What the local classifier says of an English text: the probabilities of its three classes. +public sealed record ToneScore(double Positive, double Negative, double Neutral) +{ + /// The score of 10.2: probability of positive minus probability of negative, from −1 to +1. + public double Score => Positive - Negative; +} + +/// The local classifier of SPEC 4.5. It reads only English; for other texts the caller does not ask. +public interface IToneClassifier +{ + ToneScore Classify(string text); +} + +/// The first judgement of an article: tone, serious case and importance, all without a language model. +public sealed record NewsJudgement(double? Score, string? Severe, int Importance) +{ + public Tone? Tone => Score is { } s ? NewsJudge.Grade(s) : null; +} + +/// +/// The first judgement of SPEC 10.2 point 4, local and free. The tone comes from the classifier for English texts; +/// the serious cases from keywords in two languages, so an Italian title of a fraud is still a serious case. +/// Importance: 4 to the serious cases, 3 to a negative article (score up to −0.6), 2 to the others linked to an +/// instrument, 1 to the rest. The 5 is given only by the language model (#58); a calendar event (3) arrives with #59. +/// +public static partial class NewsJudge +{ + // Lower case, words separated by single spaces. A phrase matches whole words only: "hacked" is not "hack". + private static readonly (string Kind, string[] Phrases)[] Keywords = + [ + (SevereKinds.Cyberattack, + [ + "hack", "hacked", "hacker", "hackers", "hacking", "cyberattack", "cyber attack", "cyberattacks", "ransomware", "data breach", "security breach", + "exploit", "exploited", "drained", "attacco informatico", "attacchi informatici", "attacco hacker", "violazione dei dati", + ]), + (SevereKinds.Suspension, + [ + "trading halt", "trading halted", "halts trading", "halted trading", "suspends trading", "trading suspended", "suspended from trading", + "halts withdrawals", "halted withdrawals", "suspends withdrawals", "withdrawals halted", "withdrawals suspended", "pauses withdrawals", + "sospeso dalle negoziazioni", "sospensione delle negoziazioni", "sospende le negoziazioni", "titolo sospeso", "sospende i prelievi", + "sospensione dei prelievi", "blocca i prelievi", + ]), + (SevereKinds.Fraud, + [ + "fraud", "frauds", "fraudulent", "ponzi", "embezzlement", "accounting irregularities", "frode", "frodi", "truffa", "falso in bilancio", + "irregolarità contabili", + ]), + (SevereKinds.Bankruptcy, + [ + "bankruptcy", "bankrupt", "chapter 11", "insolvency", "insolvent", "files for bankruptcy", "fallimento", "bancarotta", "insolvenza", + "insolvente", "concordato preventivo", "amministrazione straordinaria", + ]), + (SevereKinds.Investigation, + [ + "investigation", "investigations", "probe", "probes", "subpoena", "subpoenaed", "indicted", "indictment", "charged with", "sec charges", + "raided", "indagine", "indagini", "indagato", "indagati", "inchiesta", "perquisizione", "perquisizioni", + ]), + (SevereKinds.Delisting, + [ + "delist", "delisted", "delisting", "delistings", "revoca dalla quotazione", "esclusione dalle negoziazioni", + ]), + ]; + + /// The grade of a score, with the bounds of 10.2: up to −0.6, −0.2, +0.2, +0.6, then positive. + public static Tone Grade(double score) => score switch + { + <= -0.6 => Tone.Negative, + <= -0.2 => Tone.SlightlyNegative, + <= 0.2 => Tone.Neutral, + <= 0.6 => Tone.SlightlyPositive, + _ => Tone.Positive, + }; + + /// The first serious case named by the text, in the order of 10.2, or null. + public static string? Severe(string title, string? summary) + { + var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant().Replace('’', '\''), " "), " ") + " "; + foreach (var (kind, phrases) in Keywords) + { + if (phrases.Any(p => text.Contains(" " + p + " ", StringComparison.Ordinal))) + { + return kind; + } + } + + return null; + } + + /// The judgement of one article. The classifier is asked only for English and only when it exists. + public static NewsJudgement Judge(string title, string? summary, string language, bool linkedToInstrument, IToneClassifier? classifier) + { + ArgumentNullException.ThrowIfNull(title); + double? score = classifier is not null && language == "en" ? Math.Clamp(classifier.Classify(title).Score, -1, 1) : null; + var severe = Severe(title, summary); + var importance = severe is not null ? 4 : score <= -0.6 ? 3 : linkedToInstrument ? 2 : 1; + return new NewsJudgement(score, severe, importance); + } + + [GeneratedRegex(@"[^\p{L}\p{N}']+")] + private static partial Regex NonWord(); + + [GeneratedRegex(@"\s+")] + private static partial Regex Spaces(); +} diff --git a/src/Anubis/News/NewsCollector.cs b/src/Anubis/News/NewsCollector.cs index a8bdb12..0e54422 100644 --- a/src/Anubis/News/NewsCollector.cs +++ b/src/Anubis/News/NewsCollector.cs @@ -35,6 +35,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c public NewsStore Store => _store; + /// The local classifier of SPEC 4.5; without it the tone is unknown and only the keywords judge. + public IToneClassifier? Classifier { get; init; } + public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval }; /// One round over the sources that are due. @@ -107,7 +110,7 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c var content = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false); var items = FeedParser.Parse(content); - var result = await _store.IngestAsync(source, items, dictionary, cancellationToken).ConfigureAwait(false); + var result = await _store.IngestAsync(source, items, dictionary, cancellationToken, Classifier).ConfigureAwait(false); await _store.RecordCheckAsync(source, ok: true, response.Headers.ETag?.ToString(), response.Content.Headers.LastModified?.ToString("R"), null, cancellationToken) .ConfigureAwait(false); if (result.Added > 0) diff --git a/src/Anubis/News/NewsStore.cs b/src/Anubis/News/NewsStore.cs index 754a887..1f9bcb3 100644 --- a/src/Anubis/News/NewsStore.cs +++ b/src/Anubis/News/NewsStore.cs @@ -104,7 +104,8 @@ public sealed class NewsStore(Database db, IClock clock) /// story whose title it retells, within two days, or starts a new one. The story counts again its independent /// publishers and whether a trusted source told it. /// - public async Task IngestAsync(NewsSource source, IReadOnlyList items, NewsLinker dictionary, CancellationToken cancellationToken) + public async Task IngestAsync( + NewsSource source, IReadOnlyList items, NewsLinker dictionary, CancellationToken cancellationToken, IToneClassifier? classifier = null) { ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(items); @@ -140,20 +141,23 @@ public sealed class NewsStore(Database db, IClock clock) { story = Ids.NewId(clock); await s.ExecuteAsync( - "INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, created_at, updated_at) " + - "VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, @now, @now)", cancellationToken, + "INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, importance, created_at, updated_at) " + + "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)); } + 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, created_at) " + - "VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @now)", cancellationToken, + "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, ("id", Ids.NewId(clock)), ("story", story), ("source", source.Id), ("url", item.Link), ("key", key), ("pub", NewsMatching.Publisher(item.Link)), - ("title", item.Title), ("summary", item.Summary), ("lang", item.Language ?? Languages.Guess(item.Title + " " + item.Summary)), ("p", published), - ("now", now)).ConfigureAwait(false); - foreach (var link in dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic)) + ("title", item.Title), ("summary", item.Summary), ("lang", language), ("p", published), ("score", judgement.Score), ("severe", judgement.Severe), + ("importance", judgement.Importance), ("now", now)).ConfigureAwait(false); + foreach (var link in links) { await s.ExecuteAsync( "INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @story, @scope, @target, @via, @now) " + @@ -170,7 +174,10 @@ 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 = (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, " + + "score = (SELECT AVG(score) FROM news_items WHERE story_id = @id), " + + "severe = (SELECT MIN(severe) FROM news_items WHERE story_id = @id), " + + "importance = (SELECT MAX(importance) FROM news_items WHERE story_id = @id) " + "WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false); } diff --git a/tests/Anubis.Tests/NewsTests.cs b/tests/Anubis.Tests/NewsTests.cs index aaf5288..ceba2f4 100644 --- a/tests/Anubis.Tests/NewsTests.cs +++ b/tests/Anubis.Tests/NewsTests.cs @@ -269,4 +269,103 @@ public sealed class NewsTests Assert.IsFalse(NewsCollector.Due(never, Now.AddMinutes(59))); Assert.IsTrue(NewsCollector.Due(never, Now.AddHours(1)), "Never more than an hour between two tries."); } + + [TestMethod] + public void TheToneHasFiveGradesWithTheBoundsOfTheSpecification() + { + Assert.AreEqual(Tone.Negative, NewsJudge.Grade(-1)); + Assert.AreEqual(Tone.Negative, NewsJudge.Grade(-0.6)); + Assert.AreEqual(Tone.SlightlyNegative, NewsJudge.Grade(-0.59)); + Assert.AreEqual(Tone.SlightlyNegative, NewsJudge.Grade(-0.2)); + Assert.AreEqual(Tone.Neutral, NewsJudge.Grade(-0.19)); + Assert.AreEqual(Tone.Neutral, NewsJudge.Grade(0.2)); + Assert.AreEqual(Tone.SlightlyPositive, NewsJudge.Grade(0.21)); + Assert.AreEqual(Tone.SlightlyPositive, NewsJudge.Grade(0.6)); + Assert.AreEqual(Tone.Positive, NewsJudge.Grade(0.61)); + Assert.AreEqual(0.5, new ToneScore(0.7, 0.2, 0.1).Score, 1e-9); + } + + [TestMethod] + public void SeriousCasesAreFoundInBothLanguagesAndOnlyAsWholeWords() + { + Assert.AreEqual(SevereKinds.Cyberattack, NewsJudge.Severe("Exchange halts withdrawals after hack, Solana tokens drained", null)); + Assert.AreEqual(SevereKinds.Suspension, NewsJudge.Severe("Exchange halts withdrawals for maintenance", null)); + Assert.AreEqual(SevereKinds.Fraud, NewsJudge.Severe("SEC charges founder with securities fraud", null)); + Assert.AreEqual(SevereKinds.Bankruptcy, NewsJudge.Severe("Retailer files for Chapter 11 protection", null)); + Assert.AreEqual(SevereKinds.Investigation, NewsJudge.Severe("Regulators open a probe into the bank", null)); + Assert.AreEqual(SevereKinds.Delisting, NewsJudge.Severe("Exchange to delist three tokens", null)); + Assert.AreEqual(SevereKinds.Suspension, NewsJudge.Severe("Il titolo sospeso dalle negoziazioni", null)); + Assert.AreEqual(SevereKinds.Fraud, NewsJudge.Severe("Inchiesta per frode sulla società", null), "Two cases: the first in the order of 10.2."); + Assert.AreEqual(SevereKinds.Cyberattack, NewsJudge.Severe("Banca colpita da un attacco informatico", null)); + Assert.AreEqual(SevereKinds.Bankruptcy, NewsJudge.Severe("Shares fall", "The company warned of a possible bankruptcy."), "The summary counts too."); + Assert.IsNull(NewsJudge.Severe("Students win the bank's hackathon", null)); + Assert.IsNull(NewsJudge.Severe("Bitcoin drifts below $90,000 as traders await U.S. data", null)); + Assert.IsNull(NewsJudge.Severe("Borse europee in rialzo, Piazza Affari guida", null)); + } + + [TestMethod] + public void ImportanceComesFromTheSeriousCasesTheToneAndTheLinks() + { + var classifier = new WordClassifier(); + Assert.AreEqual(new NewsJudgement(null, SevereKinds.Fraud, 4), NewsJudge.Judge("Inchiesta per frode", null, "it", true, classifier)); + Assert.AreEqual(0, classifier.Calls, "Italian titles are never given to the classifier."); + Assert.AreEqual(new NewsJudgement(-0.8125, null, 3), NewsJudge.Judge("Nvidia slides", null, "en", false, classifier)); + Assert.AreEqual(new NewsJudgement(0.75, null, 2), NewsJudge.Judge("Apple shares jump", null, "en", true, classifier)); + Assert.AreEqual(new NewsJudgement(0, null, 1), NewsJudge.Judge("Markets wait", null, "en", false, classifier)); + Assert.AreEqual(new NewsJudgement(-0.8125, SevereKinds.Cyberattack, 4), NewsJudge.Judge("Tokens drained in a hack", null, "en", true, classifier)); + Assert.AreEqual(new NewsJudgement(null, null, 2), NewsJudge.Judge("Nvidia slides", null, "en", true, null), "Without the classifier the tone is unknown."); + Assert.AreEqual(Tone.Negative, NewsJudge.Judge("Nvidia slides", null, "en", false, classifier).Tone); + Assert.IsNull(NewsJudge.Judge("Nvidia slides", null, "en", false, null).Tone); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task EveryArticleKeepsItsJudgementAndTheStorySumsThemUp() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + foreach (var venue in new[] { Venues.Alpaca, Venues.Okx }) + { + await new InstrumentCatalog(test.Db, clock).SyncAsync(venue, [.. Instruments.Where(i => i.Venue == venue)], complete: false, CancellationToken.None) + .ConfigureAwait(false); + } + + var store = new NewsStore(test.Db, clock); + await store.EnsureDefaultsAsync(CancellationToken.None).ConfigureAwait(false); + var sources = (await store.ListSourcesAsync(CancellationToken.None).ConfigureAwait(false)).ToDictionary(s => s.Name); + var linker = await new NewsCollector(new HttpClient(), test.Db, clock).DictionaryAsync(CancellationToken.None).ConfigureAwait(false); + var classifier = new WordClassifier(); + foreach (var (file, source) in new[] { ("cnbc", "CNBC"), ("marketwatch", "MarketWatch"), ("coindesk", "CoinDesk"), ("sole24ore", "Il Sole 24 Ore") }) + { + await store.IngestAsync(sources[source], FeedParser.Parse(Fixture.Bytes($"news/{file}.xml")), linker, CancellationToken.None, classifier).ConfigureAwait(false); + } + + var stories = await test.Db.ReadAsync(s => s.QueryAsync("SELECT title, score, severe, importance FROM news_stories", + r => (Title: r.Text("title"), Score: r.IsNull("score") ? (double?)null : r.Measure("score"), Severe: r.TextOrNull("severe"), Importance: (int)r.Number("importance")))) + .ConfigureAwait(false); + (string Title, double? Score, string? Severe, int Importance) Story(string start) => stories.Single(s => s.Title.StartsWith(start, StringComparison.Ordinal)); + + Assert.AreEqual((0.75, (string?)null, 2), (Story("Apple shares jump").Score, Story("Apple shares jump").Severe, Story("Apple shares jump").Importance)); + Assert.AreEqual(3, Story("Target cuts").Importance, "Negative, though linked to nothing."); + Assert.AreEqual(3, Story("Fire at a chip plant").Importance); + Assert.AreEqual((SevereKinds.Cyberattack, 4), (Story("Exchange halts withdrawals").Severe, Story("Exchange halts withdrawals").Importance)); + Assert.AreEqual(((double?)null, 2), (Story("Il Bitcoin scende").Score, Story("Il Bitcoin scende").Importance), "Italian: no tone, linked to Bitcoin."); + Assert.AreEqual((0d, 1), (Story("Weekly wrap").Score ?? double.NaN, Story("Weekly wrap").Importance)); + Assert.AreEqual(1, Story("Borse europee").Importance); + } + + /// A stand-in for the classifier of 4.5: a few words decide the tone. + private sealed class WordClassifier : IToneClassifier + { + public int Calls { get; private set; } + + public ToneScore Classify(string text) + { + Calls++; + var lower = text.ToLowerInvariant(); + return new[] { "slides", "cuts", "drained", "hits" }.Any(lower.Contains) ? new ToneScore(0.0625, 0.875, 0.0625) + : new[] { "jump", "gains" }.Any(lower.Contains) ? new ToneScore(0.875, 0.125, 0) + : new ToneScore(0.125, 0.125, 0.75); + } + } }