Fase 11 — Decisioni solo matematiche (#186)
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:
1 parent
ed22d1c8b5
commit
93cdf7850d
47 files changed
+1743
-169
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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; } = [];
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
|
||||
@@ -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, "/");
|
||||
|
||||
@@ -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 --------------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user