Fase 11 — Decisioni solo matematiche (#186)
ci / test (postgres) (push) Successful in 7m36s
ci / test (sqlite) (push) Successful in 6m41s
ci / image (push) Successful in 1m49s

News, the economic calendar and earnings dates no longer change any decision (ADR 0023, choices in ADR 0027). The outside rules are measured in the shadow; a switch in the settings turns them back on.

refs #116, refs #117

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #186.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-12-04 09:14:11 +01:00
1 parent ed22d1c8b5
commit 93cdf7850d
47 files changed
+1743 -169

No files matched your search

+7 -1
View File
@@ -387,6 +387,7 @@ internal sealed partial class AnubisHost(
Guard?.Step("servizi");
var key = Config.SecretKey.GetOrCreateKey();
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
await News.ExternalRules.SettleAsync(_db, clock, cancellationToken).ConfigureAwait(false);
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
var access = new AccessStore(_db, clock, secrets, PasswordIterations, _accessGuards);
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
@@ -439,7 +440,12 @@ internal sealed partial class AnubisHost(
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
if (_lab is { } laboratory && _trading is { } running && _market is { } market)
{
var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger);
async Task<bool> HasAsync(string secret, CancellationToken ct) => (await secrets.StatusAsync(secret, ct).ConfigureAwait(false)).IsSet;
var review = new QuarterlyReview(_db, clock, laboratory, running.Stages, running.Learning, Config.Data.Research, market.PrepareReviewHistoryAsync, logger)
{
Keys = async ct => (await HasAsync("ALPACA_API_KEY_DEMO", ct).ConfigureAwait(false) && await HasAsync("ALPACA_API_SECRET_DEMO", ct).ConfigureAwait(false),
await HasAsync("FINNHUB_API_KEY", ct).ConfigureAwait(false)),
};
laboratory.ReviewTrialEnded = review.ConcludeAsync;
running.QuarterlyReview = review.RunIfDueAsync;
}
+2
View File
@@ -235,6 +235,8 @@ h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; }
.notice-loss { background: var(--loss-bg); color: var(--loss); }
.notice-gain { background: var(--gain-bg); color: var(--gain); }
.notice-attention { background: var(--attention-bg); color: var(--attention); }
.news-archive { margin-bottom: 16px; background: var(--info-bg); color: var(--text); }
.rules-off { opacity: 0.6; }
.badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 8px; font-size: 18px; line-height: 24px; font-weight: 600; }
.badge-gain { background: var(--gain-bg); color: var(--gain); }
.badge-loss { background: var(--loss-bg); color: var(--loss); }
@@ -23,7 +23,7 @@ else if (Errore is not null)
<section class="panel head-block learning-head" aria-labelledby="stato">
<div class="half learning-state">
<span class="state-badge @(s.State is LearningStates.Aside or LearningStates.Manual ? "warn" : s.State == LearningStates.Active ? "on" : null)"><Icon Name="@BadgeIcon(s.State)" Size="16" />@Badge(s.State)</span>
<span class="state-badge @(s.State is LearningStates.Aside or LearningStates.Manual or LearningStates.Rules ? "warn" : s.State == LearningStates.Active ? "on" : null)"><Icon Name="@BadgeIcon(s.State)" Size="16" />@Badge(s.State)</span>
<h2 id="stato">@v.Title</h2>
<p class="learning-text">@v.Text</p>
@if (s.State != LearningStates.None)
@@ -285,6 +285,7 @@ else if (Errore is not null)
LearningStates.None => "Non ancora partito",
LearningStates.Active => "Attivo",
LearningStates.Aside => "Messo da parte",
LearningStates.Rules => "Messo da parte",
LearningStates.Manual => "Messo da parte da te",
_ => "In osservazione",
};
@@ -294,6 +295,7 @@ else if (Errore is not null)
LearningStates.None => "clock",
LearningStates.Active => "check",
LearningStates.Aside => "alert",
LearningStates.Rules => "pause",
LearningStates.Manual => "pause",
_ => "eye",
};
@@ -396,13 +396,53 @@
<section class="panel" id="notizie">
<h2>Notizie e calendario</h2>
<p class="hint">Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.</p>
@if (_measured)
{
<p class="hint">Notizie, calendario e trimestrali non cambiano nessuna decisione: le decisioni guardano solo i numeri del mercato. Per ogni regola registro solo cosa avrebbe fatto, e il Laboratorio mostra quanto avrebbe reso.</p>
}
else
{
<p class="hint">Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.</p>
}
<h3>Regole</h3>
@if (_rules is { } switchValue)
{
var key = Anubis.News.ExternalRules.Setting.Key;
var toMeasured = !_measured;
<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
<label for="@key">@Anubis.News.ExternalRules.Setting.Label</label>
<select id="@key" name="valore" disabled="@(switchValue.ReadOnly || Shell.IsDemo)" data-autosubmit="@(_anyLive && toMeasured ? null : "")">
<option value="@Anubis.News.ExternalRules.Measured" selected="@_measured">Solo misurate</option>
<option value="@Anubis.News.ExternalRules.Active" selected="@(!_measured)">Attive</option>
</select>
@if (switchValue.ReadOnly)
{
<span class="hint">Fissato da @switchValue.Source: si cambia lì.</span>
}
else if (!Shell.IsDemo && _anyLive && toMeasured)
{
<p class="note">Una strategia usa soldi veri: per misurare soltanto le regole servono la frase e la password.</p>
<label>Scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
<button class="btn btn-small" type="submit">Salva</button>
}
else if (!Shell.IsDemo)
{
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
}
</form>
<p class="hint">@(_measured
? "Le righe qui sotto valgono quando le regole sono attive. Per riaccenderne una sola, spegni le altre e poi scegli «Attive». Il bot non le riaccende mai da solo."
: "Ogni cambio scrive una riga nel diario.")</p>
}
@foreach (var rule in _newsRules)
{
var definition = SettingsStore.Definition(rule.Key);
<form method="post" action="/azioni/impostazioni/@rule.Key" class="form-inline">
<form method="post" action="/azioni/impostazioni/@rule.Key" class="form-inline @(_measured ? "rules-off" : null)">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
<label for="@rule.Key">@definition.Label</label>
@@ -464,7 +504,7 @@
}
<h3>Modello linguistico</h3>
<p class="hint">Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.</p>
<p class="hint">Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: @(_measured ? "con le regole solo misurate la sua rilettura entra nella misura in ombra, come farebbe se fossero attive" : "può aggiungere una restrizione, mai toglierla"), e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.</p>
@DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico")
@ModelSetting(Anubis.News.NewsModelSettings.Provider.Key, "servizio", "Servizio", null)
@ModelSetting(Anubis.News.NewsModelSettings.Model.Key, "modello", "Modello", null)
@@ -475,7 +515,7 @@
<p class="note">I prezzi in dollari li conto come euro: la spesa calcolata è un po' più alta di quella vera, mai più bassa. Il tetto vale da mezzanotte a mezzanotte; prima di ogni richiesta controllo che anche il caso peggiore ci stia dentro.</p>
<h3>Calendario</h3>
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali: @(_measured ? "la misura in ombra del filtro della mean reversion non parte" : "la mean reversion non usa il suo filtro"); senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
@DataKey("FINNHUB_API_KEY", "Chiave di Finnhub")
@DataKey("FRED_API_KEY", "Chiave di FRED")
<h3>Settori delle società</h3>
@@ -666,6 +706,10 @@
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
private readonly List<SettingValue> _newsRules = [];
private SettingValue? _rules;
private bool _measured;
private readonly List<SettingValue> _model = [];
private int? _undoTo;
private readonly Dictionary<string, SettingValue> _llm = [];
@@ -702,6 +746,8 @@
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
_taxMethod = await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct);
_taxChoices = await Anubis.Trading.TaxExport.ChoicesAsync(services.Db, ct);
_rules = await services.Settings.GetAsync(Anubis.News.ExternalRules.Setting.Key, ct);
_measured = _rules.Value == Anubis.News.ExternalRules.Measured;
foreach (var rule in Anubis.News.NewsRuleSettings.All)
{
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
@@ -941,6 +987,8 @@
"fifo" => "Primo comprato, primo venduto (FIFO)",
"EUR" => "Euro (EUR)",
"USD" => "Dollaro (USD)",
Anubis.News.ExternalRules.Measured => "Solo misurate",
Anubis.News.ExternalRules.Active => "Attive",
"active" => "Attivo",
"paused" => "In pausa",
"stopped" => "Fermo",
@@ -219,6 +219,14 @@
<p class="note">L'effetto è una quota di quanto il segnale avrebbe investito: +0,10% vuol dire un euro in più ogni mille. L'intervallo contiene il valore vero 95 volte su 100.</p>
</section>
<section class="panel" aria-labelledby="regole-ombra">
<h2 id="regole-ombra">Regole esterne misurate in ombra</h2>
<p class="hint">@(_measured
? "Notizie, calendario e trimestrali non cambiano nessuna decisione. Per ogni ingresso scrivo cosa avrebbe fatto ciascuna regola, e quando l'operazione si chiude misuro quanto avrebbe reso."
: "Le regole sono attive: agiscono sugli acquisti e il bilancio delle restrizioni della revisione trimestrale ne misura l'effetto. Qui restano i casi misurati quando erano solo misurate.")</p>
<ShadowRulesTable Rules="_rules" />
</section>
<section class="panel" aria-labelledby="stime">
<h2 id="stime">Stime di costo da confermare</h2>
<p class="hint">Scostamento contato da simulatore e backtest: @string.Join("; ", SlippageTiers.All.Select(t => SlippageTiers.Label(t) + " " + Bp(_table.Of(t)))). Ogni mese si confronta con le esecuzioni ottenute dai broker, mai con quelle del simulatore. Una stima sale da sola; scende solo se viene da soldi veri e la confermi tu.</p>
@@ -283,6 +291,10 @@
private IReadOnlyList<string> _research = [];
private IReadOnlyList<CostEstimate> _costs = [];
private IReadOnlyList<Anubis.Learning.ImprovementView> _improvements = [];
private IReadOnlyList<Anubis.Learning.ShadowRuleView> _rules = [];
private bool _measured;
private IReadOnlyList<Review> _reviews = [];
private DateOnly _nextReview;
private bool _anyLive;
@@ -312,6 +324,8 @@
async Task<bool> HasAsync(string secret) => (await services.Secrets.StatusAsync(secret, ct)).IsSet;
_improvements = await learning.Shadow.LoadAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync(Edgar.ContactSecret),
(await learning.BaseRatesAsync(ct)).ContainsKey(StrategyNames.EquityMeanrev) && champion?.Model?.Strategies.Contains(StrategyNames.EquityMeanrev) == true, ct);
_rules = await learning.Shadow.LoadRulesAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync("FINNHUB_API_KEY"), ct);
_measured = await learning.RulesMeasuredAsync(ct);
_reviews = await QuarterlyReview.ListAsync(services.Db, ct);
_nextReview = QuarterlyReview.NextDue(Zones.DayIn(Clock.UtcNow, Zones.Rome), await QuarterlyReview.LastQuarterAsync(services.Db, Clock, ct));
_running = _trials.Any(t => !t.IsFinished);
@@ -17,14 +17,18 @@
};
var shown = _all ? rows : rows.Take(Shown).ToList();
}
@if (v.Measured)
{
<p class="notice news-archive" role="note"><Icon Name="info" Size="16" /><span>Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola.</span></p>
}
<p class="lead page-lead">@Lead(v)</p>
<div class="news-columns">
<section class="panel news-panel" aria-labelledby="letto">
<div class="panel-head">
<h2 id="letto">Cosa ho letto e cosa ne ho fatto</h2>
<h2 id="letto">@(v.Measured ? "Cosa ho letto e cosa avrebbe fatto ogni regola" : "Cosa ho letto e cosa ne ho fatto")</h2>
<nav class="segmented" aria-label="Filtro delle notizie">
<a class="@(_filter == "effetto" ? "on" : null)" href="/notizie?filtro=effetto" aria-current="@(_filter == "effetto" ? "page" : null)">Con effetto, @v.Board.Active</a>
<a class="@(_filter == "effetto" ? "on" : null)" href="/notizie?filtro=effetto" aria-current="@(_filter == "effetto" ? "page" : null)">@(v.Measured ? "Con una regola" : "Con effetto"), @v.Board.Active</a>
<a class="@(_filter == "posizioni" ? "on" : null)" href="/notizie?filtro=posizioni" aria-current="@(_filter == "posizioni" ? "page" : null)">Sulle tue posizioni, @v.Board.OnPositions</a>
<a class="@(_filter == "tutte" ? "on" : null)" href="/notizie?filtro=tutte" aria-current="@(_filter == "tutte" ? "page" : null)">Tutte, @v.Board.Read</a>
</nav>
@@ -74,7 +78,11 @@
Importanza @n.Importance su 5
</span>
</p>
@if (n.Active)
@if (v.Measured)
{
<p class="news-action"><strong>Cosa avrebbe fatto la regola:</strong> @Inline(n.Action)</p>
}
else if (n.Active)
{
<p class="notice notice-attention"><Icon Name="alert" Size="16" /><span><strong>Cosa ho fatto:</strong> @Inline(n.Action)</span></p>
}
@@ -124,7 +132,7 @@
</li>
}
</ul>
<p class="note gauges-note">Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.</p>
<p class="note gauges-note">@(v.Measured ? "Paura e avidità è solo registrato: non entra più nel modello. Il nervosismo di Wall Street e le scommesse a leva restano indizi del modello, come numeri del mercato. Da soli non fanno comprare né vendere." : "Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.")</p>
<p class="hint">@Anubis.Data.FearGreed.Attribution.</p>
</section>
@@ -211,17 +219,21 @@
private static string Lead(NewsView v)
{
var read = v.Board.Read == 1 ? "1 notizia letta" : $"{v.Board.Read} notizie lette";
var active = v.Board.Active switch
var active = (v.Measured, v.Board.Active) switch
{
0 => "nessuna con un effetto in corso",
1 => "1 con un effetto in corso",
var n => $"{n} con un effetto in corso",
(true, 0) => "nessuna su cui una regola avrebbe agito",
(true, 1) => "1 su cui una regola avrebbe agito",
(true, var n) => $"{n} su cui una regola avrebbe agito",
(_, 0) => "nessuna con un effetto in corso",
(_, 1) => "1 con un effetto in corso",
(_, var n) => $"{n} con un effetto in corso",
};
return $"{read} nelle ultime 24 ore, {active}.";
}
private string Empty(NewsView v) => _filter switch
{
"effetto" when v.Measured => "Nessuna regola avrebbe agito: compro e vendo come dicono le strategie, come sempre.",
"effetto" => "Nessuna notizia ha un effetto in corso: compro e vendo come dicono le strategie.",
"posizioni" => "Nessuna notizia sulle tue posizioni nelle ultime 24 ore.",
_ when !v.Collecting && !Shell.IsDemo => "Non leggo ancora notizie: la raccolta parte con i dati di mercato. Le fonti si scelgono nelle impostazioni.",
@@ -137,17 +137,21 @@
</ul>
}
<dl class="block-list">
<dt>Prossimo blocco in programma</dt>
<dt>@(v.RulesMeasured ? "Prossimo dato macro (solo registrato)" : "Prossimo blocco in programma")</dt>
@if (v.NextCalendarBlock is { } next)
{
<dd><strong>@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")</strong><span>@next.Title: in quell'ora non apro posizioni.</span></dd>
<dd><strong>@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")</strong><span>@next.Title: @(v.RulesMeasured ? "con le regole attive in quell'ora non aprirei posizioni; ora le apro come sempre." : "in quell'ora non apro posizioni.")</span></dd>
}
else
{
<dd><span>Nessun dato economico importante nei prossimi 14 giorni.</span></dd>
}
<dt>Ultimo blocco scattato</dt>
@if (v.LastCalendarBlock is { } last)
@if (v.RulesMeasured)
{
<dd><span>Nessun blocco: le regole delle notizie e del calendario sono solo misurate.</span></dd>
}
else if (v.LastCalendarBlock is { } last)
{
<dd><strong>@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")</strong><span>@last.Title.</span></dd>
}
@@ -67,7 +67,7 @@ else
}
<h3>Bilancio delle restrizioni</h3>
<p class="hint">Acquisti fermati da notizie e calendario e come sarebbero finiti, dal @LabText.Day(r.RestrictionsFrom) e da quando Anubis è in funzione. La riga delle trimestrali non è misurata: agisce dentro la strategia, prima del segnale.</p>
<p class="hint">Acquisti fermati da notizie e calendario e come sarebbero finiti, dal @LabText.Day(r.RestrictionsFrom) e da quando Anubis è in funzione: la storia del periodo in cui le regole agivano. Le trimestrali sono misurate nella tabella delle regole in ombra, qui sotto.</p>
@if (restrictions.Count == 0)
{
<p class="note">Nessun acquisto fermato finora.</p>
@@ -102,3 +102,35 @@ else
[Parameter, EditorRequired]
public Review Review { get; set; } = null!;
}
<h3>Regole esterne misurate in ombra</h3>
@if (r.ShadowRules.Count == 0)
{
<p class="note">Questa revisione è di prima della misura in ombra (ADR 0023).</p>
}
else
{
<p class="hint">Cosa avrebbero fatto notizie, calendario e trimestrali mentre erano solo misurate, al giorno della revisione. Il bot non riaccende niente da solo.</p>
<div class="table-wrap">
<table class="table">
<caption class="sr-only">Regole esterne misurate in ombra al giorno della revisione</caption>
<thead><tr><th scope="col">Regola</th><th scope="col" class="num">Esaminati</th><th scope="col" class="num">Ingressi cambiati</th><th scope="col" class="num">Solo rinviati</th><th scope="col" class="num">Aumenti fermati</th><th scope="col" class="num">Stop tenuti fermi</th><th scope="col">Effetto medio a ingresso</th><th scope="col">Stato</th></tr></thead>
<tbody>
@foreach (var x in r.ShadowRules)
{
<tr>
<td>@x.Name</td>
<td class="num">@x.Examined</td>
<td class="num">@x.Changed</td>
<td class="num">@x.Postponed</td>
<td class="num">@x.Increases</td>
<td class="num">@(x.Key == Anubis.Learning.ShadowRules.NewsSevere ? x.StopsKept.ToString(System.Globalization.CultureInfo.InvariantCulture) : "—")</td>
<td>@(x.Mean is { } mean ? Anubis.Learning.ImprovementText.Percent(mean) : "—")@if (x.Low is { } low && x.High is { } high) {<span class="note"> tra @Anubis.Learning.ImprovementText.Percent(low) e @Anubis.Learning.ImprovementText.Percent(high)</span>}@if (x.Missing is { } few) {<span class="note"> (@few)</span>}</td>
<td>@x.State@if (x.JudgedFrom is { } from) {<span class="note">, giudizio non prima del @Format.LongDate(from)</span>}</td>
</tr>
}
</tbody>
</table>
</div>
<p class="note">Intervallo al 99%: contiene il valore vero 99 volte su 100. Criterio per riaccendere una regola: 6 mesi, @Anubis.Learning.ShadowRules.MinChanged ingressi cambiati, effetto tutto sopra lo zero.</p>
}
@@ -0,0 +1,30 @@
@* The rules of ADR 0023 measured in the shadow (ADR 0027 points 16 and 17): the Laboratorio and the quarterly review show the same table. *@
@using Anubis.Learning
<div class="table-wrap">
<table class="table">
<caption class="sr-only">Regole esterne misurate in ombra</caption>
<thead><tr><th scope="col">Regola</th><th scope="col" class="num">Esaminati</th><th scope="col" class="num">Ingressi cambiati</th><th scope="col" class="num">Solo rinviati</th><th scope="col" class="num">Aumenti fermati</th><th scope="col" class="num">Stop tenuti fermi</th><th scope="col">Effetto medio a ingresso</th><th scope="col">Stato</th></tr></thead>
<tbody>
@foreach (var r in Rules)
{
<tr>
<td><strong>@r.Rule.Name</strong><br /><span class="note">@r.Rule.What</span></td>
<td class="num">@r.Examined</td>
<td class="num">@r.Changed</td>
<td class="num">@r.Postponed</td>
<td class="num">@r.Increases</td>
<td class="num">@(r.Rule.Key == ShadowRules.NewsSevere ? r.StopsKept.ToString(System.Globalization.CultureInfo.InvariantCulture) : "—")</td>
<td>@(r.Line.Mean is { } mean ? ImprovementText.Percent(mean) : "—")@if (r.Line.Interval is { } i) {<span class="note"> tra @ImprovementText.Percent(i.Low) e @ImprovementText.Percent(i.High)</span>}@if (r.Line.Missing is { } missing) {<span class="note"> (@missing)</span>}</td>
<td class="@(r.Waiting ? "attention-text" : null)">@r.State@if (r.State == "Troppo presto" && r.JudgedFrom is { } from) {<br /><span class="note">giudizio non prima del @Format.LongDate(from)</span>}</td>
</tr>
}
</tbody>
</table>
</div>
<p class="note">Per riaccendere una regola servono almeno 6 mesi di misura, almeno @ShadowRules.MinChanged ingressi cambiati e un effetto tutto sopra lo zero, con un intervallo che contiene il valore vero 99 volte su 100 (5% diviso per cinque regole); il confronto in backtest della Fase 17 non è ancora disponibile. L'effetto è una quota di quanto l'ingresso ha investito: positivo vuol dire che la regola avrebbe evitato una perdita. Un rinvio e un aumento si contano ma non si valutano. Il bot non riaccende niente da solo: lo fai tu, dalle Impostazioni.</p>
@code {
[Parameter, EditorRequired]
public IReadOnlyList<ShadowRuleView> Rules { get; set; } = [];
}
+1 -1
View File
@@ -154,7 +154,7 @@ internal static partial class Endpoints
}
// And for the rules of the news, and where the model's key goes: the page asks for the password.
if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key))
if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key) || key == Anubis.News.ExternalRules.Setting.Key)
{
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le regole delle notizie e il modello linguistico si cambiano da Impostazioni, con la password quando serve.");
}
+40 -2
View File
@@ -272,17 +272,23 @@ internal static partial class Forms
var back = Back(form, "/impostazioni");
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
var rules = key == Anubis.News.ExternalRules.Setting.Key;
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key &&
!news && !model)
!news && !model && !rules)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
if ((news || model) && host.IsDemo)
if ((news || model || rules) && host.IsDemo)
{
return Results.Redirect(With(back, "errore", "motore"));
}
if (rules && host.Services is { } services0)
{
return Results.Redirect(await ExternalRulesAsync(services0, clock, form, context, ct).ConfigureAwait(false) is { } problem ? With(back, "errore", problem) : back);
}
if (model)
{
// Amounts as the user writes them, "0,50" or "0,50 €", stored as "0.50"; the other values trimmed.
@@ -327,6 +333,38 @@ internal static partial class Forms
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
}
/// <summary>
/// The general switch of ADR 0023 (ADR 0027 points 4 and 5): only measuring the rules takes restrictions away, so with
/// real money it asks for the phrase and the password, as switching a row off; acting again is free. A real change
/// writes its diary line in the same transaction. Null when saved, otherwise the error code of the page.
/// </summary>
private static async Task<string?> ExternalRulesAsync(AppServices app, IClock clock, IFormCollection form, HttpContext context, CancellationToken ct)
{
var value = form["valore"].ToString();
if (value is not (Anubis.News.ExternalRules.Measured or Anubis.News.ExternalRules.Active))
{
return "impostazione";
}
var key = Anubis.News.ExternalRules.Setting.Key;
if (value == Anubis.News.ExternalRules.Measured && (await app.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value != Anubis.News.ExternalRules.Measured &&
await RaiseRefusalAsync(app, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
{
return refusal;
}
var by = context.User.Identity?.Name ?? "utente";
try
{
await app.Settings.SetAsync(key, value, by, (s, old) => Anubis.News.ExternalRules.WriteChangeAsync(s, clock, old, value, by, ct), ct).ConfigureAwait(false);
return null;
}
catch (ReadOnlySettingException)
{
return "impostazione";
}
}
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
+29 -12
View File
@@ -20,6 +20,9 @@ internal static class LearningStates
/// <summary>Set aside by the user.</summary>
public const string Manual = "manual";
/// <summary>Set aside because it uses an outside clue while news, calendar and earnings are only measured (ADR 0027 point 19).</summary>
public const string Rules = "rules";
}
/// <summary>A band of estimates: percentages as they are read, the point at the mean estimate.</summary>
@@ -52,6 +55,7 @@ internal sealed record LearningSummary(string State, int Signals, int Needed, in
LearningStates.Active => "Il modello rimpicciolisce le operazioni che giudica deboli.",
LearningStates.Aside => "Il modello è messo da parte per un'anomalia: le strategie proseguono senza di lui.",
LearningStates.Manual => "Hai messo da parte il modello: le strategie proseguono senza di lui.",
LearningStates.Rules => "Il modello è messo da parte: usa indizi che ora sono solo misurati.",
_ => "Il modello osserva e impara, ma non decide ancora.",
};
}
@@ -159,10 +163,11 @@ internal sealed record LearningView
var models = await desk.Models.AllAsync(cancellationToken).ConfigureAwait(false);
var evaluated = (int)await desk.Models.EvaluatedAsync(cancellationToken).ConfigureAwait(false);
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, host.Clock.UtcNow);
return Summarise(models, evaluated, await desk.CycleAsync(cancellationToken).ConfigureAwait(false), aside, await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false),
host.Clock.UtcNow);
}
private static LearningSummary Summarise(IReadOnlyList<ModelRow> models, int evaluated, CycleState state, bool aside, DateTimeOffset now)
private static LearningSummary Summarise(IReadOnlyList<ModelRow> models, int evaluated, CycleState state, bool aside, bool measured, DateTimeOffset now)
{
var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
@@ -170,6 +175,7 @@ internal sealed record LearningView
var status = champion is null ? LearningStates.None
: aside ? LearningStates.Manual
: state.Aside is not null ? LearningStates.Aside
: measured && Clues.HasExternal(champion.Model?.Clues) ? LearningStates.Rules
: state.ActivatedAt is not null ? LearningStates.Active
: LearningStates.Observation;
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now),
@@ -199,22 +205,26 @@ internal sealed record LearningView
var (_, aside) = await LearningSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
var found = await new DiscoveryDesk(services.Db, clock, desk.Store).LatestAsync(cancellationToken).ConfigureAwait(false);
var events = await desk.Models.EventsAsync(cancellationToken).ConfigureAwait(false);
return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow);
return Of(snapshot, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), capitals, aside, found, events, clock.UtcNow,
await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false));
}
/// <summary>The page from what was read, without touching the database.</summary>
/// <summary>The page from what was read, without touching the database. <paramref name="measured"/>: news, calendar and earnings only measured (ADR 0023).</summary>
public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capitals, bool aside, DiscoverySet discoveries,
IReadOnlyList<ModelEvent> events, DateTimeOffset now)
IReadOnlyList<ModelEvent> events, DateTimeOffset now, bool measured = false)
{
ArgumentNullException.ThrowIfNull(snapshot);
ArgumentNullException.ThrowIfNull(discoveries);
ArgumentNullException.ThrowIfNull(events);
var (champion, challenger, state) = (snapshot.Champion, snapshot.Challenger, snapshot.State);
var inCharge = snapshot.InCharge;
var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, now);
var summary = Summarise(snapshot.Models, inCharge.Count, state, aside, measured, now);
var activation = ActivationCheck.Of(inCharge, baseRates, capitals);
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
var (title, text) = Words(summary, state, now);
var outside = measured && Clues.HasExternal(champion?.Model?.Clues);
// A challenger without the outside clues is already the one trained in its place.
var clean = challenger is not null && !Clues.HasExternal(challenger.Model?.Clues) ? challenger.Version : null;
var (title, text) = Words(summary, state, now, outside, clean);
// What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene".
var live = Judge.Bands(inCharge);
@@ -248,7 +258,7 @@ internal sealed record LearningView
News = discoveries.News,
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
};
view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? []);
view = WithWeights(view, champion?.Report.Weights.Select(w => (w.Group, (int)w.Share)).ToList() ?? [], measured, outside);
if (champion is not null)
{
view = view with
@@ -269,7 +279,7 @@ internal sealed record LearningView
};
}
private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now)
private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now, bool outside = false, int? clean = null)
{
const string How = "Per ogni segnale delle strategie il modello stima quanto è probabile che vada bene, poi confronta la stima con quello che succede davvero.";
const string Limits = "Non potrà mai ingrandirle, né aprirne di sue.";
@@ -280,7 +290,9 @@ internal sealed record LearningView
LearningStates.Active => ("Rimpicciolisce le operazioni che giudica deboli.",
$"{How} Dal {DayText(DayOf(state.ActivatedAt!.Value), now)} le sue stime contano: un segnale che giudica debole compra meno, o niente. Non può mai ingrandire un'operazione, né aprirne di sue."),
LearningStates.Aside => ("Per ora è messo da parte.",
$"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} Torna da solo quando l'anomalia rientra{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."),
$"{(state.Health is { } health ? LearningCycle.AsideText(state.Aside!, health) : "Anomalia.")} {Alone} {(outside ? "Anche quando l'anomalia rientra resta da parte, perché usa indizi che ora sono solo misurati" : "Torna da solo quando l'anomalia rientra")}{(state.ActivatedAt is null ? "; era ancora in osservazione" : "")}."),
LearningStates.Rules => ("Per ora è messo da parte.",
$"Usa notizie, trimestrali o paura e avidità, che ora sono solo misurate: non cambia nessuna operazione nuova. {Alone} Continua a stimare e a imparare; {(clean is { } version ? string.Create(CultureInfo.InvariantCulture, $"la versione {version}, senza quegli indizi, è già in prova come sfidante.") : "la domenica ne addestro uno senza quegli indizi, che entra in prova come sfidante.")}"),
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione nuova; quelle già rimpicciolite restano così fino alla chiusura. Si riattiva da Impostazioni."),
_ when summary.Signals >= summary.Needed => ("Ha visto abbastanza casi, ma non decide ancora.",
$"{How} Potrà rimpicciolire le operazioni che giudica deboli solo quando le prove lo confermano. {Limits}"),
@@ -382,7 +394,8 @@ internal sealed record LearningView
(between > 0 ? Few($"Nelle fasce di mezzo con meno di {Judge.BandMin} casi", between) : "");
}
private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights)
// uses: the model in charge has an outside clue in its list, even one that weighs nothing (then it is set aside).
private static LearningView WithWeights(LearningView view, IReadOnlyList<(string Name, int Share)> weights, bool measured, bool uses = false)
{
var rest = weights.Skip(NamedWeights).Sum(w => w.Share);
var rows = weights.Take(NamedWeights).Where(w => w.Share > 0).Select(w => new LearningWeight(w.Name, w.Share, false)).ToList();
@@ -393,7 +406,10 @@ internal sealed record LearningView
var news = weights.Where(w => Clues.NewsGroups.Contains(w.Name)).Sum(w => w.Share);
var fear = weights.Where(w => w.Name == Fear).Sum(w => w.Share);
var outside = weights.Where(w => Clues.ExternalGroups.Contains(w.Name)).Sum(w => w.Share);
var text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
: measured && !uses && outside == 0 ? "Notizie, trimestrali, paura e avidità non entrano nel modello: le decisioni guardano solo i numeri del mercato."
: measured ? $"Il modello usa notizie, trimestrali o paura e avidità (pesano {outside} su 100), che ora sono solo misurate: per questo è messo da parte."
: news + fear == 0 && weights.Any(w => Clues.NewsGroups.Contains(w.Name) || w.Name == Fear) ? "Notizie, paura e avidità le studia già, ma per ora non pesano."
: news + fear == 0 ? $"Notizie, paura e avidità per ora non pesano: le studia solo quando almeno {Clues.MinLive} segnali dal vivo le contengono."
: news == 0 ? $"Le notizie per ora non pesano; paura e avidità pesano {fear} su 100."
@@ -515,7 +531,8 @@ internal sealed record LearningView
Story = [.. demo.GetProperty("storia").EnumerateArray().Select(s => new LearningStory(s.GetProperty("quando").GetString()!, s.GetProperty("testo").GetString()!))],
};
var named = demo.GetProperty("indizi").EnumerateArray().Select(w => (w.GetProperty("nome").GetString()!, w.GetProperty("peso").GetInt32())).ToList();
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
// The demo shows a new installation: news, calendar and earnings only measured (ADR 0027 point 24).
return WithTrial(WithWeights(view, named, measured: true), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
}
// ---- Words --------------------------------------------------------------------------------------------------
+24 -6
View File
@@ -40,6 +40,9 @@ internal sealed record NewsView(
public const int CalendarRows = 6;
/// <summary>News, calendar and earnings only measured (ADR 0023): the page is an archive of what each rule would have done.</summary>
public bool Measured => Board.Measured;
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
public static async Task<NewsView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
@@ -52,7 +55,7 @@ internal sealed record NewsView(
var board = await new NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
var switches = await NewsRuleSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
var mood = await MoodAsync(new MoodStore(services.Db, clock), now, cancellationToken).ConfigureAwait(false);
var calendar = await CalendarAsync(services, clock, shell.Zone, switches, cancellationToken).ConfigureAwait(false);
var calendar = await CalendarAsync(services, clock, shell.Zone, switches, board.Measured, cancellationToken).ConfigureAwait(false);
using var aggregates = shell.Aggregates();
if (aggregates?.RootElement.GetProperty("notizie") is { } demo)
@@ -120,7 +123,7 @@ internal sealed record NewsView(
// The events that change something or that the user expects to see: this week's US and euro data of medium or high
// impact, the central banks of the next month, the earnings of the stocks held or watched.
private static async Task<IReadOnlyList<CalendarRow>> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches,
private static async Task<IReadOnlyList<CalendarRow>> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches, bool measured,
CancellationToken cancellationToken)
{
var now = clock.UtcNow;
@@ -133,20 +136,26 @@ internal sealed record NewsView(
return (h, n);
}, cancellationToken).ConfigureAwait(false);
var stocks = held.ToHashSet(StringComparer.Ordinal);
// Measured: no note is written, so the candidates come from the list the filter of the earnings reads, within the
// reach the notes would have had (ADR 0027).
var candidates = measured ? await NewsWatcher.WatchedStocksAsync(services.Db, cancellationToken).ConfigureAwait(false) : new HashSet<string>();
var reach = NewsDesk.EarningsReach(now);
var withNote = noted.ToHashSet(StringComparer.Ordinal);
var shown = events.Where(e => e.Kind switch
{
CalendarEventKinds.Economic => e.OccursAt - now <= EconomicAhead && e.Currency is "USD" or "EUR" && e.Impact is "High" or "Medium",
CalendarEventKinds.CentralBank => true,
CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey)),
CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey)
|| (candidates.Contains(s) && Zones.DayIn(e.OccursAt, Zones.NewYork) <= reach)),
_ => false,
}).OrderBy(e => e.OccursAt).Take(CalendarRows);
return [.. shown.Select(e => Row(e, now, zone, switches))];
return [.. shown.Select(e => Row(e, now, zone, switches, measured))];
}
private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches)
private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches, bool measured)
{
var local = TimeZoneInfo.ConvertTime(e.OccursAt, zone);
var day = DateOnly.FromDateTime(local.DateTime);
@@ -163,7 +172,9 @@ internal sealed record NewsView(
"amc" => (", dopo la chiusura", "fino alla seduta dopo i conti"),
_ => ("", "fino alla seduta dopo i conti"),
};
return switches.Earnings
return measured
? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: con le regole attive niente mean reversion {until}. Solo registrato.", false)
: switches.Earnings
? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: niente mean reversion {until}", true)
: new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: la regola è spenta, nessun effetto", false);
}
@@ -177,6 +188,13 @@ internal sealed record NewsView(
};
if (CalendarBlocks.Window(e) is { } window)
{
if (measured)
{
var start = TimeZoneInfo.ConvertTime(window.From, zone);
var end = TimeZoneInfo.ConvertTime(window.To, zone);
return new CalendarRow(whenText, e.Title, string.Create(_it, $"{impact}: con le regole attive nessun nuovo ingresso dalle {start:HH:mm} alle {end:HH:mm}. Solo registrato."), false);
}
if (!switches.Macro)
{
return new CalendarRow(whenText, e.Title, impact + ": la regola è spenta, nessun blocco", false);
+5 -1
View File
@@ -50,9 +50,13 @@ internal sealed record PanoramaView(
{
ArgumentNullException.ThrowIfNull(board);
ArgumentNullException.ThrowIfNull(shell);
// With the rules only measured nothing is in force: the tile says what the rule would have done (ADR 0027 point 23).
return [.. board.Rows.Where(r => r.Active || r.OnPositions).Take(3).Select(r => new PanoramaNews(
Format.ShortDate(r.At, shell.Now, shell.Zone), "su " + r.About, r.Title,
r.Active ? $"{r.Tone.Split(',')[0]}: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].TrimEnd('.')}" : "Nessun effetto: non cambio nulla", r.Active))];
r.Active && board.Measured && r.Action.StartsWith("Con le regole attive", StringComparison.Ordinal)
? $"Evento in arrivo: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].Replace(". Solo registrato.", ", solo registrato", StringComparison.Ordinal)}"
: r.Active && board.Measured ? $"{r.Tone.Split(',')[0]}: la regola l'avrebbe fermata, solo registrato"
: r.Active ? $"{r.Tone.Split(',')[0]}: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].TrimEnd('.')}" : "Nessun effetto: non cambio nulla", r.Active && !board.Measured))];
}
public static async Task<PanoramaView> LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
+4
View File
@@ -56,6 +56,9 @@ internal sealed record RiskView(
bool HasPositions,
IReadOnlyList<WorldRisk> Tripped)
{
/// <summary>News, calendar and earnings only measured (ADR 0023): the figures block nothing, they are only recorded.</summary>
public bool RulesMeasured { get; init; }
/// <summary>After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it.</summary>
public ProtectedRestartView? ProtectedRestart { get; init; }
@@ -162,6 +165,7 @@ internal sealed record RiskView(
positions.Count > 0, tripped)
{
ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false),
RulesMeasured = await Anubis.News.ExternalRules.MeasuredAsync(services.Settings, cancellationToken).ConfigureAwait(false),
};
}
+6 -1
View File
@@ -99,9 +99,14 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, IReadOn
],
};
/// <summary>The lines of a strategy as the rules of the news are now: with them only measured the earnings change nothing (ADR 0023).</summary>
public static IReadOnlyList<string> RulesOf(string strategy, bool measured) =>
[.. (Rules.GetValueOrDefault(strategy) ?? []).Select(r => measured && r == "Salta i giorni prima delle trimestrali" ? "Trimestrali solo misurate: non salta i giorni prima" : r)];
public static async Task<StrategiesView> LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var measured = await Anubis.News.ExternalRules.MeasuredAsync(services.Settings, cancellationToken).ConfigureAwait(false);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
@@ -212,7 +217,7 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, IReadOn
: null;
var flows = equity?.Flows ?? 0m;
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
family?.Description ?? "", RulesOf(stage.Strategy, measured), account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap));
}
+29
View File
@@ -90,6 +90,25 @@ public sealed record ReviewReport
public RestrictionReport Restrictions { get; init; } = new([]);
public RestrictionReport RestrictionsEver { get; init; } = new([]);
/// <summary>
/// The rules of ADR 0023 measured in the shadow, as they stood on the day of the review (ADR 0027 point 17). Empty in the
/// reviews published before Phase 11.
/// </summary>
public IReadOnlyList<ShadowRuleLine> ShadowRules { get; init; } = [];
}
/// <summary>A rule measured in the shadow, frozen in a published review.</summary>
public sealed record ShadowRuleLine(string Key, string Name, string What, int Examined, int Changed, int Postponed, int StopsKept, double? Mean, double? Low, double? High,
string? Missing, string State, DateOnly? JudgedFrom, int Increases = 0)
{
public static ShadowRuleLine Of(ShadowRuleView view)
{
ArgumentNullException.ThrowIfNull(view);
var interval = view.Line.Interval;
return new ShadowRuleLine(view.Rule.Key, view.Rule.Name, view.Rule.What, view.Examined, view.Changed, view.Postponed, view.StopsKept, view.Line.Mean, interval?.Low, interval?.High,
view.Line.Missing, view.State, view.State == "Troppo presto" ? view.JudgedFrom : null, view.Increases);
}
}
/// <summary>A row of <c>quarterly_reviews</c>.</summary>
@@ -120,6 +139,12 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
private readonly ILogger _logger = logger ?? NullLogger.Instance;
/// <summary>
/// Whether the keys of Alpaca and Finnhub are there, read as the Laboratorio reads them: the table of the rules in the
/// shadow says the same thing in both places. Without it the review falls back to the data it finds.
/// </summary>
public Func<CancellationToken, Task<(bool Alpaca, bool Finnhub)>>? Keys { get; init; }
private sealed record State(string Quarter);
public static string QuarterOf(DateOnly day) => string.Create(CultureInfo.InvariantCulture, $"{day.Year:0000}-Q{((day.Month - 1) / 3) + 1}");
@@ -276,6 +301,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false);
var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false);
var restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false);
var keys = Keys is { } read ? await read(cancellationToken).ConfigureAwait(false)
: (stockBars, await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM calendar_events WHERE kind = @k", ("k", CalendarEventKinds.Earnings)), cancellationToken).ConfigureAwait(false) > 0);
var rules = await learning.Shadow.LoadRulesAsync(keys.Item1, keys.Item2, cancellationToken).ConfigureAwait(false);
var report = new ReviewReport
{
Missing = missing,
@@ -284,6 +312,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome),
Restrictions = restrictions,
RestrictionsEver = RestrictionBalance.Add(previous?.Report?.RestrictionsEver, restrictions),
ShadowRules = [.. rules.Select(ShadowRuleLine.Of)],
};
var lines = new List<ReviewLine>();
foreach (var stage in all)
+35 -3
View File
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
public static readonly IReadOnlyList<SettingDefinition> All =
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, News.ExternalRules.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
@@ -65,7 +65,14 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
return new SettingValue(key, saved is null ? definition.Default : JsonSerializer.Deserialize<string>(saved)!, false, null);
}
public async Task SetAsync(string key, string value, string changedBy, CancellationToken cancellationToken = default)
public Task SetAsync(string key, string value, string changedBy, CancellationToken cancellationToken = default) =>
SetAsync(key, value, changedBy, null, cancellationToken);
/// <summary>
/// Saves a value. <paramref name="alsoWhenChanged"/> runs in the same transaction, with the old value, only when the
/// value really changes: a diary line that must exist exactly when the change does. Returns whether it changed.
/// </summary>
public async Task<bool> SetAsync(string key, string value, string changedBy, Func<DbSession, string, Task>? alsoWhenChanged, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(value);
var definition = Definition(key);
@@ -84,10 +91,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
throw new ArgumentException(problem, nameof(value));
}
var now = clock.UtcNow;
var json = new DbJson(JsonSerializer.Serialize(value));
var changed = await db.WriteAsync(async s =>
{
// The time of the change is taken under the writer's lock: a reader of the log never sees it out of order.
var now = clock.UtcNow;
var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
if (old == json.Text)
{
@@ -108,6 +116,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
var previous = old is null ? new DbJson(JsonSerializer.Serialize(definition.Default)) : new DbJson(old);
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
("id", Ids.NewId(clock)), ("k", key), ("o", previous), ("n", json), ("by", changedBy), ("t", now)).ConfigureAwait(false);
if (alsoWhenChanged is not null)
{
await alsoWhenChanged(s, JsonSerializer.Deserialize<string>(previous.Text)!).ConfigureAwait(false);
}
return true;
}, cancellationToken).ConfigureAwait(false);
@@ -115,6 +128,25 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
{
bus.Publish(new SettingChanged(key, value));
}
return changed;
}
/// <summary>
/// The value a setting had at <paramref name="at"/>: the old value of the first change after it, or the value of now
/// when nothing changed since. Values of the startup configuration never change.
/// </summary>
public async Task<string> ValueAtAsync(string key, DateTimeOffset at, CancellationToken cancellationToken = default)
{
var now = await GetAsync(key, cancellationToken).ConfigureAwait(false);
if (now.ReadOnly)
{
return now.Value;
}
var then = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT old_value FROM config_history WHERE key = @k AND created_at > @at ORDER BY created_at, id LIMIT 1",
r => r.TextOrNull("old_value"), ("k", key), ("at", at)), cancellationToken).ConfigureAwait(false);
return then is null ? now.Value : JsonSerializer.Deserialize<string>(then) ?? now.Value;
}
/// <summary>The change log, newest first. Secret values never appear: their entries say only "impostato" or "tolto".</summary>
+3 -3
View File
@@ -54,8 +54,8 @@
"lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50",
"fonti": [{ "nome": "Alpaca News", "frequenza": "in tempo reale" }, { "nome": "14 testate e banche centrali", "frequenza": "ogni 2 minuti" }, { "nome": "Comunicati alla SEC", "frequenza": "ogni 2 minuti" }, { "nome": "Calendario economico", "frequenza": "aggiornato alle 08:00" }],
"panoramica": [
{ "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: per 24 ore non aumento SOL", "in_corso": true },
{ "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: niente mean reversion su JPM fino a martedì", "in_corso": true },
{ "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: la regola l'avrebbe fermata, solo registrato", "in_corso": false },
{ "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: con le regole attive niente mean reversion su JPM, solo registrato", "in_corso": false },
{ "quando": "07:52", "riguarda": "sul mercato in generale", "titolo": "I verbali della banca centrale USA non cambiano le attese sui tassi", "effetto": "Nessun effetto: non cambio nulla", "in_corso": false }
]
},
@@ -87,7 +87,7 @@
"fasce_testo": "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato. Sopra il 65% ha visto solo 14 casi, troppo pochi per contarci.",
"indizi": [
{ "nome": "Forza della tendenza", "peso": 22 }, { "nome": "Agitazione recente dei prezzi", "peso": 17 }, { "nome": "Fase generale del mercato", "peso": 14 },
{ "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Tono delle notizie, 3 giorni", "peso": 9 }, { "nome": "Paura o avidità", "peso": 8 },
{ "nome": "Distanza dallo stop", "peso": 11 }, { "nome": "Nervosismo di Wall Street", "peso": 9 }, { "nome": "Quota di titoli in salita", "peso": 8 },
{ "nome": "Volumi scambiati", "peso": 7 }, { "nome": "Scommesse a leva sulle crypto", "peso": 5 }, { "nome": "Giorno della settimana", "peso": 3 },
{ "nome": "Altro", "peso": 4 }
],
-6
View File
@@ -1,16 +1,10 @@
Giorno;Ora;Voce;Tipo
Oggi;08:20;Controllo periodico: registri in ordine, conto Alpaca allineato.;Sistema
Oggi;08:00;Inviato il riepilogo del mattino su Telegram.;Sistema
Oggi;07:52;Notizia sui verbali della banca centrale USA: nessun effetto.;Notizie
Oggi;06:10;Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.;Notizie
Oggi;03:00;Controllo del modello: nessuna anomalia.;Apprendimento
Oggi;02:06;Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.;Ordini
Oggi;02:05;Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.;Decisioni
Ieri;22:41;Ho messo una restrizione fino a martedì: niente mean reversion su JPM. Motivo: JPMorgan pubblica i conti martedì prima dell'apertura.;Notizie
Ieri;22:21;Azioni: nessun nuovo acquisto. AAPL resta aperta: non è ancora tornata sopra la media a 5 giorni.;Decisioni
Ieri;21:58;Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni. (con il collegamento "Perché l'ho comprata e venduta");Ordini
Ieri;18:20;Ricontrollata la voce sui prelievi rallentati di un exchange: rientrata.;Notizie
Ieri;16:20;Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.;Notizie
Ieri;15:36;Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.;Ordini
Ieri;15:35;Rimessi 6 stop giornalieri sulle frazioni di azione.;Ordini
Ieri;14:31;Richieste di sussidi USA sotto le attese: impatto medio, nessun blocco.;Notizie
Can't render this file because it contains an unexpected character in line 8 and column 81.
+21 -9
View File
@@ -10,9 +10,10 @@ namespace Anubis.Learning;
/// <summary>
/// A clue of SPEC 11.2. <see cref="Group"/> is what the interface calls it: several clues may tell the same thing.
/// <see cref="FromHistory"/> is false for one whose past cannot be rebuilt here: it stays out of the model until at least
/// <see cref="Clues.MinLive"/> live examples contain it.
/// <see cref="Clues.MinLive"/> live examples contain it. <see cref="External"/> marks the clues of news, earnings and fear and
/// greed: with those rules only measured no model may use them (ADR 0023 point 2, ADR 0027 point 18).
/// </summary>
public sealed record Clue(string Key, string Group, bool FromHistory);
public sealed record Clue(string Key, string Group, bool FromHistory, bool External = false);
/// <summary>What was known outside the bars at a decision: each value only if it was already out and already read.</summary>
public sealed record OutsideView
@@ -84,16 +85,16 @@ public static class Clues
new(Breadth, "Quota di titoli in salita", true),
new(WeekSin, "Giorno della settimana", true),
new(WeekCos, "Giorno della settimana", true),
new(Tone1, "Tono delle notizie, 1 giorno", false),
new(Tone3, "Tono delle notizie, 3 giorni", false),
new(Count1, "Numero di notizie", false),
new(Count3, "Numero di notizie", false),
new(WorstEvent, "Notizia più grave", false),
new(FearGreed, "Paura o avidità", false),
new(Tone1, "Tono delle notizie, 1 giorno", false, External: true),
new(Tone3, "Tono delle notizie, 3 giorni", false, External: true),
new(Count1, "Numero di notizie", false, External: true),
new(Count3, "Numero di notizie", false, External: true),
new(WorstEvent, "Notizia più grave", false, External: true),
new(FearGreed, "Paura o avidità", false, External: true),
new(Vix, "Nervosismo di Wall Street", false),
new(Funding, "Scommesse a leva sulle crypto", false),
new(OpenInterest, "Scommesse a leva sulle crypto", false),
new(EarningsDays, "Giorni alla trimestrale", false),
new(EarningsDays, "Giorni alla trimestrale", false, External: true),
];
/// <summary>The groups that come from the news, for the sentence under the weights of the clues.</summary>
@@ -104,6 +105,17 @@ public static class Clues
public static Clue? Find(string key) => All.FirstOrDefault(c => c.Key == key);
/// <summary>The seven outside clues: news, earnings, fear and greed. VIX, funding and open interest are market numbers and stay.</summary>
public static readonly IReadOnlySet<string> External = All.Where(c => c.External).Select(c => c.Key).ToHashSet(StringComparer.Ordinal);
/// <summary>The groups of the outside clues, as the page names them.</summary>
public static readonly IReadOnlySet<string> ExternalGroups = All.Where(c => c.External).Select(c => c.Group).ToHashSet(StringComparer.Ordinal);
public static bool IsExternal(string key) => External.Contains(key);
/// <summary>Whether a model that studies these clues uses an outside one.</summary>
public static bool HasExternal(IEnumerable<string>? keys) => keys?.Any(IsExternal) == true;
/// <summary>The instrument whose trend is the market's: Bitcoin for crypto, SPY for stocks.</summary>
public static string? MarketOf(string strategy, StrategyContext context)
{
+87 -9
View File
@@ -130,6 +130,13 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
public async Task CheckAsync(CancellationToken cancellationToken)
{
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
var measured = await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false);
if (measured && snapshot.State.RulesMeasuredSince is null)
{
await ChangeDayAsync(snapshot, cancellationToken).ConfigureAwait(false);
snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
}
if (snapshot.Champion is not { } champion)
{
return;
@@ -141,14 +148,31 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
var health = Health.Check(champion, labelled, [.. snapshot.Examples.Where(e => e.Source == CaseSources.Live)], now);
var activation = ActivationCheck.Of(snapshot.InCharge, await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false), await CapitalsAsync(cancellationToken).ConfigureAwait(false));
var state = snapshot.State;
var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now };
if (state.ActivatedAt is null && activation.Passed)
var outside = measured && Clues.HasExternal(champion.Model?.Clues);
var next = state with { Health = health, LastNight = today, Aside = health.Aside, AsideAt = health.Aside is null ? null : state.AsideAt ?? now, OutsideAside = outside };
// A model that cannot count does not start counting: the message would say the contrary of what happens.
if (state.ActivatedAt is null && activation.Passed && !outside)
{
next = next with { ActivatedAt = now };
}
await db.WriteAsync(async s =>
{
// Its own reason, never the words of an alarm, and nothing to the phone (ADR 0027 point 19).
if (outside && !state.OutsideAside)
{
var text = string.Create(It, $"Metto da parte la versione {champion.Version}: usa notizie, trimestrali o paura e avidità, che ora sono solo misurate. La domenica ne addestro una senza, che entra in prova come sfidante.");
await TellAsync(s, ModelEvents.RulesAside, champion.Version, text, "Controllo del modello: " + Lower(text), notify: false, cancellationToken).ConfigureAwait(false);
}
else if (!outside && state.OutsideAside)
{
var text = !measured
? string.Create(It, $"Notizie, calendario e trimestrali sono di nuovo attive: la versione {champion.Version} non è più da parte per i loro indizi.")
: string.Create(It, $"La versione {champion.Version} in carica non usa indizi solo misurati: nessun modello è più da parte per questo.");
await TellAsync(s, ModelEvents.RulesBack, champion.Version, text, "Controllo del modello: " + Lower(text), notify: false, cancellationToken).ConfigureAwait(false);
}
if (health.Aside is { } reason && state.Aside is null)
{
var text = AsideText(reason, health) + " Lo metto da parte finché non rientra: le strategie proseguono senza di lui.";
@@ -157,13 +181,18 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
else if (health.Aside is null && state is { Aside: not null, AsideAt: { } since })
{
var days = Math.Max(1, (int)Math.Round((now - since).TotalDays));
var text = $"Anomalia rientrata dopo {(days == 1 ? "un giorno" : days.ToString(It) + " giorni")}: il modello non è più da parte.";
var after = days == 1 ? "un giorno" : days.ToString(It) + " giorni";
var text = outside
? $"Anomalia rientrata dopo {after}, ma il modello resta da parte: usa indizi che ora sono solo misurati."
: $"Anomalia rientrata dopo {after}: il modello non è più da parte.";
await TellAsync(s, ModelEvents.Back, champion.Version, text, "Controllo del modello: " + Lower(text), notify: true, cancellationToken).ConfigureAwait(false);
}
else if (state.LastNight != today)
{
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_check",
health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health) : "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false);
health.Aside is { } still ? "Controllo del modello: resta da parte. " + AsideText(still, health)
: outside ? "Controllo del modello: nessuna anomalia, ma resta da parte perché usa indizi che ora sono solo misurati."
: "Controllo del modello: nessuna anomalia.", null, cancellationToken).ConfigureAwait(false);
}
if (next.ActivatedAt is not null && state.ActivatedAt is null)
@@ -176,6 +205,39 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
}, cancellationToken).ConfigureAwait(false);
}
// Once for each installation: the day news, calendar and earnings stopped changing decisions, and how many labels made
// before it left before a report. They stay as they are (ADR 0023 point 6).
private async Task ChangeDayAsync(LearningSnapshot snapshot, CancellationToken cancellationToken)
{
// The day the decisions stopped reading the rules: the last change to «misurate», or the day the switch was
// written with this version; not the night of this check (ADR 0027 point 22).
var since = await db.ReadAsync(async s =>
{
var changes = await s.QueryAsync("SELECT new_value, created_at FROM config_history WHERE key = @k ORDER BY created_at DESC, id DESC",
r => (Value: r.TextOrNull("new_value"), At: r.Moment("created_at")), ("k", News.ExternalRules.Setting.Key)).ConfigureAwait(false);
return changes.FirstOrDefault(c => c.Value is { } v && System.Text.Json.JsonSerializer.Deserialize<string>(v) == News.ExternalRules.Measured) is { Value: not null } last
? last.At
: await s.FirstOrDefaultAsync("SELECT created_at FROM config WHERE key = @k", r => (DateTimeOffset?)r.Moment("created_at"), ("k", News.ExternalRules.Setting.Key))
.ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
var now = since is { } at && at < clock.UtcNow ? at : clock.UtcNow;
var before = snapshot.Examples.Count(e => e.Source == CaseSources.Live && e.Label?.ExitReason == EquityMeanrev.Reasons.ExitEarnings);
var labels = before switch
{
0 => "Nessun esempio già etichettato usava l'uscita per trimestrale.",
1 => "Un esempio già etichettato usava l'uscita per trimestrale e resta così.",
_ => string.Create(It, $"{before} esempi già etichettati usavano l'uscita per trimestrale e restano così."),
};
var text = string.Create(It, $"Dal {Format.Day(Zones.DayIn(now, Zones.Rome))} notizie, calendario e trimestrali non cambiano le decisioni, e il modello non ne usa gli indizi per decidere. {labels}");
var state = snapshot.State with { RulesMeasuredSince = now };
await db.WriteAsync(async s =>
{
await ModelStore.AddEventAsync(s, clock, ModelEvents.RulesMeasured, null, text, cancellationToken).ConfigureAwait(false);
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_" + ModelEvents.RulesMeasured, text, null, cancellationToken).ConfigureAwait(false);
await LearningStore.SaveStateAsync(s, clock, CycleState.Key, state, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
public static string AsideText(string reason, HealthCheck health)
{
ArgumentNullException.ThrowIfNull(health);
@@ -217,13 +279,25 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
}
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
var measured = await desk.RulesMeasuredAsync(cancellationToken).ConfigureAwait(false);
if (snapshot is { Champion: { } champion, Challenger: { } challenger })
{
await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false);
return;
if (!measured || !Clues.HasExternal(challenger.Model?.Clues))
{
await JudgeAsync(snapshot, champion, challenger, sunday, cancellationToken).ConfigureAwait(false);
return;
}
// Promoted, it would be set aside at once: it leaves its place to one trained without the outside clues (ADR 0027 point 20).
await db.WriteAsync(async s =>
{
await ModelStore.SetStatusAsync(s, clock, challenger.Id, ModelStatuses.Discarded, cancellationToken).ConfigureAwait(false);
var text = string.Create(It, $"Scartata la versione {challenger.Version}: usa indizi che ora sono solo misurati. Ne addestro una senza.");
await TellAsync(s, ModelEvents.Discarded, challenger.Version, text, text, notify: false, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
await TrainAsync(snapshot, sunday, cancellationToken).ConfigureAwait(false);
await TrainAsync(snapshot, sunday, measured, snapshot.Challenger is not null, cancellationToken).ConfigureAwait(false);
}
private Task SaveAsync(CycleState state, CancellationToken cancellationToken) =>
@@ -259,7 +333,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
}, cancellationToken).ConfigureAwait(false);
}
private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, CancellationToken cancellationToken)
private async Task TrainAsync(LearningSnapshot snapshot, DateOnly sunday, bool measured, bool discarded, CancellationToken cancellationToken)
{
// A strategy without a base rate is not estimated, so it does not train either (ADR 0018).
var rates = await desk.BaseRatesAsync(cancellationToken).ConfigureAwait(false);
@@ -268,7 +342,10 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
var seen = state.TrainedOn > 0 ? state.TrainedOn : snapshot.Champion?.Examples ?? 0;
var champion = snapshot.Champion;
TrainingResult? result = null;
if (examples.Count != seen && (champion is not null || examples.Count >= ActivationCheck.Needed))
// A model in charge set aside for the outside clues is trained again even without new labels: otherwise it could
// stay aside for ever (ADR 0027 point 20). So is one in place of a challenger just discarded for the same reason.
var again = measured && (discarded || Clues.HasExternal(champion?.Model?.Clues));
if ((examples.Count != seen || again) && (champion is not null || examples.Count >= ActivationCheck.Needed))
{
var input = new TrainingInput(examples)
{
@@ -276,6 +353,7 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
Capital = await CapitalsAsync(cancellationToken).ConfigureAwait(false),
Funded = await FundedAsync(cancellationToken).ConfigureAwait(false),
Rule = (await desk.GateAsync(cancellationToken).ConfigureAwait(false)).Rule,
ExternalClues = !measured,
};
result = await Task.Run(() => Trainer.Train(input, cancellationToken), cancellationToken).ConfigureAwait(false);
state = state with { TrainedOn = examples.Count };
+65 -19
View File
@@ -32,6 +32,12 @@ public sealed record CycleState
public int TrainedOn { get; init; }
public HealthCheck? Health { get; init; }
/// <summary>True while the model in charge is set aside because it uses an outside clue (ADR 0027 point 19).</summary>
public bool OutsideAside { get; init; }
/// <summary>When this installation first ran with the rules only measured: the day of the change (ADR 0023 point 6).</summary>
public DateTimeOffset? RulesMeasuredSince { get; init; }
}
/// <summary>Why a model is set aside on its own (SPEC 11.4).</summary>
@@ -48,9 +54,12 @@ public sealed record ModelEstimate(ModelRow Row, double Probability, double Base
/// <summary>What decides about the operations at a decision: the model in charge, the one on trial, and whether it counts.</summary>
public sealed record ModelGate(ModelRow? Champion, ModelRow? Challenger, MultiplierRule Rule, IReadOnlyDictionary<string, double> BaseRates, bool Counts)
{
/// <summary>It would count, but it is set aside: by an alarm or by the user.</summary>
/// <summary>It would count, but it is set aside: by an alarm, by the user, or because it uses an outside clue.</summary>
public bool Aside { get; init; }
/// <summary>Set aside because it uses an outside clue while those rules are only measured (ADR 0027 point 19).</summary>
public bool OutsideClues { get; init; }
public static readonly ModelGate None = new(null, null, MultiplierRule.Standard, new Dictionary<string, double>(), false);
/// <summary>Without a base rate for the strategy, or a model that studied it, there is no estimate (ADR 0018).</summary>
@@ -211,14 +220,27 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
public async Task<CycleState> CycleAsync(CancellationToken cancellationToken) => await Store.StateAsync<CycleState>(CycleState.Key, cancellationToken).ConfigureAwait(false) ?? new CycleState();
public async Task<ModelGate> GateAsync(CancellationToken cancellationToken)
/// <summary>Whether news, calendar and earnings are only measured now (ADR 0023); without settings they act.</summary>
public Task<bool> RulesMeasuredAsync(CancellationToken cancellationToken) => News.ExternalRules.MeasuredAsync(settings, cancellationToken);
public async Task<ModelGate> GateAsync(CancellationToken cancellationToken) =>
await GateAsync(await RulesMeasuredAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
/// <summary>
/// The gate of a decision. With the rules only measured a model in charge that uses an outside clue is set aside at
/// once, for that reason and no other (ADR 0027 point 19): it keeps estimating, and changes no size.
/// </summary>
public async Task<ModelGate> GateAsync(bool rulesMeasured, CancellationToken cancellationToken)
{
var (rule, aside) = await LearningSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false);
var state = await CycleAsync(cancellationToken).ConfigureAwait(false);
return new ModelGate(await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false),
await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule, await BaseRatesAsync(cancellationToken).ConfigureAwait(false), state is { ActivatedAt: not null, Aside: null } && !aside)
var champion = await Models.FindAsync(ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
var outside = rulesMeasured && Clues.HasExternal(champion?.Model?.Clues);
return new ModelGate(champion, await Models.FindAsync(ModelStatuses.Challenger, cancellationToken).ConfigureAwait(false), rule,
await BaseRatesAsync(cancellationToken).ConfigureAwait(false), state is { ActivatedAt: not null, Aside: null } && !aside && !outside)
{
Aside = state.Aside is not null || aside,
Aside = state.Aside is not null || aside || outside,
OutsideClues = outside,
};
}
@@ -228,8 +250,12 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
/// not know more than the operation that started on time. Each part that fails is left out alone, because the
/// multiplier an operation was born with holds whatever happens (SPEC 11.1).
/// </summary>
/// <remarks>
/// With the rules of the news only measured (<paramref name="rulesMeasured"/>, ADR 0027 point 9) the earnings dates go to
/// the shadow and nowhere else: the example has no <c>earnings_days</c>, so its label never leaves before a report.
/// </remarks>
public async Task<LearningTurn?> PrepareAsync(string strategy, string stage, DateOnly day, DateTimeOffset at, BacktestDataset data, Func<IStrategy> create,
IReadOnlyDictionary<string, DateOnly>? earnings, CancellationToken cancellationToken)
IReadOnlyDictionary<string, DateOnly>? earnings, bool rulesMeasured, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(create);
@@ -270,9 +296,10 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
}
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
var gate = await OrAsync(() => GateAsync(cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, rulesMeasured ? null : earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
var gate = await OrAsync(() => GateAsync(rulesMeasured, cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
var shadow = await OrAsync(() => Shadow.InputAsync(strategy, stage, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
shadow = shadow with { RulesMeasured = rulesMeasured, Earnings = rulesMeasured ? earnings : null };
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy), shadow, create);
}
@@ -377,6 +404,20 @@ public sealed class LearningTurn
];
}
/// <summary>What the rules of the news would have done to this decision, for the shadow only (ADR 0027 point 13).</summary>
public void Rules(IReadOnlyList<RuleAnswer> answers)
{
ArgumentNullException.ThrowIfNull(answers);
try
{
_shadow.Rules(answers);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_failed(ex);
}
}
// What the model in charge would say of an entry that was not made.
private double? ProbabilityOf(StrategyContext context, Intent intent) =>
_gate.Estimate(new Example(Guid.Empty, _strategy, intent.Symbol, CaseSources.Live, context.Day, context.Now, intent.Reason, intent.TargetWeight ?? 0m, intent.Stop, intent.StopOffset,
@@ -473,18 +514,23 @@ public sealed class LearningTurn
.ConfigureAwait(false);
if (estimate.InCharge)
{
var data = new Dictionary<string, object?>
{
["probability"] = estimate.Probability,
["base_rate"] = estimate.BaseRate,
["multiplier"] = estimate.Multiplier,
["applied"] = applied,
["version"] = estimate.Row.Version,
["counts"] = _gate.Counts,
["aside"] = _gate.Aside,
};
if (_gate.OutsideClues)
{
data["outside_clues"] = true;
}
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, _strategy, account, made.Symbol, DecisionStages.Model,
applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [],
new Dictionary<string, object?>
{
["probability"] = estimate.Probability,
["base_rate"] = estimate.BaseRate,
["multiplier"] = estimate.Multiplier,
["applied"] = applied,
["version"] = estimate.Row.Version,
["counts"] = _gate.Counts,
["aside"] = _gate.Aside,
}, now), cancellationToken).ConfigureAwait(false);
applied >= 1 ? DecisionOutcomes.Passed : applied > 0 ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, [], data, now), cancellationToken).ConfigureAwait(false);
}
}
}
+8
View File
@@ -49,6 +49,14 @@ public static class ModelEvents
public const string SetAside = "set_aside";
public const string Back = "back";
public const string Drift = "drift";
/// <summary>The day news, calendar and earnings stopped changing decisions on this installation (ADR 0023 point 6).</summary>
public const string RulesMeasured = "rules_measured";
/// <summary>Set aside, and back, because the model in charge uses an outside clue while those rules are only measured.</summary>
public const string RulesAside = "rules_aside";
public const string RulesBack = "rules_back";
}
/// <summary>The register of the models, their estimates and their history (SPEC 11.3–11.5).</summary>
+231 -9
View File
@@ -43,6 +43,66 @@ public static class Improvements
];
}
/// <summary>
/// The five rules of news, calendar and earnings measured in the shadow while they only are measured (ADR 0023 point 4,
/// ADR 0027 points 11–17). Apart from the improvements of 8.7: their own level (99%), their own criterion, no discoveries.
/// </summary>
public static class ShadowRules
{
public const string NewsSevere = "rule_news_severe";
public const string NewsNegative = "rule_news_negative";
public const string Macro = "rule_macro";
public const string EarningsEntry = "rule_earnings_entry";
public const string EarningsExit = "rule_earnings_exit";
/// <summary>The stops a serious event would have kept where they were: only counted.</summary>
public const string SevereStop = "rule_news_severe_stop";
/// <summary>Five rules share 5%: each is judged at 99% (ADR 0023 point 5).</summary>
public const double Level = 0.99;
/// <summary>Months of measure before a judgement; under them the line says «troppo presto».</summary>
public const int Months = 6;
/// <summary>Entries the rule would have changed, at least.</summary>
public const int MinChanged = 30;
public static readonly IReadOnlyList<Improvement> All =
[
new(NewsSevere, "Notizia grave", "Evento grave confermato: niente nuovi acquisti per 72 ore, lo stop resta dov'è",
[StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]),
new(NewsNegative, "Notizia negativa", "Notizia negativa confermata: niente acquisti né aumenti per 24 ore",
[StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]),
new(Macro, "Dato macro", "Dato macro ad alto impatto: niente ingressi da 30 minuti prima a 30 dopo",
[StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]),
new(EarningsEntry, "Trimestrale in ingresso", "Niente mean reversion su un titolo con i conti in arrivo entro tre sedute", [StrategyNames.EquityMeanrev]),
new(EarningsExit, "Trimestrale in uscita", "La mean reversion esce alla chiusura prima dei conti", [StrategyNames.EquityMeanrev]),
];
/// <summary>The rules that look only at stocks: without the Alpaca keys they have nothing to measure.</summary>
public static bool StocksOnly(string rule) => rule is EarningsEntry or EarningsExit;
}
/// <summary>What a rule would have done to one purchase or one stop (ADR 0027 point 13).</summary>
public enum RuleEffect
{
None,
Postponed,
Dropped,
StopKept,
}
/// <summary>The answer of one rule on one symbol of a decision, given by the live engine.</summary>
public sealed record RuleAnswer(string Rule, string Symbol, RuleEffect Effect, News.EntryHold? Hold);
/// <summary>What a rule case is beside a plain entry: only counted, never valued.</summary>
public static class ShadowKinds
{
public const string Postponed = "postponed";
public const string Increase = "increase";
public const string Stop = "stop";
}
/// <summary>What an improvement would have done with a signal. A factor of 1 leaves it as it is.</summary>
public sealed record ShadowCase(string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, IReadOnlyDictionary<string, double> Numbers)
{
@@ -51,6 +111,20 @@ public sealed record ShadowCase(string Improvement, string Strategy, string Symb
/// <summary>Measured later on prices (the entry time), not on the outcome of the signal.</summary>
public bool OnPrices { get; init; }
/// <summary>A rule case only counted (<see cref="ShadowKinds"/>); null for an entry it judges.</summary>
public string? Kind { get; init; }
/// <summary>The earnings date known at the entry, for the rule of the exit.</summary>
public DateOnly? Report { get; init; }
/// <summary>The story or the figure behind a rule case, and when its hold would have ended.</summary>
public string? Motive { get; init; }
public DateTimeOffset? Until { get; init; }
/// <summary>Counted at once: an increase or a stop has no example of its own to measure.</summary>
public bool Settled => Kind is ShadowKinds.Increase or ShadowKinds.Stop;
}
public sealed record ShadowEntry(string Symbol, decimal Weight, decimal? StopOffset, string Reason, double? EarningsDays);
@@ -119,6 +193,12 @@ public sealed record ShadowInput(IReadOnlyList<ShadowBook> OtherBooks, IReadOnly
/// <summary>False when what another strategy held on that day is no longer known: the portfolio cannot be judged.</summary>
public bool Whole { get; init; } = true;
/// <summary>True when news, calendar and earnings are only measured: then their rules go to the shadow (ADR 0027 point 12).</summary>
public bool RulesMeasured { get; init; }
/// <summary>The next earnings date of each stock known at the decision; null when the calendar is not fresh.</summary>
public IReadOnlyDictionary<string, DateOnly>? Earnings { get; init; }
}
/// <summary>
@@ -189,6 +269,56 @@ internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, Ca
}
Choice(context, intents, fresh);
if (input.RulesMeasured && input.Earnings is { } earnings)
{
Earnings(context, fresh, earnings);
}
}
}
// The two rules of the earnings (ADR 0027 points 14 and 15), with the dates known at the decision. The exit is noted at
// the entry, once for the operation, and measured when the operation has its label.
private void Earnings(StrategyContext context, HashSet<string> fresh, IReadOnlyDictionary<string, DateOnly> earnings)
{
if (context.NextSession is not { } entry)
{
return;
}
var sessions = create() is EquityMeanrev rules ? rules.EarningsSessions : new EquityMeanrevSettings().EarningsSessions;
foreach (var symbol in fresh.Order(StringComparer.Ordinal))
{
var report = earnings.TryGetValue(symbol, out var date) && date >= day ? date : (DateOnly?)null;
var ahead = report is { } r && EquityMeanrev.EarningsAhead(day, entry, r, sessions);
_cases.Add(new ShadowCase(ShadowRules.EarningsEntry, strategy, symbol, day, ahead ? 0 : 1, Days(report)) { Report = report });
_cases.Add(new ShadowCase(ShadowRules.EarningsExit, strategy, symbol, day, report is null ? 1 : 0, Days(report)) { Report = report });
}
}
private Dictionary<string, double> Days(DateOnly? report) =>
report is { } r ? new Dictionary<string, double>(StringComparer.Ordinal) { ["report_days"] = r.DayNumber - day.DayNumber } : new Dictionary<string, double>(StringComparer.Ordinal);
/// <summary>
/// What the rules of the news and of the figures would have done to the purchases and stops of this decision (ADR 0027
/// point 13). A new entry is judged; an increase and a stop kept are only counted.
/// </summary>
public void Rules(IReadOnlyList<RuleAnswer> answers)
{
if (!input.RulesMeasured)
{
return;
}
var fresh = collector.Cases.Where(c => c.Day == day).Select(c => c.Symbol).ToHashSet(StringComparer.Ordinal);
foreach (var a in answers)
{
var numbers = new Dictionary<string, double>(StringComparer.Ordinal);
var found = new ShadowCase(a.Rule, strategy, a.Symbol, day, 1, numbers) { Motive = a.Hold?.Motive, Until = a.Effect == RuleEffect.None ? null : a.Hold?.Until };
_cases.Add(a.Effect == RuleEffect.StopKept ? found with { Kind = ShadowKinds.Stop }
: !fresh.Contains(a.Symbol) ? found with { Kind = ShadowKinds.Increase, Factor = a.Effect == RuleEffect.None ? 1 : 0 }
: a.Effect == RuleEffect.Dropped ? found with { Factor = 0 }
: a.Effect == RuleEffect.Postponed ? found with { Kind = ShadowKinds.Postponed }
: found);
}
}
@@ -301,14 +431,17 @@ internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, Ca
/// <summary>How many signals an improvement changed and what it would have been worth, on one alternative.</summary>
public sealed record ImprovementLine(string? Label, int Cases, int Months, double? Mean, double? Error)
{
/// <summary>How often the interval holds the true mean: 95 times in 100 for the improvements, 99 for the rules of ADR 0023.</summary>
public double Level { get; init; } = 0.95;
/// <summary>Fewer months than these give no interval: the signals of a month move together, so a month counts as one.</summary>
public const int MinMonths = 6;
/// <summary>What is missing for an interval, in words; null when nothing is.</summary>
public string? Missing => Cases > 0 && Months < MinMonths ? $"troppo pochi mesi per un intervallo: {Months}, ne servono {MinMonths}" : null;
/// <summary>The interval that holds the mean effect 95 times in 100; null with too few months.</summary>
public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile(0.975, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null;
/// <summary>The interval that holds the mean effect <see cref="Level"/> of the times; null with too few months.</summary>
public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile((1 + Level) / 2, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null;
}
/// <summary>An improvement as the pages show it.</summary>
@@ -318,6 +451,17 @@ public sealed record ImprovementView(Improvement Improvement, int Examined, IRea
public string Trust => Discovery.TrustOf(Lines.Where(l => l.Missing is null).Select(l => l.Cases).DefaultIfEmpty(0).Max());
}
/// <summary>
/// A rule of ADR 0023 as the Laboratory and the quarterly review show it: what it would have touched, what it would have been
/// worth at 99%, and whether the criterion to switch it back on is met.
/// </summary>
public sealed record ShadowRuleView(Improvement Rule, int Examined, int Changed, int Postponed, int Increases, int StopsKept, ImprovementLine Line, DateOnly? Since,
string State, bool Waiting, bool Met)
{
/// <summary>The day the judgement can come, six months after the first case.</summary>
public DateOnly? JudgedFrom => Since?.AddMonths(ShadowRules.Months);
}
/// <summary>Saves the shadow of each decision, measures it when the outcomes are known and sums it up.</summary>
public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
{
@@ -364,6 +508,18 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
public IReadOnlyDictionary<string, double> Numbers { get; init; } = new Dictionary<string, double>();
public ShadowEntry? Instead { get; init; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public string? Kind { get; init; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public DateOnly? Report { get; init; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public string? Motive { get; init; }
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
public DateTimeOffset? Until { get; init; }
}
internal static async Task WriteAsync(DbSession s, IClock clock, Guid decisionId, ShadowTurn turn, string strategy, CancellationToken cancellationToken)
@@ -371,13 +527,14 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
var now = clock.UtcNow;
foreach (var c in turn.Cases)
{
// A signal the improvement leaves alone needs no outcome: its effect is nothing.
var known = c.Factor >= 1 && !c.OnPrices;
// A signal the improvement leaves alone needs no outcome: its effect is nothing. A case only counted has none.
var known = c.Factor >= 1 && !c.OnPrices && !c.Settled;
await s.ExecuteAsync(
"INSERT INTO shadow_cases (id, improvement, strategy, symbol, decided_day, decision_id, factor, data, effect, measured_at, created_at, updated_at) " +
"VALUES (@id, @i, @s, @sy, @d, @dec, @f, @data, @e, @m, @now, @now) ON CONFLICT (improvement, strategy, symbol, decided_day) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("i", c.Improvement), ("s", c.Strategy), ("sy", c.Symbol), ("d", BarStore.DayText(c.Day)), ("dec", decisionId), ("f", c.Factor),
("data", new DbJson(JsonSerializer.Serialize(new Stored { Numbers = c.Numbers, Instead = c.Instead }))), ("e", known ? 0.0 : null), ("m", known ? now : null), ("now", now))
("data", new DbJson(JsonSerializer.Serialize(new Stored { Numbers = c.Numbers, Instead = c.Instead, Kind = c.Kind, Report = c.Report, Motive = c.Motive, Until = c.Until }))),
("e", known ? 0.0 : null), ("m", known || c.Settled ? now : null), ("now", now))
.ConfigureAwait(false);
}
@@ -443,6 +600,11 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
return true;
}
if (o.Improvement == ShadowRules.EarningsExit && o.Data.Report is { } report)
{
return await EarningsExitAsync(o, example, result, report, dataOf, cancellationToken).ConfigureAwait(false);
}
if (o.Data.Instead is not { } entry)
{
await SaveAsync(o, (o.Factor - 1) * result, null, cancellationToken).ConfigureAwait(false);
@@ -461,6 +623,22 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
return true;
}
// The operation again with the report it knew at the entry: when the rule would have taken it out before the report, the
// effect is what that exit would have made more than the real one (ADR 0027 point 15). Otherwise it changed nothing.
private async Task<bool> EarningsExitAsync(Open o, Example example, double result, DateOnly report,
Func<string, IReadOnlyList<Example>, CancellationToken, Task<LabelData?>> dataOf, CancellationToken cancellationToken)
{
if (await dataOf(o.Strategy, [example], cancellationToken).ConfigureAwait(false) is not { } source || source.Data[example.Symbol] is not { } instrument
|| instrument.IndexOf(example.Day) < 0 || CaseLabels.Of(example, source.Create, source.Data, source.Through, earnings: report) is not { } with)
{
return false;
}
var exited = with.ExitReason == EquityMeanrev.Reasons.ExitEarnings && with.Result is not null;
await SaveAsync(o, exited ? with.Result!.Value - result : 0, null, cancellationToken, exited ? 0 : 1).ConfigureAwait(false);
return true;
}
private async Task<bool> EntryTimeAsync(Open o, IMarketCalendar calendar, Func<string, DateTimeOffset, DateTimeOffset, CancellationToken, Task<IReadOnlyList<Bar>>> minutes,
CancellationToken cancellationToken)
{
@@ -498,10 +676,10 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
return true;
}
private Task<int> SaveAsync(Open o, double? effect, IReadOnlyDictionary<string, double>? numbers, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET effect = @e, data = @d, measured_at = @now, updated_at = @now WHERE id = @id AND measured_at IS NULL", cancellationToken,
("e", effect is { } e ? Math.Round(e, 8) : null), ("d", new DbJson(JsonSerializer.Serialize(numbers is null ? o.Data : o.Data with { Numbers = numbers }))), ("now", clock.UtcNow), ("id", o.Id)),
cancellationToken);
private Task<int> SaveAsync(Open o, double? effect, IReadOnlyDictionary<string, double>? numbers, CancellationToken cancellationToken, double? factor = null) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET effect = @e, data = @d, factor = @f, measured_at = @now, updated_at = @now WHERE id = @id AND measured_at IS NULL",
cancellationToken, ("e", effect is { } e ? Math.Round(e, 8) : null), ("d", new DbJson(JsonSerializer.Serialize(numbers is null ? o.Data : o.Data with { Numbers = numbers }))),
("f", factor ?? o.Factor), ("now", clock.UtcNow), ("id", o.Id)), cancellationToken);
// ---- Page ---------------------------------------------------------------------------------------------------
@@ -534,6 +712,50 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
];
}
/// <summary>
/// The rules of ADR 0023 measured in the shadow, with the criterion to switch one back on (ADR 0027 point 16). The bot only
/// says whether it is met: switching a rule back on is the user's.
/// </summary>
public async Task<IReadOnlyList<ShadowRuleView>> LoadRulesAsync(bool alpacaKeys, bool finnhubKey, CancellationToken cancellationToken)
{
var rows = await db.ReadAsync(s => s.QueryAsync("SELECT improvement, decided_day, factor, effect, data FROM shadow_cases WHERE improvement LIKE 'rule_%'",
r => new Row(r.Text("improvement"), BarStore.ParseDay(r.Text("decided_day")), r.Measure("factor"), r.IsNull("effect") ? null : r.Measure("effect"),
JsonSerializer.Deserialize<Stored>(r.Json("data").Text) ?? new Stored())), cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime);
return [.. ShadowRules.All.Select(rule => RuleView(rule, rows.Where(r => r.Improvement == rule.Key).ToList(),
rule.Key == ShadowRules.NewsSevere ? rows.Count(r => r.Improvement == ShadowRules.SevereStop) : 0, today, alpacaKeys, finnhubKey))];
}
private static ShadowRuleView RuleView(Improvement rule, List<Row> mine, int stops, DateOnly today, bool alpacaKeys, bool finnhubKey)
{
var valued = mine.Where(r => r is { Factor: < 1, Effect: not null } && r.Data.Kind is null).Select(r => (r.Day, r.Effect!.Value)).ToList();
var line = Summary(null, valued) with { Level = ShadowRules.Level };
var first = mine.Count > 0 ? mine.Min(r => r.Day) : (DateOnly?)null;
string state;
var waiting = false;
var met = false;
if (first is not { } since)
{
waiting = ShadowRules.StocksOnly(rule.Key) && (!alpacaKeys || !finnhubKey);
state = !ShadowRules.StocksOnly(rule.Key) ? "Nessun caso finora"
: !alpacaKeys ? "In attesa delle chiavi Alpaca"
: !finnhubKey ? "In attesa della chiave Finnhub"
: "Nessun caso finora";
}
else if (today < since.AddMonths(ShadowRules.Months))
{
state = "Troppo presto";
}
else
{
met = valued.Count >= ShadowRules.MinChanged && line.Interval is { Low: > 0 };
state = met ? "Criterio raggiunto" : "Criterio non raggiunto";
}
return new ShadowRuleView(rule, mine.Count, valued.Count, mine.Count(r => r.Data.Kind == ShadowKinds.Postponed), mine.Count(r => r.Data.Kind == ShadowKinds.Increase && r.Factor < 1),
stops, line, first, state, waiting, met);
}
private static IReadOnlyList<ImprovementLine> EntryLines(List<Row> rows) =>
[
.. new[] { ("A 15 minuti", "gain15"), ("A 30 minuti", "gain30") }.Select(x =>
+8 -3
View File
@@ -74,6 +74,9 @@ public sealed record TrainingInput(IReadOnlyList<Example> Examples)
public MultiplierRule Rule { get; init; } = MultiplierRule.Standard;
public long Seed { get; init; } = 11;
/// <summary>False while news, calendar and earnings are only measured: the outside clues stay out (ADR 0027 point 18).</summary>
public bool ExternalClues { get; init; } = true;
}
public sealed record TrainingResult(TrainedModel Model, ModelReport Report);
@@ -106,12 +109,14 @@ public static class Trainer
/// The clues that enter (SPEC 11.2): those rebuilt from the history, and those without one only when at least
/// <see cref="Clues.MinLive"/> live examples contain them. A clue that never changes tells nothing.
/// </summary>
public static IReadOnlyList<string> CluesOf(IReadOnlyList<Example> examples)
/// <remarks>With <paramref name="external"/> false the outside clues never enter, however many live examples carry them.</remarks>
public static IReadOnlyList<string> CluesOf(IReadOnlyList<Example> examples, bool external = true)
{
ArgumentNullException.ThrowIfNull(examples);
return
[
.. Clues.All.Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive)
.. Clues.All.Where(c => external || !c.External)
.Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive)
.Select(c => c.Key)
.Where(key => examples.Where(e => e.Features.ContainsKey(key)).Select(e => e.Features[key]).Distinct().Take(2).Count() > 1),
];
@@ -122,7 +127,7 @@ public static class Trainer
{
ArgumentNullException.ThrowIfNull(input);
var cases = input.Examples.Where(e => e.IsLabelled).OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal).ToList();
var clues = CluesOf(cases);
var clues = CluesOf(cases, input.ExternalClues);
if (cases.Count < MinExamples || clues.Count == 0 || !BothOutcomes(cases))
{
return null;
+87
View File
@@ -0,0 +1,87 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.News;
/// <summary>
/// Whether news, the economic calendar and the earnings dates change decisions (ADR 0023, 0027): «misurate», the default,
/// leaves every decision to the numbers and only records what each rule would have done; «attive» is the behaviour of
/// Phase 7. It stands above the five rows of SPEC 10.5, which act only with «attive».
/// </summary>
public static class ExternalRules
{
public const string Measured = "misurate";
public const string Active = "attive";
/// <summary>The code of the diary line each real change writes.</summary>
public const string Changed = "external_rules_changed";
public static readonly SettingDefinition Setting = new("decisions.external_rules", "Notizie, calendario e trimestrali", Measured, [Measured, Active]);
/// <summary>
/// Whether the rules are only measured now. Without settings, which happens only in tests that build a part alone, they
/// act, as the five rows are all on without settings.
/// </summary>
public static async Task<bool> MeasuredAsync(SettingsStore? settings, CancellationToken cancellationToken) =>
settings is not null && (await settings.GetAsync(Setting.Key, cancellationToken).ConfigureAwait(false)).Value == Measured;
/// <summary>Whether the rules were only measured at <paramref name="at"/>, from the change log: a decision redone later reads them as they were.</summary>
public static async Task<bool> MeasuredAtAsync(SettingsStore? settings, DateTimeOffset at, CancellationToken cancellationToken) =>
settings is not null && await settings.ValueAtAsync(Setting.Key, at, cancellationToken).ConfigureAwait(false) == Measured;
/// <summary>The value in the words of the Impostazioni page.</summary>
public static string Label(string value) => value switch
{
Measured => "solo misurate",
Active => "attive",
_ => value,
};
/// <summary>
/// Writes the switch once, at the first start of this version (ADR 0027 point 22). On an installation that already
/// decided something the rules acted until now: the change log gets «attive» → «misurate» at this instant, so a
/// decision redone later reads the rules as they were, and the diary says it once. A new installation only gets the
/// row, so a copy moved elsewhere carries it. Returns true when it recorded an upgrade.
/// </summary>
public static Task<bool> SettleAsync(Database db, IClock clock, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(clock);
return db.WriteAsync(async s =>
{
if (await s.CountAsync("SELECT COUNT(*) FROM config WHERE key = @k", ("k", Setting.Key)).ConfigureAwait(false) > 0)
{
return false;
}
var now = clock.UtcNow;
var measured = new DbJson(System.Text.Json.JsonSerializer.Serialize(Measured));
await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)", cancellationToken,
("id", Ids.NewId(clock)), ("k", Setting.Key), ("v", measured), ("t", now)).ConfigureAwait(false);
if (await s.CountAsync("SELECT COUNT(*) FROM engine_runs").ConfigureAwait(false) == 0)
{
return false;
}
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
("id", Ids.NewId(clock)), ("k", Setting.Key), ("o", new DbJson(System.Text.Json.JsonSerializer.Serialize(Active))), ("n", measured), ("by", Upgrade), ("t", now))
.ConfigureAwait(false);
await Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.System, Changed,
"Con questa versione notizie, calendario e trimestrali sono solo misurate: da ora non cambiano nessuna decisione, registro solo cosa avrebbe fatto ogni regola. " +
"Per farle tornare ad agire: Impostazioni → Notizie.", new { from = Active, to = Measured, by = Upgrade }, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
}
/// <summary>Who changed the switch when this version found an installation where the rules acted.</summary>
public const string Upgrade = "aggiornamento";
/// <summary>The diary line of a change, in the same transaction as the change itself (ADR 0027 point 5). No Telegram.</summary>
public static Task WriteChangeAsync(DbSession s, IClock clock, string from, string to, string by, CancellationToken cancellationToken)
{
var text = to == Measured
? $"Notizie, calendario e trimestrali da «{Label(from)}» a «{Label(to)}»: da ora non cambiano nessuna decisione, registro solo cosa avrebbe fatto ogni regola. Cambiato da {by}."
: $"Notizie, calendario e trimestrali da «{Label(from)}» a «{Label(to)}»: da ora le regole accese possono fermare o rinviare un acquisto. Cambiato da {by}.";
return Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.System, Changed, text, new { from, to }, cancellationToken);
}
}
+29 -5
View File
@@ -27,7 +27,14 @@ public sealed record NewsBoardRow(
}
/// <summary>The stories of the last 24 hours with what the bot did, and the three counts of the filters.</summary>
public sealed record NewsBoardResult(IReadOnlyList<NewsBoardRow> Rows, int Read, int OnPositions, int Active);
public sealed record NewsBoardResult(IReadOnlyList<NewsBoardRow> Rows, int Read, int OnPositions, int Active)
{
/// <summary>
/// True when news, calendar and earnings are only measured (ADR 0023): <see cref="NewsBoardRow.Action"/> says what the rule
/// would have done, and <see cref="Active"/> counts the stories a rule would act on now.
/// </summary>
public bool Measured { get; init; }
}
/// <summary>
/// What the Notizie e mercato screen lists (SPEC 13.6): every story read in the last 24 hours, plus older ones whose
@@ -43,6 +50,7 @@ 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);
var measured = await ExternalRules.MeasuredAsync(settings, cancellationToken).ConfigureAwait(false);
// 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 =>
@@ -93,7 +101,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
})];
// Older stories stay while their effect is in force: from a note, or from the rules for an instrument nobody watches.
var stories = all.Select(a => a.Fact).Where(st => st.FirstSeenAt >= since || notesOf["story:" + st.Id].Any(n => n.Until > now) ||
(linksOf[st.Id].Any(l => l.Scope == LinkScopes.Instrument) && NewsRules.Active([st], now, switches).Count > 0)).ToList();
(linksOf[st.Id].Any(l => l.Scope == LinkScopes.Instrument) && NewsRules.Active([st], now, measured ? NewsRuleSwitches.AllOn : switches).Count > 0)).ToList();
var rows = new List<NewsBoardRow>();
foreach (var story in stories)
@@ -108,9 +116,13 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
_ => holding.Count > 0,
});
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);
// Measured: the rule of the story first; the filter of the earnings speaks only for a story no rule of 10.5 meets.
var rule = measured ? ByRule(story, instruments, heldTargets, NewsRuleSwitches.AllOn, now, true) : default;
var (action, active) = !measured ? Act(story, instruments, storyNotes.Select(n => (n.Kind, n.Action, n.Until)).ToList(), heldTargets, switches, now)
: !rule.Active && instruments.FirstOrDefault(reporting.Contains) is { } report ? (NewsActions.WouldSkipEarnings(report[(report.IndexOf(':', StringComparison.Ordinal) + 1)..]), true)
: rule;
var verdict = verdicts[story.Id];
// 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)) +
@@ -124,7 +136,7 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
rows = [.. rows.OrderByDescending(r => r.Active).ThenByDescending(r => r.At).ThenBy(r => r.Id)];
var read = stories.Count(st => st.FirstSeenAt >= since);
return new NewsBoardResult(rows, read, rows.Count(r => r.OnPositions), rows.Count(r => r.Active));
return new NewsBoardResult(rows, read, rows.Count(r => r.OnPositions), rows.Count(r => r.Active)) { Measured = measured };
}
/// <summary>The five grades of SPEC 10.2 point 4 in words; an Italian title without the model has no tone.</summary>
@@ -217,6 +229,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
return (unconfirmed, false);
}
return ByRule(story, instruments, held, switches, now, false);
}
// The rule of 10.5 the story meets, or why it meets none. Measured: what the rule would have done, never done (ADR 0027).
private static (string Action, bool Active) ByRule(StoryFact story, List<string> instruments, HashSet<string> held, NewsRuleSwitches switches, DateTimeOffset now, bool measured)
{
if (instruments.Count == 0)
{
return story.Score is <= -0.2
@@ -239,6 +257,12 @@ public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings
var target = instruments[0];
var symbol = target[(target.IndexOf(':', StringComparison.Ordinal) + 1)..];
if (measured)
{
var would = NewsActions.WouldRestrict(matched, symbol, held.Contains(target));
return matched.Until > now ? (would + " Solo registrato.", true) : (would + " Sarebbe già finita.", false);
}
var text = NewsActions.Restriction(matched, symbol, held.Contains(target));
return matched.Until > now ? (text, true) : (text + " Restrizione finita.", false);
}
+81 -2
View File
@@ -156,12 +156,34 @@ public interface IEntryGate
Task<EntryHold?> KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken);
}
/// <summary>What each rule of 10.5 that stops a purchase would say of it, each on its own and with every row on (ADR 0027 point 7).</summary>
public sealed record RuleHolds(EntryHold? Severe, EntryHold? Negative, EntryHold? Macro)
{
public static readonly RuleHolds None = new(null, null, null);
}
/// <summary>
/// The gate asked rule by rule, for the measure in the shadow when the rules are only measured (ADR 0023 point 4). It
/// answers whatever the rows say: a row switched off is still measured.
/// </summary>
public interface IRuleShadowGate
{
/// <summary>
/// The holds of the three rules on a purchase decided at <paramref name="at"/> and due at <paramref name="due"/>: the
/// news as they are at the decision, the figures around the time the order would go (ADR 0027 point 8).
/// </summary>
Task<RuleHolds> ByRuleAsync(InstrumentSpec spec, DateTimeOffset at, DateTimeOffset due, CancellationToken cancellationToken);
/// <summary>The serious event that would keep the stop of a position where it is, or null.</summary>
Task<EntryHold?> WouldKeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken);
}
/// <summary>
/// The rows of 10.5 that act on a single purchase: the news on the instrument (first two rows) and the high-impact
/// figures (fifth row), the strictest of them. The earnings row acts inside <c>equity_meanrev</c>, which knows its
/// sessions; the third row never stops anything.
/// </summary>
public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings = null) : IEntryGate
public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings = null) : IEntryGate, IRuleShadowGate
{
private readonly NewsDesk _desk = new(db, clock, settings);
private readonly CalendarEventStore _calendar = new(db, clock);
@@ -197,6 +219,33 @@ public sealed class EntryGate(Database db, IClock clock, SettingsStore? settings
: null;
}
public async Task<RuleHolds> ByRuleAsync(InstrumentSpec spec, DateTimeOffset at, DateTimeOffset due, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(spec);
var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.Longest, cancellationToken).ConfigureAwait(false);
var all = NewsRules.Active(stories, at, NewsRuleSwitches.AllOn);
EntryHold? Of(string code) => NewsRules.Strictest(all.Where(r => r.Code == code)) is { } r ? new EntryHold(r.Code, r.Until, Motive(r.Story)) : null;
EntryHold? macro = null;
var events = await _calendar.BetweenAsync(due - TimeSpan.FromHours(3), due + TimeSpan.FromHours(3), cancellationToken).ConfigureAwait(false);
if (CalendarBlocks.BlockedUntil(due, events) is { } until)
{
var named = events.Where(e => CalendarBlocks.Window(e) is { } w && w.From <= due && w.To > due).OrderByDescending(e => CalendarBlocks.Window(e)!.Value.To).First();
macro = new EntryHold(CorrectiveReasons.CalendarEvent, until, named.Title);
}
return new RuleHolds(Of(NewsReasons.Severe), Of(NewsReasons.Negative), macro);
}
public async Task<EntryHold?> WouldKeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(spec);
var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.Longest, cancellationToken).ConfigureAwait(false);
return NewsRules.KeepsStop(NewsRules.Active(stories, at, NewsRuleSwitches.AllOn)) is { } severe
? new EntryHold(NewsReasons.KeepStop, severe.Until, Motive(severe.Story))
: null;
}
/// <summary>The story as the diary names it: its title in quotes and who published it.</summary>
public static string Motive(StoryFact story)
{
@@ -221,9 +270,17 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
/// <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>
/// <summary>
/// One round over the instruments watched now: those held by any strategy and those of the latest universes. With the
/// rules only measured it says nothing at all: no note, no diary line, no notice (ADR 0023 point 2).
/// </summary>
public async Task<int> RunOnceAsync(CancellationToken cancellationToken)
{
if (await ExternalRules.MeasuredAsync(settings, cancellationToken).ConfigureAwait(false))
{
return 0;
}
var now = clock.UtcNow;
var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false);
var watched = await WatchedAsync(db, cancellationToken).ConfigureAwait(false);
@@ -332,6 +389,11 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin
return 1;
}, cancellationToken);
/// <summary>The stocks held or candidates of a strategy: the ones whose earnings the filter of the mean reversion reads.</summary>
public static async Task<IReadOnlySet<string>> WatchedStocksAsync(Database db, CancellationToken cancellationToken) =>
(await WatchedAsync(db, cancellationToken).ConfigureAwait(false)).Where(w => w.Target.StartsWith(Venues.Alpaca + ":", StringComparison.Ordinal))
.Select(w => w.Target[(Venues.Alpaca.Length + 1)..]).ToHashSet(StringComparer.Ordinal);
internal static async Task<IReadOnlyList<(string Target, string Symbol, bool Held)>> WatchedAsync(Database db, CancellationToken cancellationToken)
{
var held = await db.ReadAsync(s => s.QueryAsync("SELECT i.venue, i.symbol, p.quantity FROM positions p JOIN instruments i ON i.id = p.instrument_id",
@@ -363,6 +425,23 @@ public static class NewsActions
return held ? $"Per 24 ore non aumento la posizione su {shown}." : $"Per 24 ore non compro {shown}.";
}
/// <summary>The same rule as <see cref="Restriction"/> when the rules are only measured: what it would have done (ADR 0027).</summary>
public static string WouldRestrict(NewsRestriction r, string symbol, bool held)
{
ArgumentNullException.ThrowIfNull(r);
var shown = Trading.DiaryText.Coin(symbol);
if (r.Code == NewsReasons.Severe)
{
return held ? $"Avrebbe fermato per 72 ore i nuovi acquisti di {shown} e tenuto fermo lo stop." : $"Avrebbe fermato per 72 ore i nuovi acquisti di {shown}.";
}
return held ? $"Avrebbe fermato per 24 ore gli aumenti della posizione su {shown}." : $"Avrebbe fermato per 24 ore gli acquisti di {shown}.";
}
/// <summary>What the filter of the earnings would have done on a stock that reports soon, with the rules only measured (ADR 0027).</summary>
public static string WouldSkipEarnings(string symbol) =>
$"Con le regole attive niente nuovi acquisti di mean reversion su {symbol} prima dei conti. Solo registrato.";
public static string Unconfirmed(DateTimeOffset recheck, TimeZoneInfo zone) =>
$"Niente, perché nessun'altra fonte la riportava. La ricontrollo alle {TimeZoneInfo.ConvertTime(recheck, zone):HH:mm}.";
+14 -8
View File
@@ -344,6 +344,9 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
public string Version => EquityMeanrevFamily.FamilyVersion;
/// <summary>Sessions after the entry in which a report keeps the strategy out.</summary>
public int EarningsSessions => _settings.EarningsSessions;
public EquityMeanrevSettings Settings => _settings;
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
@@ -489,20 +492,23 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
/// Earnings in the entry session or the three after it, or out after today's close (live only: the backtest has no
/// earnings calendar, SPEC 8.3).
/// </summary>
private bool EarningsAhead(StrategyContext context, string symbol)
{
if (!context.EarningsEntries || context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry)
{
return false;
}
private bool EarningsAhead(StrategyContext context, string symbol) =>
context.EarningsEntries && context.NextEarnings?.Invoke(symbol) is { } earnings && context.NextSession is { } entry
&& EarningsAhead(context.Day, entry, earnings, _settings.EarningsSessions);
/// <summary>
/// The entry filter as a pure rule: a report from <paramref name="day"/> through the entry session and the
/// <paramref name="sessions"/> after it (weekends skipped, holidays not). The shadow of ADR 0027 point 14 reads the same rule.
/// </summary>
public static bool EarningsAhead(DateOnly day, DateOnly entry, DateOnly earnings, int sessions)
{
var last = entry;
for (var i = 0; i < _settings.EarningsSessions; i++)
for (var i = 0; i < sessions; i++)
{
last = last.AddDays(last.DayOfWeek == DayOfWeek.Friday ? 3 : 1);
}
return earnings >= context.Day && earnings <= last;
return earnings >= day && earnings <= last;
}
public static class Reasons
+106 -16
View File
@@ -156,6 +156,15 @@ public sealed partial class LiveEngine : IDisposable
/// </summary>
public Func<DateOnly, CancellationToken, Task<EarningsView?>>? Earnings { get; init; }
/// <summary>
/// Whether news, calendar and earnings were only measured at an instant (ADR 0023, 0027): then nothing is held back, no
/// date reaches the strategies, and the gate is asked rule by rule for the shadow only. Null: they act, as in Phase 7.
/// </summary>
public Func<DateTimeOffset, CancellationToken, Task<bool>>? RulesMeasured { get; init; }
private async Task<bool> MeasuredAsync(DateTimeOffset at, CancellationToken cancellationToken) =>
RulesMeasured is not null && await RulesMeasured(at, cancellationToken).ConfigureAwait(false);
/// <summary>Learning (SPEC 11): notes the examples of each decision. Null in tests that do not look at it.</summary>
public Anubis.Learning.LearningDesk? Learning { get; init; }
@@ -563,11 +572,13 @@ public sealed partial class LiveEngine : IDisposable
var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters);
var data = loaded.Data;
var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false);
// Read once: one decision never mixes the two ways (ADR 0027 point 2).
var measured = await MeasuredAsync(m.Now, cancellationToken).ConfigureAwait(false);
var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, measured, cancellationToken).ConfigureAwait(false);
var turn = Learning is null
? null
: await Learning.PrepareAsync(m.Strategy, stage.Stage, m.Day, m.Due, data, () => CreateStrategy(m.Strategy, stage.Qualification?.Parameters), await EarningsOfAsync(m, cancellationToken)
.ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
.ConfigureAwait(false), measured, cancellationToken).ConfigureAwait(false);
if (turn is not null)
{
options = options with { Correctives = turn.Around(options.Correctives) };
@@ -596,7 +607,7 @@ public sealed partial class LiveEngine : IDisposable
plan = plan with { Working = await WorkingAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false) };
}
plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false);
plan = measured ? await MeasureRulesAsync(m, mode, plan, data, turn, cancellationToken).ConfigureAwait(false) : await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false);
var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false);
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, turn, cancellationToken).ConfigureAwait(false);
@@ -635,10 +646,13 @@ 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)
/// <summary>
/// The earnings calendar as the decision of <paramref name="day"/> reads it (SPEC 10.5, fourth row; 8.3). With the rules
/// only measured no date reaches the strategy: it decides as every backtest always did (ADR 0027 point 9).
/// </summary>
private async Task<BacktestOptions> WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, bool measured, CancellationToken cancellationToken)
{
if (Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
if (measured || Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
{
return options;
}
@@ -775,6 +789,66 @@ public sealed partial class LiveEngine : IDisposable
return plan with { Orders = orders, Stops = stops, Holds = holds, KeptStops = kept };
}
/// <summary>
/// The rules of 10.5 with the rules only measured (ADR 0027 points 7 and 8): the gate is asked rule by rule and with
/// every row on, what each rule would have done goes to the shadow, and the plan goes out as the strategy made it.
/// </summary>
private async Task<PlanResult> MeasureRulesAsync(Moment m, string mode, PlanResult plan, BacktestDataset data, Anubis.Learning.LearningTurn? turn, CancellationToken cancellationToken)
{
if (Gate is not IRuleShadowGate gate || turn is null)
{
return plan;
}
var answers = new List<Anubis.Learning.RuleAnswer>();
try
{
foreach (var order in plan.Orders.Where(o => o.Side == OrderSide.Buy))
{
if (data[order.Symbol]?.Spec is not { } spec)
{
continue;
}
var holds = await gate.ByRuleAsync(spec, m.Now, order.Due, cancellationToken).ConfigureAwait(false);
foreach (var (rule, hold) in new[] { (Anubis.Learning.ShadowRules.NewsSevere, holds.Severe), (Anubis.Learning.ShadowRules.NewsNegative, holds.Negative),
(Anubis.Learning.ShadowRules.Macro, holds.Macro) })
{
answers.Add(new Anubis.Learning.RuleAnswer(rule, order.Symbol, EffectOf(order, hold), hold));
}
}
foreach (var (symbol, from, to) in plan.Stops)
{
if (mode != DecisionModes.Observation && from > 0m && to < from && data[symbol]?.Spec is { } spec
&& await gate.WouldKeepStopAsync(spec, m.Now, cancellationToken).ConfigureAwait(false) is { } keep)
{
answers.Add(new Anubis.Learning.RuleAnswer(Anubis.Learning.ShadowRules.SevereStop, symbol, Anubis.Learning.RuleEffect.StopKept, keep));
}
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// The measure is apart: a failure of it never changes the decision.
LogShadowFailed(_logger, ex, m.Strategy);
return plan;
}
turn.Rules(answers);
return plan;
}
// What a hold would have done to one purchase: nothing, put it off within its deadline, or left it out (SPEC 5.6).
private Anubis.Learning.RuleEffect EffectOf(PlannedOrder order, EntryHold? hold)
{
if (hold is null || ReleaseAt(order.Crypto, hold.Until) is var release && release <= order.Due)
{
return Anubis.Learning.RuleEffect.None;
}
return order.ValidUntil is { } until && release > until ? Anubis.Learning.RuleEffect.Dropped : Anubis.Learning.RuleEffect.Postponed;
}
/// <summary>
/// The intents become orders as the backtest plans them (BacktestEngine.Plan): target quantity from the weight and
/// the equity at the close, the difference bought or sold, a full exit when the weight is zero, stops moved on what
@@ -893,7 +967,8 @@ public sealed partial class LiveEngine : IDisposable
var currency = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(m.Strategy));
await _db.WriteAsync(async s =>
{
if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken).ConfigureAwait(false))
// The run carries the instant the decision read the switch: the one-step check reads it as it was then.
if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken, now).ConfigureAwait(false))
{
return;
}
@@ -1064,8 +1139,9 @@ public sealed partial class LiveEngine : IDisposable
private async Task<(Guid, bool, IReadOnlyList<string>)?> OneStepAsync(string strategyName, IStrategy strategy, BacktestDataset data, CancellationToken cancellationToken)
{
var previous = await _db.ReadAsync(s => s.FirstOrDefaultAsync(
"SELECT decision_day, decision_id, state, proposed FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1",
r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed")), ("s", strategyName)),
"SELECT decision_day, decision_id, state, proposed, created_at FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1",
r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed"), At: r.Moment("created_at")),
("s", strategyName)),
cancellationToken).ConfigureAwait(false);
if (previous.State is null || previous.Proposed is null || data.Instruments.All(i => i.IndexOf(previous.Day) < 0))
{
@@ -1080,7 +1156,9 @@ public sealed partial class LiveEngine : IDisposable
}
var state = snapshot.ToState();
var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, cancellationToken).ConfigureAwait(false);
// The earnings as that decision read them: a change of the switch in between is no difference (ADR 0027 point 2).
var options = await WithEarningsAsync(new BacktestOptions(), strategyName, previous.Day, await MeasuredAsync(previous.At, cancellationToken).ConfigureAwait(false),
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);
@@ -1089,7 +1167,11 @@ public sealed partial class LiveEngine : IDisposable
// ---- Releasing planned orders -------------------------------------------------------------------------------
private sealed record Planned(Guid Id, Guid DecisionId, string Strategy, Guid AccountId, Guid InstrumentId, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll,
decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, DateTimeOffset? FirstDue = null);
decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, DateTimeOffset? FirstDue = null)
{
/// <summary>When the decision behind it was taken: the switch of the outside rules is read as it was then (ADR 0027 point 2).</summary>
public DateTimeOffset DecidedAt { get; init; } = Due;
}
/// <summary>
/// The planned orders whose time has come go to the order manager, sales first (SPEC 5.5). An entry past its
@@ -1151,7 +1233,9 @@ public sealed partial class LiveEngine : IDisposable
return;
}
if (order.Side == OrderSide.Buy && Gate is not null && await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold)
// The gate at send time belongs to a decision taken with the rules acting: the switch is read as that decision read it.
if (order.Side == OrderSide.Buy && Gate is not null && !await MeasuredAsync(order.DecidedAt, cancellationToken).ConfigureAwait(false)
&& await Gate.HoldAsync(instrument.Spec, now, cancellationToken).ConfigureAwait(false) is { } hold)
{
await HoldAsync(order, instrument.Symbol, hold with { Until = ReleaseAt(instrument.IsCrypto, hold.Until) }, now, cancellationToken).ConfigureAwait(false);
return;
@@ -1267,13 +1351,16 @@ public sealed partial class LiveEngine : IDisposable
private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked);
// decided_at is the first row of its decision: an order planned again after a restart keeps the instant of the decision.
private const string PlannedColumns =
"p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until, p.first_due_at";
"p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until, p.first_due_at, " +
"(SELECT MIN(x.created_at) FROM planned_orders x WHERE x.decision_id = p.decision_id) AS decided_at";
private static Planned ReadPlanned(DbRow r) =>
new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")),
r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"),
r.MomentOrNull("valid_until"), r.MomentOrNull("first_due_at"));
r.MomentOrNull("valid_until"), r.MomentOrNull("first_due_at"))
{ DecidedAt = r.Moment("decided_at") };
/// <summary>
/// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between
@@ -1545,12 +1632,12 @@ public sealed partial class LiveEngine : IDisposable
_db.WriteAsync(s => ClaimAsync(s, strategy, key, day, Guid.Empty, "none", null, null, cancellationToken), cancellationToken);
private async Task<bool> ClaimAsync(DbSession s, string strategy, string key, DateOnly day, Guid decisionId, string mode, string? state, string? proposed,
CancellationToken cancellationToken) =>
CancellationToken cancellationToken, DateTimeOffset? at = null) =>
await s.ExecuteAsync(
"INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, @st, @p, @now) " +
"ON CONFLICT (run_key) DO NOTHING", cancellationToken,
("id", Ids.NewId(_clock)), ("s", strategy), ("k", key), ("d", BarStore.DayText(day)), ("dec", decisionId), ("m", mode),
("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0;
("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", at ?? _clock.UtcNow)).ConfigureAwait(false) > 0;
public void Dispose() => _gate.Dispose();
@@ -1562,6 +1649,9 @@ public sealed partial class LiveEngine : IDisposable
[LoggerMessage(Level = LogLevel.Error, Message = "Planned order {Id} could not be released")]
private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id);
[LoggerMessage(Level = LogLevel.Error, Message = "The shadow of the news rules of {Strategy} was left out")]
private static partial void LogShadowFailed(ILogger logger, Exception exception, string strategy);
}
/// <summary>The comparison of two sets of intents (SPEC 12.3): same action and size within 10%, for what is held and what either version enters.</summary>
+1
View File
@@ -200,6 +200,7 @@ public sealed partial class TradingService : IDisposable
{
WantData = market is null ? null : _ => market.WakeWorker(),
Gate = new News.EntryGate(db, clock, settings),
RulesMeasured = (at, ct) => News.ExternalRules.MeasuredAtAsync(settings, at, ct),
Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct),
Ready = () => _started,
AccountReady = AccountReady,