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
@@ -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