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

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:
Alby96andClaude Opus 5.5 committed 2026-12-01 09:49:14 +01:00
1 parent 61878c2023
commit a3ff8ea6b7
22 files changed
+862 -123

No files matched your search

+59 -17
View File
@@ -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);
}
}
+3
View File
@@ -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);
+1 -1
View File
@@ -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),
};
}
+3 -2
View File
@@ -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
View File
@@ -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();
+13 -6
View File
@@ -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)
+1 -1
View File
@@ -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
View File
@@ -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}"),
+14 -3
View File
@@ -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));
}
}
+68 -20
View File
@@ -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);
+6 -2
View File
@@ -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}.";
+53 -17
View File
@@ -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);
}