Show what the model knows on its own screen and let the user set it aside
The Apprendimento screen says in plain words whether the model counts, how well its probabilities hold, which clues it weighs, how the challenger is doing and what it has learned. Thresholds, set-aside and the undo of a promotion live in Impostazioni; anything that shrinks less with real money asks for the phrase. The new tests also caught a wrong column name that broke the Panoramica as soon as the first model existed. refs #66 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
14e8a872dc
commit
f69943f70a
22 files changed
+1680
-27
No files matched your search
@@ -681,7 +681,90 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.source-list li > span:first-child { display: inline-flex; }
|
||||
.source-list .muted { text-align: right; }
|
||||
|
||||
/* ---- Apprendimento (mockup 06) ---- */
|
||||
.learning-head { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); }
|
||||
.learning-state { display: flex; flex-direction: column; align-items: flex-start; gap: 14px; }
|
||||
.learning-state h2 { font-size: 26px; line-height: 34px; letter-spacing: -0.015em; }
|
||||
.learning-text { color: var(--text-2); font-size: 15px; line-height: 23px; max-width: 62ch; }
|
||||
.learning-progress { width: 100%; max-width: 560px; }
|
||||
.learning-progress .usage { height: 8px; border-radius: 4px; }
|
||||
.state-badge { display: inline-flex; align-items: center; gap: 8px; padding: 4px 12px; border-radius: 999px; background: var(--surface-2); color: var(--text); font-weight: 600; font-size: 13.5px; }
|
||||
.state-badge.on { background: var(--gain-bg); color: var(--gain); }
|
||||
.state-badge.warn { background: var(--attention-bg); color: var(--attention); }
|
||||
.learning-facts { margin: 0; display: flex; flex-direction: column; justify-content: center; }
|
||||
.learning-facts > div { padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||
.learning-facts > div:last-child { border-bottom: 0; }
|
||||
.learning-facts dt { color: var(--text-3); font-size: 13.5px; }
|
||||
.learning-facts dd { margin: 0; }
|
||||
.learning-facts dd strong { font-size: 16px; line-height: 24px; font-weight: 650; }
|
||||
.learning-facts .learning-precision { font-size: 30px; line-height: 38px; font-weight: 650; letter-spacing: -0.02em; }
|
||||
.learning-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; align-items: stretch; }
|
||||
.learning-row-wide { grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); }
|
||||
.learning-row .panel { padding: 24px 26px; display: flex; flex-direction: column; min-width: 0; }
|
||||
.learning-row .panel > h2 { margin-bottom: 4px; }
|
||||
.learning-open { align-items: start; gap: 28px; }
|
||||
.calibration { display: flex; flex-direction: column; margin-top: 12px; flex: 1; }
|
||||
.calibration-title, .calibration-foot { color: var(--text-2); font-size: 14px; }
|
||||
.calibration-foot { text-align: center; margin-right: 20%; }
|
||||
.calibration-box { position: relative; display: grid; grid-template-columns: 56px minmax(0, 1fr); height: 250px; margin: 14px 20% 0 0; }
|
||||
.calibration .chart-axis { display: block; }
|
||||
.calibration .base { stroke: var(--control); stroke-width: 1; }
|
||||
.calibration-x { position: relative; height: 30px; margin: 8px 20% 0 56px; color: var(--text-3); font-size: 13px; }
|
||||
.calibration-x span { position: absolute; transform: translateX(-50%); }
|
||||
.calibration .legend { margin-top: 20px; }
|
||||
.calibration-text { color: var(--text-2); margin-top: 12px; }
|
||||
.point-label { position: absolute; white-space: nowrap; font-size: 13.5px; font-weight: 650; pointer-events: none; }
|
||||
.point-label.below { transform: translate(12px, 8px); }
|
||||
.point-label.above { transform: translate(-100%, -24px); margin-left: -8px; }
|
||||
.point-label.under { transform: translate(-50%, 10px); }
|
||||
.hover-dot:hover { z-index: 2; }
|
||||
.hover-dot.quiet { opacity: 0; }
|
||||
.hover-dot.quiet:hover { opacity: 1; }
|
||||
.hover-box { display: none; position: absolute; bottom: 18px; left: 50%; transform: translateX(-50%); padding: 6px 10px; border-radius: 8px; background: var(--text); color: var(--surface); font-size: 13px; line-height: 18px; white-space: nowrap; font-weight: 500; }
|
||||
.hover-dot:hover .hover-box { display: block; }
|
||||
.weights { list-style: none; margin: 12px 0 0; padding: 0; }
|
||||
.weights li { display: grid; grid-template-columns: minmax(0, 215px) minmax(0, 1fr) 30px; gap: 16px; align-items: center; min-height: 31px; }
|
||||
.weights strong { text-align: right; font-variant-numeric: tabular-nums; font-weight: 650; }
|
||||
.weight-bar span { display: block; height: 11px; border-radius: 0 4px 4px 0; background: var(--text-2); min-width: 2px; }
|
||||
.weights .rest > span:first-child { color: var(--text-3); }
|
||||
.weights .rest .weight-bar span { background: var(--bench); }
|
||||
.weights-text { margin-top: auto; padding-top: 18px; }
|
||||
.versions { margin-top: 8px; }
|
||||
.versions thead td { border-bottom: 1px solid var(--rule); }
|
||||
.versions thead th { color: var(--text); font-weight: 650; font-size: 13.5px; border-bottom-color: var(--rule); }
|
||||
.versions th[scope="row"] { font-weight: 400; text-align: left; font-size: 13.5px; color: var(--text-2); }
|
||||
@media (min-width: 761px) { .versions thead th { white-space: nowrap; } }
|
||||
.learning-row .aside { margin-top: 16px; }
|
||||
.learning-row .aside strong { color: var(--text); }
|
||||
.learning-row .panel > .chart-table, .learning-row .panel > form { margin-top: 14px; }
|
||||
.learning-watch .panel-head { margin-bottom: 8px; }
|
||||
.learning-watch .aside { margin-top: auto; }
|
||||
.status-pill.gain { color: var(--gain); }
|
||||
.watch-list { list-style: none; margin: 0 0 14px; padding: 0; }
|
||||
.watch-list li { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-top: 1px solid var(--rule-inner); color: var(--text-2); }
|
||||
.watch-list .icon { margin-top: 2px; color: var(--text-3); }
|
||||
.watch-list .ok .icon { color: var(--gain); }
|
||||
.watch-list .warn, .watch-list .warn .icon { color: var(--attention); }
|
||||
.weekly { margin: 0 0 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); }
|
||||
.weekly-box { display: grid; grid-template-columns: minmax(0, 1fr) 76px; height: 84px; margin: 12px 0 4px 6px; }
|
||||
.weekly svg .bench { fill: none; stroke: var(--bench); stroke-width: 1; }
|
||||
.weekly svg .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
|
||||
.weekly .end-dot { width: 12px; height: 12px; margin: -6px 0 0 -6px; }
|
||||
.weekly-side { position: relative; font-size: 13px; }
|
||||
.weekly-side strong, .weekly-side span { position: absolute; left: 14px; line-height: 15px; white-space: nowrap; }
|
||||
.weekly-side strong { transform: translateY(-60%); font-weight: 650; }
|
||||
.weekly-side span { color: var(--text-3); transform: translateY(-20%); font-size: 12.5px; }
|
||||
.weekly-x { display: flex; justify-content: space-between; margin: 10px 76px 0 6px; }
|
||||
.found { list-style: none; margin: 0; padding: 0; }
|
||||
.found li { display: flex; flex-direction: column; gap: 5px; padding: 14px 0; border-bottom: 1px solid var(--rule); }
|
||||
.found li:last-child { border-bottom: 0; }
|
||||
.found strong { font-weight: 650; }
|
||||
.found-detail { color: var(--text-2); }
|
||||
.found .attention { font-size: 13px; }
|
||||
.learning-open .plain h3 { margin: 18px 0 4px; }
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.learning-row, .learning-row-wide { grid-template-columns: minmax(0, 1fr); }
|
||||
.overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.overview-row-wide, .journal-columns, .news-columns { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@@ -787,4 +870,14 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.news-panel > .panel-head .segmented { display: flex; width: 100%; }
|
||||
.news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
|
||||
.news-columns, .news-side { gap: 14px; }
|
||||
.learning-head { grid-template-columns: minmax(0, 1fr); }
|
||||
.learning-state h2 { font-size: 22px; line-height: 28px; }
|
||||
.learning-row { gap: 14px; }
|
||||
.learning-row .panel { padding: 18px; }
|
||||
.calibration-box { margin-right: 0; grid-template-columns: 42px minmax(0, 1fr); }
|
||||
.calibration-x { margin-right: 0; margin-left: 42px; }
|
||||
.calibration-foot { margin-right: 0; }
|
||||
.calibration .legend { flex-direction: row; }
|
||||
.weights li { grid-template-columns: minmax(0, 150px) minmax(0, 1fr) 26px; gap: 10px; }
|
||||
.chart-table summary { min-height: 44px; display: flex; align-items: center; }
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
@* How often it went well against what the model said (SPEC 13.4, mockup 06): one scale, 2 px lines, faint grid, the
|
||||
perfect estimate beside it, direct labels on the fullest band and on the last one, a box on hover and the table.
|
||||
As in EquityChart the lines are SVG stretched to the box; texts and points are HTML placed in percent. *@
|
||||
@if (Bands.Count > 0)
|
||||
{
|
||||
var loX = Bands.Min(b => b.From) / 10 * 10;
|
||||
var hiX = (Bands.Max(b => b.To) + 9) / 10 * 10;
|
||||
var loY = Math.Min(loX, (int)Math.Floor(Bands.Min(b => b.Observed)) / 10 * 10) - 5m;
|
||||
var hiY = Math.Max(hiX, Bands.Max(b => b.Observed)) + 4m;
|
||||
var step = hiX - loX > 60 ? 20 : 10;
|
||||
var fullest = Bands.MaxBy(b => b.Cases)!;
|
||||
var last = Bands[^1];
|
||||
decimal X(decimal v) => (v - loX) / (hiX - loX) * 1000m;
|
||||
decimal Y(decimal v) => (hiY - v) / (hiY - loY) * 1000m;
|
||||
<figure class="chart calibration" aria-label="Quanto spesso è andata bene, rispetto a quello che diceva il modello">
|
||||
<p class="calibration-title" aria-hidden="true">…va bene davvero</p>
|
||||
<div class="calibration-box">
|
||||
<div class="chart-axis" aria-hidden="true">
|
||||
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||
{
|
||||
<span style="top:@Pct(Y(t) / 10)">@t%</span>
|
||||
}
|
||||
</div>
|
||||
<div class="chart-plot">
|
||||
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||
@for (var t = (int)Math.Ceiling(loY / step) * step; t <= hiY; t += step)
|
||||
{
|
||||
<line class="grid" x1="0" x2="1000" y1="@Css(Y(t))" y2="@Css(Y(t))" vector-effect="non-scaling-stroke" />
|
||||
}
|
||||
<line class="base" x1="0" x2="1000" y1="1000" y2="1000" vector-effect="non-scaling-stroke" />
|
||||
<line class="bench" x1="0" y1="@Css(Y(loX))" x2="1000" y2="@Css(Y(hiX))" vector-effect="non-scaling-stroke" />
|
||||
<polyline class="equity" points="@string.Join(" ", Bands.Select(b => Css(X(b.Estimated)) + "," + Css(Y(b.Observed))))" vector-effect="non-scaling-stroke" />
|
||||
</svg>
|
||||
@foreach (var b in Bands)
|
||||
{
|
||||
<span class="end-dot hover-dot" style="left:@Pct(X(b.Estimated) / 10);top:@Pct(Y(b.Observed) / 10)"><span class="hover-box">Tra @(b.From)% e @(b.To)%<br />@Format.Number(b.Observed)% su @b.Cases casi</span></span>
|
||||
}
|
||||
<span class="point-label below" style="left:@Pct(X(fullest.Estimated) / 10);top:@Pct(Y(fullest.Observed) / 10)">@Label(fullest)</span>
|
||||
@if (last != fullest)
|
||||
{
|
||||
<span class="point-label above" style="left:@Pct(X(last.Estimated) / 10);top:@Pct(Y(last.Observed) / 10)">@Label(last)</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="calibration-x" aria-hidden="true">
|
||||
@for (var t = loX; t <= hiX; t += step)
|
||||
{
|
||||
<span style="left:@Pct(X(t) / 10)">@t%</span>
|
||||
}
|
||||
</div>
|
||||
<p class="calibration-foot" aria-hidden="true">Quando il modello dice…</p>
|
||||
<figcaption class="legend">
|
||||
<span class="key key-equity">Il modello</span>
|
||||
<span class="key key-bench">Stima perfetta</span>
|
||||
</figcaption>
|
||||
<p class="calibration-text">@Text</p>
|
||||
<details class="chart-table">
|
||||
<summary>Vedi i numeri in una tabella</summary>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Quando il modello dice</th><th scope="col" class="num">Casi</th><th scope="col" class="num">È andata bene</th><th scope="col">Affidabilità</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var b in Bands)
|
||||
{
|
||||
<tr><td>tra @(b.From)% e @(b.To)%</td><td class="num">@b.Cases</td><td class="num">@Format.Number(b.Observed)%</td><td class="@(b.Solid ? null : "attention-text")">@(b.Solid ? "conta" : "troppo pochi casi per contarci")</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</figure>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<LearningBand> Bands { get; set; } = [];
|
||||
|
||||
[Parameter]
|
||||
public string Text { get; set; } = "";
|
||||
|
||||
private static string Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {(b.Cases == 1 ? "un caso" : b.Cases + " casi")}";
|
||||
|
||||
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||
}
|
||||
@@ -89,6 +89,9 @@
|
||||
case "tick":
|
||||
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
||||
break;
|
||||
case "eye":
|
||||
<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z" /><circle cx="12" cy="12" r="2.8" />
|
||||
break;
|
||||
case "logout":
|
||||
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||
break;
|
||||
|
||||
@@ -1,5 +1,306 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/apprendimento"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@using Anubis.Learning
|
||||
|
||||
<PageTitle>Apprendimento · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
|
||||
@{
|
||||
var v = _view;
|
||||
var s = v.Summary;
|
||||
var c = _currency;
|
||||
}
|
||||
<p class="lead page-lead">Il modello impara dall'esito di ogni segnale.</p>
|
||||
@if (Ok == "promozione")
|
||||
{
|
||||
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />Promozione annullata: è tornata in carica la versione precedente.</p>
|
||||
}
|
||||
else if (Errore is not null)
|
||||
{
|
||||
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@(Errore == "motore" ? "Nella modalità dimostrativa non si cambia nulla." : "Non c'è nessuna promozione da annullare.")</p>
|
||||
}
|
||||
|
||||
<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>
|
||||
<h2 id="stato">@v.Title</h2>
|
||||
<p class="learning-text">@v.Text</p>
|
||||
@if (s.State != LearningStates.None)
|
||||
{
|
||||
<div class="limit learning-progress">
|
||||
@if (s.Signals < s.Needed)
|
||||
{
|
||||
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@s.Signals</strong> <span class="muted">su @s.Needed necessari</span></span></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@Format.Number(s.Signals)</strong> <span class="muted">(ne servivano @s.Needed)</span></span></div>
|
||||
}
|
||||
<span class="usage"><span style="width: @Css(Math.Min(100m, s.Signals * 100m / Math.Max(1, s.Needed)))%"></span></span>
|
||||
@if (v.Pace is { } pace)
|
||||
{
|
||||
<span class="note">@pace</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (v.Missing.Count > 0)
|
||||
{
|
||||
<ul class="checks">
|
||||
@foreach (var m in v.Missing)
|
||||
{
|
||||
<li class="wait"><Icon Name="clock" Size="16" />@m</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
@if (s.State == LearningStates.Manual)
|
||||
{
|
||||
<p><a href="/impostazioni#modello">Vai a Impostazioni</a></p>
|
||||
}
|
||||
</div>
|
||||
<dl class="half learning-facts">
|
||||
<div>
|
||||
<dt>Previsioni azzeccate su casi mai visti</dt>
|
||||
<dd class="learning-precision">@(s.Precision is { } precision ? precision + "%" : "—")</dd>
|
||||
<dd class="note">@(s.Precision is null ? "Si misura al primo addestramento" : "Tirando a caso sarebbe il 50%")</dd>
|
||||
</div>
|
||||
<div><dt>Ultimo addestramento</dt><dd><strong>@Capital(v.LastTraining)</strong></dd></div>
|
||||
<div><dt>@s.NextLabel</dt><dd><strong>@Capital(s.NextCheck)</strong></dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<div class="learning-row">
|
||||
<section class="panel" aria-labelledby="fiducia">
|
||||
<h2 id="fiducia">Ci si può fidare delle sue probabilità?</h2>
|
||||
@if (v.Bands.Count == 0)
|
||||
{
|
||||
<p class="note">@v.BandsText Qui vedrai quante volte va bene davvero quando il modello dice che una cosa è probabile.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">Più i punti stanno sulla linea, più la stima corrisponde ai fatti.@(v.BandsFromHistory ? " Per ora sono i casi storici che non aveva studiato: quelli dal vivo sono ancora troppo pochi." : "")</p>
|
||||
<CalibrationChart Bands="v.Bands" Text="@v.BandsText" />
|
||||
}
|
||||
</section>
|
||||
<section class="panel learning-weights" aria-labelledby="indizi">
|
||||
<h2 id="indizi">Cosa guarda di più</h2>
|
||||
@if (v.Champion is null)
|
||||
{
|
||||
<p class="note">Si vedrà con il primo modello.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">Quanto pesa ogni informazione nelle sue stime, su 100.</p>
|
||||
@if (v.Weights.Count > 0)
|
||||
{
|
||||
var most = v.Weights.Max(w => w.Share);
|
||||
<ul class="weights">
|
||||
@foreach (var w in v.Weights)
|
||||
{
|
||||
<li class="@(w.Rest ? "rest" : null)"><span>@w.Name</span><span class="weight-bar" aria-hidden="true"><span style="width: @Css(w.Share * 100m / most)%"></span></span><strong>@w.Share</strong></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<p class="note weights-text">@v.WeightsText</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="learning-row learning-row-wide">
|
||||
<section class="panel" aria-labelledby="versioni">
|
||||
<h2 id="versioni">Il modello in carica e lo sfidante</h2>
|
||||
<p class="note">Lo sfidante gira in ombra accanto al modello in carica. Ne prende il posto solo se è chiaramente migliore.</p>
|
||||
@if (v.Champion is { } now)
|
||||
{
|
||||
var other = v.Challenger;
|
||||
var same = other is null || other.GainWithout == now.GainWithout;
|
||||
<div class="table-wrap">
|
||||
<table class="table versions">
|
||||
<thead><tr><td></td><th scope="col" class="num">In carica, versione @now.Version</th>@if (other is not null){<th scope="col" class="num">Sfidante, versione @other.Version</th>}</tr></thead>
|
||||
<tbody>
|
||||
<tr><th scope="row">Addestrato</th><td class="num">@now.Trained</td>@if (other is not null){<td class="num">@other.Trained</td>}</tr>
|
||||
<tr><th scope="row">Casi studiati</th><td class="num">@Format.Number(now.Examples)</td>@if (other is not null){<td class="num">@Format.Number(other.Examples)</td>}</tr>
|
||||
<tr><th scope="row">Previsioni azzeccate su casi mai visti</th><td class="num"><strong>@Share(now.Precision)</strong></td>@if (other is not null){<td class="num"><strong>@Share(other.Precision)</strong></td>}</tr>
|
||||
<tr><th scope="row">Errore sulle probabilità <span class="muted">(più basso è meglio)</span></th><td class="num">@Error(now.Error)</td>@if (other is not null){<td class="num">@Error(other.Error)</td>}</tr>
|
||||
<tr><th scope="row">Guadagno medio per operazione se filtrasse lui @if (same && now.GainWithout is { } without){<span class="muted">(senza filtro: @Shell.Money(without, c, withSign: true))</span>}</th>
|
||||
<td class="num">@Gain(now, same, c)</td>@if (other is not null){<td class="num">@Gain(other, same, c)</td>}</tr>
|
||||
@if (other is not null)
|
||||
{
|
||||
<tr><th scope="row">Casi di confronto diretto</th><td class="num muted">non serve</td><td class="num">@v.Pairs su @v.PairsNeeded</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
<p class="aside"><strong>@v.TrialTitle</strong> @v.TrialText</p>
|
||||
@if (v.Choice is { } choice)
|
||||
{
|
||||
<details class="chart-table">
|
||||
<summary>Come è stato scelto il modello in carica</summary>
|
||||
<p class="note">@choice Sono tutte prove su casi che il modello non aveva studiato; contano anche quelle scartate.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Tipo di modello</th><th scope="col" class="num">Previsioni azzeccate</th><th scope="col" class="num">Errore</th><th scope="col" class="num">Guadagno per operazione</th><th scope="col">Esito</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var a in v.Attempts)
|
||||
{
|
||||
<tr><td>@a.Learner</td><td class="num">@Share(a.Precision)</td><td class="num">@Error(a.Error)</td><td class="num nowrap">@Shell.Money(a.Gain, c, withSign: true)</td><td>@(a.Chosen ? "scelto" : "non scelto")</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
@if (v.UndoTo is { } back && !Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<button class="btn" type="submit" data-confirm="Torna in carica la versione @back e la versione @v.Champion!.Version viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||
<span class="hint">Tornerebbe in carica la versione @back.</span>
|
||||
</form>
|
||||
}
|
||||
</section>
|
||||
<section class="panel learning-watch" aria-labelledby="sorveglianza">
|
||||
<div class="panel-head">
|
||||
<h2 id="sorveglianza">Sorveglianza</h2>
|
||||
@if (v.Checked)
|
||||
{
|
||||
<span class="status-pill @(v.Anomaly ? "attention" : "gain")"><Icon Name="@(v.Anomaly ? "alert" : "check")" Size="16" />@(v.Anomaly ? "Anomalia" : "Nessuna anomalia")</span>
|
||||
}
|
||||
</div>
|
||||
@if (!v.Checked)
|
||||
{
|
||||
<p class="note">Il controllo gira ogni notte alle 03:00: confronta le stime con gli esiti e il mercato di oggi con quello su cui ha studiato.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="watch-list">
|
||||
@foreach (var check in v.Checks)
|
||||
{
|
||||
<li class="@check.State"><Icon Name="@(check.State switch { "ok" => "tick", "warn" => "alert", _ => "clock" })" Size="16" /><span>@check.Text</span></li>
|
||||
}
|
||||
</ul>
|
||||
<WeeklyPrecision Weeks="v.Weeks" />
|
||||
}
|
||||
<p class="aside">Se la precisione cala, il modello viene messo da parte da solo e le strategie proseguono senza di lui.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="learning-row learning-open">
|
||||
<section class="plain" aria-labelledby="imparato">
|
||||
<h2 id="imparato">Cosa ha imparato finora</h2>
|
||||
@if (v.Found.Count == 0)
|
||||
{
|
||||
<p class="note">Ancora niente: le relazioni tra indizi ed esiti si cercano ogni notte, quando i casi bastano per un confronto.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="found">
|
||||
@foreach (var d in v.Found)
|
||||
{
|
||||
<li>
|
||||
<strong>@d.Title</strong>
|
||||
<span class="found-detail">@d.Detail</span>
|
||||
<span class="@(d.Cases < 20 ? "attention" : "note")">@if (d.Cases < 20){<Icon Name="alert" Size="16" />}@(d.Cases == 1 ? "Un caso" : Format.Number(d.Cases) + " casi"): @d.Trust</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
@if (v.News.Count > 0)
|
||||
{
|
||||
<h3>Cosa succede ai prezzi dopo una notizia</h3>
|
||||
<p class="note">Rendimento medio dalla prima chiusura dopo la notizia. È solo un'informazione: non cambia nessuna regola.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Tipo di notizia</th><th scope="col" class="num">Dopo 1 giorno</th><th scope="col" class="num">Dopo 5 giorni</th><th scope="col">Casi</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var n in v.News)
|
||||
{
|
||||
<tr><td>@NewsEventNames.Label(n.Kind)</td><td class="num">@Move(n.OneDay)</td><td class="num">@Move(n.FiveDays)</td><td class="@(n.Cases < 20 ? "attention-text" : null)">@n.Cases: @n.Trust</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
<section class="plain" aria-labelledby="storia">
|
||||
<h2 id="storia">Storia</h2>
|
||||
@if (v.Story.Count == 0)
|
||||
{
|
||||
<p class="note">La storia comincia con il primo modello.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<dl class="events">
|
||||
@foreach (var e in v.Story.Take(LearningView.StoryRows))
|
||||
{
|
||||
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (v.Story.Count > LearningView.StoryRows)
|
||||
{
|
||||
<details class="chart-table">
|
||||
<summary>Mostra i @(v.Story.Count - LearningView.StoryRows) eventi precedenti</summary>
|
||||
<dl class="events">
|
||||
@foreach (var e in v.Story.Skip(LearningView.StoryRows))
|
||||
{
|
||||
<dt>@e.When</dt><dd>@e.Text</dd>
|
||||
}
|
||||
</dl>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private LearningView _view = null!;
|
||||
private string _currency = "EUR";
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ok")]
|
||||
public string? Ok { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "errore")]
|
||||
public string? Errore { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||
_currency = Shell.Effective((await Host.Services!.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||
_view = await LearningView.LoadAsync(Host, Shell, ct);
|
||||
}
|
||||
|
||||
private string Gain(LearningVersion version, bool same, string currency) => version.Gain is not { } gain ? "—"
|
||||
: Shell.Money(gain, currency, withSign: true) + (same || version.GainWithout is not { } without ? "" : $" (senza: {Shell.Money(without, currency, withSign: true)})");
|
||||
|
||||
private static string Badge(string state) => state switch
|
||||
{
|
||||
LearningStates.None => "Non ancora partito",
|
||||
LearningStates.Active => "Attivo",
|
||||
LearningStates.Aside => "Messo da parte",
|
||||
LearningStates.Manual => "Messo da parte da te",
|
||||
_ => "In osservazione",
|
||||
};
|
||||
|
||||
private static string BadgeIcon(string state) => state switch
|
||||
{
|
||||
LearningStates.None => "clock",
|
||||
LearningStates.Active => "check",
|
||||
LearningStates.Aside => "alert",
|
||||
LearningStates.Manual => "pause",
|
||||
_ => "eye",
|
||||
};
|
||||
|
||||
private static string Share(int? points) => points is { } p ? p + "%" : "—";
|
||||
|
||||
private static string Error(decimal? value) => value is { } e ? Format.Number(e, 3) : "—";
|
||||
|
||||
private static string Move(double value) => Format.Percent((decimal)Math.Round(value * 100, 2), 2, withSign: true);
|
||||
|
||||
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||
|
||||
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -31,6 +31,8 @@
|
||||
"fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.",
|
||||
"chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.",
|
||||
"chiave-tolta" => "Chiave tolta.",
|
||||
"apprendimento" => "Impostazioni del modello salvate: valgono dalla prossima decisione.",
|
||||
"promozione" => "Promozione annullata: è tornata in carica la versione precedente.",
|
||||
|
||||
_ => "Fatto.",
|
||||
})</p>
|
||||
@@ -41,7 +43,7 @@
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#modello">Modello</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
@@ -405,6 +407,55 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel" id="modello">
|
||||
<h2>Modello</h2>
|
||||
<p class="hint">Il modello non compra mai e non ingrandisce niente: quando avrà superato le sue prove potrà solo rimpicciolire, o non fare, un acquisto che giudica debole. Quanto debole lo decidi qui, in punti di probabilità sotto la frequenza con cui la strategia guadagna di solito. <a href="/apprendimento">Cosa sta facendo</a></p>
|
||||
<form method="post" action="/azioni/modello" class="form-grid">
|
||||
<AntiforgeryToken />
|
||||
@foreach (var m in _model)
|
||||
{
|
||||
var definition = SettingsStore.Definition(m.Key);
|
||||
<label>@ModelLabel(m.Key)
|
||||
<select name="@m.Key" disabled="@(m.ReadOnly || Shell.IsDemo)">
|
||||
@foreach (var choice in definition.Allowed!)
|
||||
{
|
||||
<option value="@choice" selected="@(choice == m.Value)">@ModelChoice(m.Key, choice)</option>
|
||||
}
|
||||
</select>
|
||||
@if (m.ReadOnly)
|
||||
{
|
||||
<span class="hint">Fissato da @m.Source: si cambia lì.</span>
|
||||
}
|
||||
</label>
|
||||
}
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
@if (_anyLive)
|
||||
{
|
||||
<p class="note">Una strategia usa soldi veri: per rimpicciolire meno, o mettere da parte il modello, 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" type="submit">Salva</button>
|
||||
}
|
||||
</form>
|
||||
<h3>Ultima promozione</h3>
|
||||
@if (_undoTo is { } undo)
|
||||
{
|
||||
<form method="post" action="/azioni/modello/annulla-promozione" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni" />
|
||||
<button class="btn" type="submit" data-confirm="Torna in carica la versione @undo e quella di adesso viene tolta. Continuare?">Annulla l'ultima promozione</button>
|
||||
<span class="hint">Tornerebbe in carica la versione @undo.</span>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">Nessuna promozione da annullare.</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="sicurezza">
|
||||
<h2>Sicurezza</h2>
|
||||
@if (Shell.IsDemo)
|
||||
@@ -536,6 +587,8 @@
|
||||
|
||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||
private readonly List<SettingValue> _newsRules = [];
|
||||
private readonly List<SettingValue> _model = [];
|
||||
private int? _undoTo;
|
||||
private readonly Dictionary<string, SettingValue> _llm = [];
|
||||
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
|
||||
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
|
||||
@@ -573,6 +626,12 @@
|
||||
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
||||
}
|
||||
|
||||
foreach (var setting in Anubis.Learning.LearningSettings.All)
|
||||
{
|
||||
_model.Add(await services.Settings.GetAsync(setting.Key, ct));
|
||||
}
|
||||
|
||||
_undoTo = Shell.IsDemo ? null : await new Anubis.Learning.ModelStore(services.Db).UndoToAsync(ct);
|
||||
foreach (var setting in Anubis.News.NewsModelSettings.All)
|
||||
{
|
||||
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
|
||||
@@ -656,6 +715,7 @@
|
||||
"fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.",
|
||||
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
|
||||
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
|
||||
"promozione" => "Non c'è nessuna promozione da annullare.",
|
||||
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
|
||||
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
|
||||
|
||||
@@ -705,6 +765,13 @@
|
||||
</form>;
|
||||
}
|
||||
|
||||
private static string ModelLabel(string key) => key == Anubis.Learning.LearningSettings.Full.Key ? "Acquisto intero fino a"
|
||||
: key == Anubis.Learning.LearningSettings.Zero.Key ? "Nessun acquisto da" : "Il modello";
|
||||
|
||||
private static string ModelChoice(string key, string choice) => key == Anubis.Learning.LearningSettings.Aside.Key
|
||||
? choice == "on" ? "Messo da parte: non conta" : "Al suo posto"
|
||||
: choice == "0" ? "Solo alla frequenza di sempre o sopra" : choice + " punti sotto";
|
||||
|
||||
private static string ProviderName(string provider) => provider switch
|
||||
{
|
||||
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
|
||||
|
||||
@@ -364,19 +364,23 @@
|
||||
</section>
|
||||
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
|
||||
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
|
||||
@if (p.Learning is not { } m)
|
||||
@{ var m = p.Learning; }
|
||||
<p><strong>@m.Sentence</strong></p>
|
||||
@if (m.State == LearningStates.Observation)
|
||||
{
|
||||
<p class="note">L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p><strong>Il modello osserva e impara, ma non decide ancora.</strong></p>
|
||||
<div class="limit">
|
||||
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
|
||||
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
|
||||
</div>
|
||||
}
|
||||
@if (m.State == LearningStates.None)
|
||||
{
|
||||
<p class="note">@m.NextLabel: @m.NextCheck.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<dl class="tile-facts">
|
||||
<dt>Previsioni azzeccate</dt><dd>@m.Precision% su dati mai visti</dd>
|
||||
<dt>Previsioni azzeccate</dt><dd>@(m.Precision is { } hit ? $"{hit}% su dati mai visti" : "non ancora misurate")</dd>
|
||||
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
|
||||
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
|
||||
</dl>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
@* The precision of the model week by week with the alarm line (SPEC 13.6, mockup 06). Weeks without enough cases leave no
|
||||
point; the days on the axis keep the distance between the others. *@
|
||||
@if (Weeks.Count >= 2)
|
||||
{
|
||||
var alarm = (decimal)(Anubis.Learning.Health.Alarm * 100);
|
||||
var lo = Math.Min(Weeks.Min(w => w.Precision), alarm) - 4m;
|
||||
var hi = Math.Max(Weeks.Max(w => w.Precision), alarm) + 4m;
|
||||
var (first, last) = (Weeks[0], Weeks[^1]);
|
||||
var lowest = Weeks.MinBy(w => w.Precision)!;
|
||||
decimal X(LearningWeek w) => (w.Monday.DayNumber - first.Monday.DayNumber) * 1000m / (last.Monday.DayNumber - first.Monday.DayNumber);
|
||||
decimal Y(decimal v) => (hi - v) / (hi - lo) * 1000m;
|
||||
<figure class="weekly" aria-label="Precisione settimana per settimana">
|
||||
<figcaption class="note">Precisione settimana per settimana</figcaption>
|
||||
<div class="weekly-box">
|
||||
<div class="chart-plot">
|
||||
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||
<line class="bench" x1="0" x2="1000" y1="@Css(Y(alarm))" y2="@Css(Y(alarm))" vector-effect="non-scaling-stroke" />
|
||||
<polyline class="equity" points="@string.Join(" ", Weeks.Select(w => Css(X(w)) + "," + Css(Y(w.Precision))))" vector-effect="non-scaling-stroke" />
|
||||
</svg>
|
||||
@foreach (var w in Weeks)
|
||||
{
|
||||
<span class="end-dot hover-dot @(w == last || w == lowest ? null : "quiet")" style="left:@Pct(X(w) / 10);top:@Pct(Y(w.Precision) / 10)"><span class="hover-box">Settimana del @Day(w.Monday)<br />@w.Precision%</span></span>
|
||||
}
|
||||
@if (lowest != last)
|
||||
{
|
||||
<span class="point-label under" style="left:@Pct(X(lowest) / 10);top:@Pct(Y(lowest.Precision) / 10)">@lowest.Precision%</span>
|
||||
}
|
||||
</div>
|
||||
<div class="weekly-side" aria-hidden="true">
|
||||
<strong style="top:@Pct(Math.Min(Y(last.Precision), Y(alarm) - 300m) / 10)">@last.Precision%</strong>
|
||||
<span style="top:@Pct(Y(alarm) / 10)">allarme<br />sotto @Format.Number(alarm)%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="weekly-x note" aria-hidden="true"><span>@Day(first.Monday)</span><span>@Day(last.Monday)</span></div>
|
||||
<details class="chart-table">
|
||||
<summary>Vedi i numeri in una tabella</summary>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Settimana dal lunedì</th><th scope="col" class="num">Precisione</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var w in Weeks.Reverse())
|
||||
{
|
||||
<tr><td>@Format.LongDate(w.Monday)</td><td class="num">@w.Precision%</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</figure>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<LearningWeek> Weeks { get; set; } = [];
|
||||
|
||||
private static string Day(DateOnly day) => day.ToString("d MMM", CultureInfo.GetCultureInfo("it-IT"));
|
||||
|
||||
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Pct(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
|
||||
}
|
||||
@@ -140,6 +140,12 @@ internal static partial class Endpoints
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||
}
|
||||
|
||||
// The same for what lets the model shrink less.
|
||||
if (Anubis.Learning.LearningSettings.All.Any(d => d.Key == key))
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||
}
|
||||
|
||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ internal static partial class Forms
|
||||
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
|
||||
signed.MapPost("/laboratorio", PlanTrialAsync);
|
||||
signed.MapPost("/stime-di-costo/{id:guid}/{choice}", DecideCostAsync);
|
||||
signed.MapPost("/modello", SetModelAsync);
|
||||
signed.MapPost("/modello/annulla-promozione", UndoPromotionAsync);
|
||||
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
||||
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
||||
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
||||
@@ -783,6 +785,66 @@ internal static partial class Forms
|
||||
return Results.Redirect(done ? "/laboratorio#stime" : "/laboratorio?errore=stima#stime");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The thresholds of the multiplier and the manual set-aside (SPEC 13.5), all at once. A choice that lets operations be
|
||||
/// bigger while a strategy has real money needs the phrase and the password, like a risk limit (SPEC 12.4).
|
||||
/// </summary>
|
||||
private static async Task<IResult> SetModelAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#modello");
|
||||
}
|
||||
|
||||
var current = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var definition in Anubis.Learning.LearningSettings.All)
|
||||
{
|
||||
var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false);
|
||||
current[definition.Key] = value.Value;
|
||||
var chosen = form[definition.Key].ToString();
|
||||
if (value.ReadOnly || chosen.Length == 0)
|
||||
{
|
||||
next[definition.Key] = value.Value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!definition.Allowed!.Contains(chosen, StringComparer.Ordinal))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=impostazione#modello");
|
||||
}
|
||||
|
||||
next[definition.Key] = chosen;
|
||||
}
|
||||
|
||||
if (Anubis.Learning.LearningSettings.Raised(k => current[k], k => next[k]) && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=" + refusal + "#modello");
|
||||
}
|
||||
|
||||
var by = context.User.Identity?.Name ?? "utente";
|
||||
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
|
||||
{
|
||||
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return Results.Redirect(back + "?ok=apprendimento#modello");
|
||||
}
|
||||
|
||||
/// <summary>One click takes back the last promotion (SPEC 11.4).</summary>
|
||||
private static async Task<IResult> UndoPromotionAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
|
||||
{
|
||||
var (page, anchor) = Back(form, "/apprendimento") == "/impostazioni" ? ("/impostazioni", "#modello") : ("/apprendimento", "");
|
||||
if (host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(page + "?errore=motore" + anchor);
|
||||
}
|
||||
|
||||
var done = await Anubis.Learning.LearningCycle.UndoPromotionAsync(services.Db, host.Clock, ct).ConfigureAwait(false);
|
||||
return Results.Redirect(page + (done ? "?ok=promozione" : "?errore=promozione") + anchor);
|
||||
}
|
||||
|
||||
private static DateOnly? ParseDay(string text) =>
|
||||
DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null;
|
||||
|
||||
|
||||
@@ -0,0 +1,545 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Learning;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>What the model is doing, for the badge and the sentences at the top.</summary>
|
||||
internal static class LearningStates
|
||||
{
|
||||
/// <summary>No model yet: the night after the first start prepares it.</summary>
|
||||
public const string None = "none";
|
||||
|
||||
public const string Observation = "observation";
|
||||
public const string Active = "active";
|
||||
|
||||
/// <summary>Set aside on its own by the nightly check.</summary>
|
||||
public const string Aside = "aside";
|
||||
|
||||
/// <summary>Set aside by the user.</summary>
|
||||
public const string Manual = "manual";
|
||||
}
|
||||
|
||||
/// <summary>A band of estimates: percentages as they are read, the point at the mean estimate.</summary>
|
||||
public sealed record LearningBand(int From, int To, int Cases, decimal Estimated, decimal Observed)
|
||||
{
|
||||
public bool Solid => Cases >= Judge.BandMin;
|
||||
}
|
||||
|
||||
internal sealed record LearningWeight(string Name, int Share, bool Rest);
|
||||
|
||||
/// <summary>A column of the comparison between the model in charge and the one on trial.</summary>
|
||||
internal sealed record LearningVersion(int Version, string Trained, int Examples, int? Precision, decimal? Error, decimal? Gain, decimal? GainWithout);
|
||||
|
||||
/// <summary>What was tried when a model was trained, the chosen one included.</summary>
|
||||
internal sealed record LearningAttempt(string Learner, int? Precision, decimal Error, decimal Gain, bool Chosen);
|
||||
|
||||
public sealed record LearningWeek(DateOnly Monday, int Precision);
|
||||
|
||||
/// <summary>A line of "Sorveglianza": <paramref name="State"/> is ok, warn or wait.</summary>
|
||||
internal sealed record LearningCheck(string State, string Text);
|
||||
|
||||
internal sealed record LearningStory(string When, string Text);
|
||||
|
||||
/// <summary>The model box of the Panoramica: the same state in few words.</summary>
|
||||
internal sealed record LearningSummary(string State, int Signals, int Needed, int? Precision, string Trained, string NextLabel, string NextCheck)
|
||||
{
|
||||
public string Sentence => State switch
|
||||
{
|
||||
LearningStates.None => "Il modello non è ancora pronto: comincia a osservare dopo la prima verifica.",
|
||||
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.",
|
||||
_ => "Il modello osserva e impara, ma non decide ancora.",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Apprendimento screen (SPEC 13.6, mockup 06): what the model is doing, whether its probabilities can be trusted,
|
||||
/// what it looks at, the model in charge against the challenger, the watch, the discoveries and the history. In demo mode
|
||||
/// the numbers of appendix F.7 come from the aggregates.
|
||||
/// </summary>
|
||||
internal sealed record LearningView
|
||||
{
|
||||
/// <summary>The clues named one by one; the others are "Tutto il resto".</summary>
|
||||
public const int NamedWeights = 9;
|
||||
|
||||
public const int StoryRows = 12;
|
||||
|
||||
private const string Fear = "Paura o avidità";
|
||||
|
||||
/// <summary>The pace is measured on the last four weeks, and needs at least one.</summary>
|
||||
private const int PaceDays = 28;
|
||||
|
||||
private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
private static readonly string[] _numbers = ["zero", "una", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici"];
|
||||
|
||||
public required LearningSummary Summary { get; init; }
|
||||
|
||||
public required string Title { get; init; }
|
||||
|
||||
public required string Text { get; init; }
|
||||
|
||||
public string? Pace { get; init; }
|
||||
|
||||
/// <summary>With 300 signals done, what still stops it from counting.</summary>
|
||||
public IReadOnlyList<string> Missing { get; init; } = [];
|
||||
|
||||
/// <summary>"domenica 4 ottobre, versione 3".</summary>
|
||||
public required string LastTraining { get; init; }
|
||||
|
||||
public IReadOnlyList<LearningBand> Bands { get; init; } = [];
|
||||
|
||||
/// <summary>The sentence under the calibration chart.</summary>
|
||||
public string BandsText { get; init; } = "";
|
||||
|
||||
/// <summary>True when the bands are those of the verification on the history, because the live ones are still too few.</summary>
|
||||
public bool BandsFromHistory { get; init; }
|
||||
|
||||
public IReadOnlyList<LearningWeight> Weights { get; init; } = [];
|
||||
|
||||
public string WeightsText { get; init; } = "";
|
||||
|
||||
public LearningVersion? Champion { get; init; }
|
||||
|
||||
public LearningVersion? Challenger { get; init; }
|
||||
|
||||
/// <summary>The signals both estimated, with their outcome, and how many the next decision needs.</summary>
|
||||
public int Pairs { get; init; }
|
||||
|
||||
public int PairsNeeded { get; init; }
|
||||
|
||||
public string TrialTitle { get; init; } = "";
|
||||
|
||||
public string TrialText { get; init; } = "";
|
||||
|
||||
/// <summary>How the model in charge was chosen, with everything that was tried.</summary>
|
||||
public string? Choice { get; init; }
|
||||
|
||||
public IReadOnlyList<LearningAttempt> Attempts { get; init; } = [];
|
||||
|
||||
/// <summary>Set when the last promotion can be taken back: the version that would return.</summary>
|
||||
public int? UndoTo { get; init; }
|
||||
|
||||
public bool Anomaly { get; init; }
|
||||
|
||||
public bool Checked { get; init; }
|
||||
|
||||
public IReadOnlyList<LearningCheck> Checks { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<LearningWeek> Weeks { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<LearningStory> Story { get; init; } = [];
|
||||
|
||||
// ---- Panoramica ---------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The few numbers of the Panoramica.</summary>
|
||||
public static async Task<LearningSummary> SummaryAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
using var aggregates = shell.Aggregates();
|
||||
if (aggregates is not null)
|
||||
{
|
||||
return DemoSummary(aggregates.RootElement.GetProperty("apprendimento"));
|
||||
}
|
||||
|
||||
var services = host.Services!;
|
||||
var desk = new LearningDesk(services.Db, host.Clock, services.Settings);
|
||||
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);
|
||||
}
|
||||
|
||||
private static LearningSummary Summarise(IReadOnlyList<ModelRow> models, int evaluated, CycleState state, bool aside, DateTimeOffset now)
|
||||
{
|
||||
var champion = models.LastOrDefault(m => m.Status == ModelStatuses.Champion);
|
||||
var challenger = models.LastOrDefault(m => m.Status == ModelStatuses.Challenger);
|
||||
var last = models.LastOrDefault(m => m.Version is not null);
|
||||
var status = champion is null ? LearningStates.None
|
||||
: aside ? LearningStates.Manual
|
||||
: state.Aside is not null ? LearningStates.Aside
|
||||
: state.ActivatedAt is not null ? LearningStates.Active
|
||||
: LearningStates.Observation;
|
||||
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : Format.Day(DayOf(last.TrainedAt)),
|
||||
champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null));
|
||||
}
|
||||
|
||||
private static LearningSummary DemoSummary(JsonElement demo) => new(demo.GetProperty("stato").GetString()!, demo.GetProperty("segnali").GetInt32(), demo.GetProperty("necessari").GetInt32(),
|
||||
demo.GetProperty("precisione_pct").GetInt32(), demo.GetProperty("ultimo_addestramento").GetString()!, "Prossima verifica dello sfidante", demo.GetProperty("prossima_verifica").GetString()!);
|
||||
|
||||
// ---- Page ---------------------------------------------------------------------------------------------------
|
||||
|
||||
public static async Task<LearningView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
using var aggregates = shell.Aggregates();
|
||||
if (aggregates is not null)
|
||||
{
|
||||
return Demo(aggregates.RootElement.GetProperty("apprendimento"));
|
||||
}
|
||||
|
||||
var services = host.Services!;
|
||||
var clock = host.Clock;
|
||||
var desk = new LearningDesk(services.Db, clock, services.Settings);
|
||||
var snapshot = await LearningSnapshot.LoadAsync(desk, cancellationToken).ConfigureAwait(false);
|
||||
var capitals = await LearningCycle.CapitalsAsync(services.Db, clock, cancellationToken).ConfigureAwait(false);
|
||||
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, desk.BaseRates, capitals, aside, found, events, clock.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>The page from what was read, without touching the database.</summary>
|
||||
public static LearningView Of(LearningSnapshot snapshot, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capitals, bool aside, DiscoverySet discoveries,
|
||||
IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||
{
|
||||
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 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 live = activation.Scores.Bands;
|
||||
var history = !live.Any(b => b.Cases >= Judge.BandMin);
|
||||
var verified = Verified(champion);
|
||||
var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList();
|
||||
var view = new LearningView
|
||||
{
|
||||
Summary = summary,
|
||||
Title = title,
|
||||
Text = text,
|
||||
Pace = state.ActivatedAt is null && champion is not null ? PaceText(inCharge, now) : null,
|
||||
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
|
||||
LastTraining = last is null ? "mai" : $"{Format.Day(DayOf(last.TrainedAt))}, versione {last.Version}",
|
||||
Bands = bands,
|
||||
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
|
||||
BandsFromHistory = history && bands.Count > 0,
|
||||
Champion = Column(champion, now),
|
||||
Challenger = Column(challenger, now),
|
||||
Choice = champion?.Report.Reason is { Length: > 0 } reason ? reason : null,
|
||||
Attempts = champion is null ? [] :
|
||||
[
|
||||
.. champion.Report.Attempts.Select(a =>
|
||||
new LearningAttempt(LearnerNames.Label(a.Learner), Points(a.Combined.Precision), Round(a.Combined.Brier, 3), Round(a.Combined.GainWith, 2), a.Chosen)),
|
||||
],
|
||||
UndoTo = champion?.ReplacedId is { } replaced ? snapshot.Models.FirstOrDefault(m => m.Id == replaced && m.Status == ModelStatuses.Retired)?.Version : null,
|
||||
Anomaly = state.Aside is not null,
|
||||
Checked = state.Health is not null,
|
||||
Found = discoveries.Found,
|
||||
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() ?? []);
|
||||
if (champion is not null)
|
||||
{
|
||||
view = view with
|
||||
{
|
||||
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Points(w.Precision)!.Value))],
|
||||
Checks = state.Health is { } health ? ChecksOf(health, snapshot, champion, verified, events, now) : [],
|
||||
};
|
||||
}
|
||||
|
||||
return champion is not null && challenger is not null
|
||||
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), champion.Version, challenger.Version)
|
||||
: view with
|
||||
{
|
||||
TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.",
|
||||
TrialText = champion is null ? "" : $"Il prossimo si addestra {At(summary.NextCheck)}, se nel frattempo ci sono casi nuovi.",
|
||||
};
|
||||
}
|
||||
|
||||
private static (string Title, string Text) Words(LearningSummary summary, CycleState state, DateTimeOffset now)
|
||||
{
|
||||
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.";
|
||||
const string Alone = "Le strategie proseguono senza di lui.";
|
||||
return summary.State switch
|
||||
{
|
||||
LearningStates.None => ("Non ha ancora cominciato.", $"{How} La prima verifica, {At(summary.NextCheck)}, prepara il primo modello dai dati storici; da lì parte in osservazione."),
|
||||
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" : "")}."),
|
||||
LearningStates.Manual => ("L'hai messo da parte tu.", $"{Alone} Continua a stimare e a imparare, ma non cambia nessuna operazione. 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}"),
|
||||
_ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>How long the missing signals take at the pace of the last four weeks.</summary>
|
||||
public static string? PaceText(IReadOnlyList<Estimate> inCharge, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(inCharge);
|
||||
var missing = ActivationCheck.Needed - inCharge.Count;
|
||||
if (missing <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var today = DayOf(now);
|
||||
if (inCharge.Count == 0 || (today.DayNumber - inCharge.Min(e => e.Case.Label!.ClosedDay!.Value).DayNumber) is not (>= 7 and var seen))
|
||||
{
|
||||
return "È presto per dire quanto manca.";
|
||||
}
|
||||
|
||||
var days = Math.Min(PaceDays, seen);
|
||||
var recent = inCharge.Count(e => e.Case.Label!.ClosedDay!.Value > today.AddDays(-days));
|
||||
return recent == 0 ? "Nelle ultime settimane nessun segnale si è concluso." : PaceWords(missing * days / 7.0 / recent);
|
||||
}
|
||||
|
||||
/// <summary>"Al ritmo attuale, tra tre e quattro settimane." from the weeks that are missing.</summary>
|
||||
public static string PaceWords(double weeks)
|
||||
{
|
||||
if (weeks <= 1)
|
||||
{
|
||||
return "Al ritmo attuale, meno di una settimana.";
|
||||
}
|
||||
|
||||
if (weeks > 52)
|
||||
{
|
||||
return "Al ritmo attuale, più di un anno.";
|
||||
}
|
||||
|
||||
if (weeks > 12)
|
||||
{
|
||||
return string.Create(_it, $"Al ritmo attuale, circa {Math.Round(weeks / 4.345):0} mesi.");
|
||||
}
|
||||
|
||||
var (low, high) = ((int)Math.Floor(weeks), (int)Math.Ceiling(weeks));
|
||||
return low == high ? $"Al ritmo attuale, circa {_numbers[low]} settimane." : $"Al ritmo attuale, tra {_numbers[low]} e {_numbers[high]} settimane.";
|
||||
}
|
||||
|
||||
private static List<string> Missings(ActivationCheck check)
|
||||
{
|
||||
var missing = new List<string>();
|
||||
if (!check.Calibrated)
|
||||
{
|
||||
missing.Add(check.CalibrationError is { } error
|
||||
? string.Create(_it, $"Le probabilità non sono ancora ben tarate: sbagliano in media di {error * 100:0.0} punti, il massimo è {ActivationCheck.MaxCalibrationError * 100:0}.")
|
||||
: $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi.");
|
||||
}
|
||||
|
||||
if (!check.Improves)
|
||||
{
|
||||
missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso.");
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
// ---- Calibration and clues ----------------------------------------------------------------------------------
|
||||
|
||||
private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1));
|
||||
|
||||
/// <summary>The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not count.</summary>
|
||||
public static string BandsWords(IReadOnlyList<LearningBand> bands)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bands);
|
||||
var solid = bands.Where(b => b.Solid).ToList();
|
||||
if (solid.Count == 0)
|
||||
{
|
||||
return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci.";
|
||||
}
|
||||
|
||||
var error = solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
|
||||
var best = solid[^1];
|
||||
var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " +
|
||||
(error < (decimal)ActivationCheck.MaxCalibrationError * 100 ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
|
||||
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
|
||||
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
|
||||
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
|
||||
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : cases.ToString(_it) + " casi, troppo pochi")} per contarci.";
|
||||
return text + (above.Count > 0 ? Few($"Sopra il {best.To}%", above.Sum(b => b.Cases)) : "") + (below.Count > 0 ? Few($"Sotto il {solid[0].From}%", below.Sum(b => b.Cases)) : "") +
|
||||
(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)
|
||||
{
|
||||
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();
|
||||
if (rest > 0)
|
||||
{
|
||||
rows.Add(new LearningWeight("Tutto il resto", rest, true));
|
||||
}
|
||||
|
||||
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 text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
|
||||
: 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."
|
||||
: $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100.";
|
||||
return view with { Weights = rows, WeightsText = text };
|
||||
}
|
||||
|
||||
// ---- Versions -----------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The scores of a model on the cases it had not studied, from the verification of its training.</summary>
|
||||
private static Scores? Verified(ModelRow? model) => model?.Report.Attempts.FirstOrDefault(a => a.Chosen)?.Combined;
|
||||
|
||||
private static LearningVersion? Column(ModelRow? model, DateTimeOffset now) => model?.Version is not { } version ? null
|
||||
: Verified(model) is { Cases: > 0 } s
|
||||
? new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, Points(s.Precision), Round(s.Brier, 3), Round(s.GainWith, 2), Round(s.GainWithout, 2))
|
||||
: new LearningVersion(version, DayText(DayOf(model.TrainedAt), now), model.Examples, null, null, null, null);
|
||||
|
||||
private static LearningView WithTrial(LearningView view, TrialCheck check, int? champion, int? challenger)
|
||||
{
|
||||
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > check.Pairs, TrialCheck.Thresholds[^1]);
|
||||
var first = TrialCheck.Thresholds[0];
|
||||
var thresholds = string.Join(", ", TrialCheck.Thresholds.SkipLast(1)) + " e " + TrialCheck.Thresholds[^1];
|
||||
var text = check.Pairs switch
|
||||
{
|
||||
0 => $"Non ha ancora casi di confronto: ne servono {first}. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||
_ when check.Pairs < first => $"{(check.Mean > 0 ? "Sembra un po' meglio, ma ha" : "Per ora non sembra meglio, e ha")} solo {(check.Pairs == 1 ? "un caso" : check.Pairs + " casi")} di confronto su {first}: " +
|
||||
$"troppo pochi per escludere la fortuna. Fino ad allora gira in ombra accanto alla {champion}.",
|
||||
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. Si decide solo quando i casi superano {thresholds}: " +
|
||||
$"prende il posto della {champion} se il vantaggio non si spiega con il caso, e dopo {TrialCheck.Thresholds[^1]} casi senza vantaggio è scartata.",
|
||||
};
|
||||
return view with { Pairs = check.Pairs, PairsNeeded = next, TrialTitle = $"La versione {challenger} è ancora in prova.", TrialText = text };
|
||||
}
|
||||
|
||||
// ---- Watch --------------------------------------------------------------------------------------------------
|
||||
|
||||
private static List<LearningCheck> ChecksOf(HealthCheck health, LearningSnapshot snapshot, ModelRow champion, Scores? verified, IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||
{
|
||||
var known = champion.Model is { } model ? snapshot.Examples.Count(e => e.Source == CaseSources.Live && model.Strategies.Contains(e.Strategy)) : 0;
|
||||
var checks = new List<LearningCheck>
|
||||
{
|
||||
health.DriftingClues.Count > 0 ? new("warn", "Il mercato è diverso da quello su cui ha studiato: " + string.Join(", ", health.DriftingClues).ToLower(_it))
|
||||
: known < Health.MinCases ? new("wait", $"Se il mercato somiglia a quello su cui ha studiato si vede da {Health.MinCases} segnali: per ora sono {known}")
|
||||
: new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||
PrecisionCheck(Points(health.Precision), health.Cases, Points(verified?.Precision)),
|
||||
};
|
||||
if (health.ErrorDrift)
|
||||
{
|
||||
checks.Add(new("warn", "I suoi errori sono aumentati negli ultimi casi"));
|
||||
}
|
||||
|
||||
checks.Add(new("wait", $"Ultimo controllo {Moment(health.At, now)}. {AlarmText(events, now)}"));
|
||||
return checks;
|
||||
}
|
||||
|
||||
private static LearningCheck PrecisionCheck(int? precision, int cases, int? expected)
|
||||
{
|
||||
if (precision is not { } seen || cases < Health.MinCases)
|
||||
{
|
||||
return new("wait", cases == 0 ? $"Nessun segnale concluso: la precisione si giudica da {Health.MinCases} casi" : $"Segnali conclusi: {cases}. La precisione si giudica da {Health.MinCases} casi");
|
||||
}
|
||||
|
||||
var against = expected is not { } e ? "" : Math.Abs(seen - e) <= 5 ? $", in linea con il {e}% atteso" : seen < e ? $", sotto il {e}% atteso" : $", sopra il {e}% atteso";
|
||||
return new(seen < Health.Alarm * 100 ? "warn" : "ok", $"Precisione sugli ultimi {cases} casi: {seen}%{against}");
|
||||
}
|
||||
|
||||
private static string AlarmText(IReadOnlyList<ModelEvent> events, DateTimeOffset now)
|
||||
{
|
||||
if (events.LastOrDefault(e => e.Kind == ModelEvents.SetAside) is not { } alarm)
|
||||
{
|
||||
return "Nessun allarme finora";
|
||||
}
|
||||
|
||||
var back = events.FirstOrDefault(e => e.Kind == ModelEvents.Back && e.At >= alarm.At);
|
||||
var days = back is null ? 0 : Math.Max(1, (int)Math.Round((back.At - alarm.At).TotalDays));
|
||||
return $"Ultimo allarme il {DayText(DayOf(alarm.At), now)}, {(back is null ? "ancora in corso" : days == 1 ? "rientrato in un giorno" : $"rientrato in {days} giorni")}";
|
||||
}
|
||||
|
||||
// ---- Demo ---------------------------------------------------------------------------------------------------
|
||||
|
||||
private static LearningView Demo(JsonElement demo)
|
||||
{
|
||||
static decimal Amount(JsonElement e, string name) => decimal.Parse(e.GetProperty(name).GetString()!, CultureInfo.InvariantCulture);
|
||||
LearningVersion Version(string name)
|
||||
{
|
||||
var v = demo.GetProperty(name);
|
||||
return new LearningVersion(v.GetProperty("versione").GetInt32(), v.GetProperty("addestrato").GetString()!, v.GetProperty("casi").GetInt32(), v.GetProperty("precisione_pct").GetInt32(),
|
||||
Amount(v, "errore"), Amount(v, "guadagno"), Amount(demo, "guadagno_senza_filtro"));
|
||||
}
|
||||
|
||||
var summary = DemoSummary(demo);
|
||||
var champion = Version("in_carica");
|
||||
var challenger = Version("sfidante");
|
||||
var watch = demo.GetProperty("sorveglianza");
|
||||
var (title, text) = Words(summary, new CycleState(), DateTimeOffset.MinValue);
|
||||
var view = new LearningView
|
||||
{
|
||||
Summary = summary,
|
||||
Title = title,
|
||||
Text = text,
|
||||
Pace = PaceWords(demo.GetProperty("settimane_mancanti").GetDouble()),
|
||||
LastTraining = $"{summary.Trained}, versione {challenger.Version}",
|
||||
Bands =
|
||||
[
|
||||
.. demo.GetProperty("fasce").EnumerateArray().Select(b => (From: b.GetProperty("da").GetInt32(), To: b.GetProperty("a").GetInt32(), Band: b))
|
||||
.Select(b => new LearningBand(b.From, b.To, b.Band.GetProperty("casi").GetInt32(), (b.From + b.To) / 2m, b.Band.GetProperty("pct").GetInt32())),
|
||||
],
|
||||
BandsText = demo.GetProperty("fasce_testo").GetString()!,
|
||||
Champion = champion,
|
||||
Challenger = challenger,
|
||||
Checked = true,
|
||||
Checks =
|
||||
[
|
||||
new("ok", "Il mercato di oggi somiglia a quello su cui ha studiato"),
|
||||
PrecisionCheck(watch.GetProperty("precisione_pct").GetInt32(), watch.GetProperty("casi").GetInt32(), champion.Precision),
|
||||
new("wait", watch.GetProperty("controllo").GetString()!),
|
||||
],
|
||||
Weeks = [.. watch.GetProperty("settimane").EnumerateArray().Select(w => new LearningWeek(DateOnly.Parse(w.GetProperty("lunedi").GetString()!, CultureInfo.InvariantCulture), w.GetProperty("pct").GetInt32()))],
|
||||
Found = [.. demo.GetProperty("scoperte").EnumerateArray().Select(d => new Discovery(d.GetProperty("titolo").GetString()!, d.GetProperty("dettaglio").GetString()!, d.GetProperty("casi").GetInt32()))],
|
||||
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), champion.Version, challenger.Version);
|
||||
}
|
||||
|
||||
// ---- Words --------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The night that comes: 03:00 in Rome of the next Sunday, or of the next day before the first model.</summary>
|
||||
private static string NextText(DateTimeOffset now, bool sunday)
|
||||
{
|
||||
var local = TimeZoneInfo.ConvertTime(now, Zones.Rome);
|
||||
var today = DateOnly.FromDateTime(local.DateTime);
|
||||
var day = local.Hour < 3 ? today : today.AddDays(1);
|
||||
if (sunday)
|
||||
{
|
||||
day = day.AddDays((7 - (int)day.DayOfWeek) % 7);
|
||||
}
|
||||
|
||||
return Format.Day(day) + ", 03:00";
|
||||
}
|
||||
|
||||
/// <summary>"domenica 11 ottobre alle 03:00" from the short form.</summary>
|
||||
private static string At(string next) => next.Replace(",", " alle", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>"oggi alle 03:00", "il 4 ottobre alle 03:00".</summary>
|
||||
private static string Moment(DateTimeOffset at, DateTimeOffset now)
|
||||
{
|
||||
var time = TimeZoneInfo.ConvertTime(at, Zones.Rome).ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
return (DayOf(now).DayNumber - DayOf(at).DayNumber) switch
|
||||
{
|
||||
0 => $"oggi alle {time}",
|
||||
1 => $"ieri alle {time}",
|
||||
_ => $"il {DayText(DayOf(at), now)} alle {time}",
|
||||
};
|
||||
}
|
||||
|
||||
private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome);
|
||||
|
||||
/// <summary>"4 ottobre", with the year when it is another one.</summary>
|
||||
private static string DayText(DateOnly day, DateTimeOffset now) => day.Year == DayOf(now).Year ? Format.LongDate(day)[..^5] : Format.LongDate(day);
|
||||
|
||||
private static int? Points(double? share) => share is { } s ? (int)Math.Round(s * 100, MidpointRounding.AwayFromZero) : null;
|
||||
|
||||
private static decimal Round(double value, int decimals) => Math.Round((decimal)value, decimals, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -14,8 +14,6 @@ internal sealed record AccountTrend(decimal Month, IReadOnlyList<decimal> Points
|
||||
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
|
||||
|
||||
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
|
||||
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
|
||||
|
||||
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
|
||||
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
|
||||
|
||||
@@ -39,7 +37,7 @@ internal sealed record PanoramaView(
|
||||
IReadOnlyList<LastAction>? DemoLast,
|
||||
string? NextDecision,
|
||||
IReadOnlyList<PanoramaNews>? News,
|
||||
PanoramaLearning? Learning,
|
||||
LearningSummary Learning,
|
||||
DateTimeOffset? FractionStops)
|
||||
{
|
||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||
@@ -93,12 +91,13 @@ internal sealed record PanoramaView(
|
||||
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
|
||||
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
|
||||
|
||||
var learning = await LearningView.SummaryAsync(host, shell, cancellationToken).ConfigureAwait(false);
|
||||
using var aggregates = shell.Aggregates();
|
||||
if (aggregates is null)
|
||||
{
|
||||
var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone),
|
||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), null, fractions);
|
||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions);
|
||||
}
|
||||
|
||||
var root = aggregates.RootElement;
|
||||
@@ -108,9 +107,6 @@ internal sealed record PanoramaView(
|
||||
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
|
||||
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
|
||||
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
|
||||
var model = root.GetProperty("apprendimento");
|
||||
var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
|
||||
model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
|
||||
|
||||
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
|
||||
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
|
||||
|
||||
@@ -80,7 +80,7 @@ internal static class ReasonTexts
|
||||
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto";
|
||||
}
|
||||
|
||||
return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": in osservazione, non cambia niente";
|
||||
return json.RootElement.TryGetProperty("counts", out var counts) && counts.ValueKind == JsonValueKind.True ? said + ": taglia piena" : said + ": solo osservazione, non ha cambiato la dimensione";
|
||||
}
|
||||
|
||||
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
|
||||
|
||||
Reference in new issue
Block a user