Files
Anubis/tests/Anubis.Tests/NewsReviewTests.cs
T
Alby96andClaude Opus 5.5 a3ff8ea6b7
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
Fix what the independent review of Phase 7 found and close the phase (refs #61)
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>
2026-12-01 09:49:14 +01:00

274 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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();
}
}