Fix what the independent review of Phase 8 found and close the phase
ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s
ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s
Two reviewers with a clean context read the engine and the screens. The isotonic calibration took its floor from the first step, even of two cases, so with few winners it flattened every estimate: the first model is rebuilt with the fix. Learning failures no longer forget the multiplier an operation was born with, nor stop a decision or the nightly check; recovered decisions read the outside world as it was when due; models estimate only the strategies they studied; a newer history does not repeat what was lived. The screens count examples instead of verifications, show the next threshold and never round an alarm to 50%; two forms now check the antiforgery token. Each defect has its test, on both engines. ADR 0018 point 17 has the list. refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f69943f70a
commit
0b0f4a5e75
33 files changed
+659
-145
No files matched your search
@@ -715,6 +715,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.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.below-left { transform: translate(calc(-100% - 10px), 8px); }
|
||||
.point-label.above { transform: translate(-100%, -24px); margin-left: -8px; }
|
||||
.point-label.under { transform: translate(-50%, 10px); }
|
||||
.hover-dot:hover { z-index: 2; }
|
||||
|
||||
@@ -33,9 +33,9 @@
|
||||
</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="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 @Cases(b)</span></span>
|
||||
}
|
||||
<span class="point-label below" style="left:@Pct(X(fullest.Estimated) / 10);top:@Pct(Y(fullest.Observed) / 10)">@Label(fullest)</span>
|
||||
<span class="point-label @(X(fullest.Estimated) > 450m ? "below-left" : "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>
|
||||
@@ -62,7 +62,7 @@
|
||||
<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>
|
||||
<tr><td>tra @(b.From)% e @(b.To)%</td><td class="num">@Format.Number(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>
|
||||
@@ -78,7 +78,9 @@
|
||||
[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 Label(LearningBand b) => $"{Format.Number(b.Observed)}% su {Cases(b)}";
|
||||
|
||||
private static string Cases(LearningBand b) => b.Cases == 1 ? "un caso" : Format.Number(b.Cases) + " casi";
|
||||
|
||||
private static string Css(decimal v) => v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
|
||||
@@ -126,12 +126,16 @@ else if (Errore is not null)
|
||||
<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>
|
||||
<tr><th scope="row">Casi di confronto diretto</th><td class="num muted">non serve</td><td class="num">@Format.Number(v.Pairs) su @v.PairsNeeded</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
@if (v.GainOnReference)
|
||||
{
|
||||
<p class="note">Nessuna strategia con capitale affidato ha ancora casi: il guadagno è calcolato su tutte, con il capitale di riferimento.</p>
|
||||
}
|
||||
<p class="aside"><strong>@v.TrialTitle</strong> @v.TrialText</p>
|
||||
@if (v.Choice is { } choice)
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
"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.",
|
||||
"apprendimento" => "Impostazioni del modello salvate: valgono dalle prossime operazioni. Quelle già rimpicciolite restano così fino alla chiusura.",
|
||||
"promozione" => "Promozione annullata: è tornata in carica la versione precedente.",
|
||||
|
||||
_ => "Fatto.",
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
@foreach (var c in pending)
|
||||
{
|
||||
<div class="row">
|
||||
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (tra @Bp(c.LowBp) e @Bp(c.HighBp) al 95%).</span></p>
|
||||
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (quasi certamente tra @Bp(c.LowBp) e @Bp(c.HighBp)). Un punto base è un centesimo di punto percentuale.</span></p>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/rifiuta" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Rifiuta</button></form>
|
||||
</div>
|
||||
|
||||
@@ -111,7 +111,8 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
|
||||
private static async Task<IResult> AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct)
|
||||
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
||||
private static async Task<IResult> AbsenceSeenAsync(Guid id, IFormCollection form, AnubisHost host, CancellationToken ct)
|
||||
{
|
||||
if (!host.IsDemo && host.Services is { } services)
|
||||
{
|
||||
@@ -767,8 +768,8 @@ internal static partial class Forms
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6).</summary>
|
||||
private static async Task<IResult> DecideCostAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6). The form is bound for the antiforgery check.</summary>
|
||||
private static async Task<IResult> DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta"))
|
||||
{
|
||||
|
||||
@@ -112,6 +112,9 @@ internal sealed record LearningView
|
||||
|
||||
public int PairsNeeded { get; init; }
|
||||
|
||||
/// <summary>No strategy with capital had examples when the model in charge was trained.</summary>
|
||||
public bool GainOnReference { get; init; }
|
||||
|
||||
public string TrialTitle { get; init; } = "";
|
||||
|
||||
public string TrialText { get; init; } = "";
|
||||
@@ -169,7 +172,7 @@ internal sealed record LearningView
|
||||
: 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)),
|
||||
return new LearningSummary(status, evaluated, ActivationCheck.Needed, Points(Verified(champion)?.Precision), last is null ? "mai" : LongDay(DayOf(last.TrainedAt), now),
|
||||
champion is null ? "Prima verifica" : challenger is null ? "Prossimo addestramento" : "Prossima verifica dello sfidante", NextText(now, champion is not null));
|
||||
}
|
||||
|
||||
@@ -213,7 +216,8 @@ internal sealed record LearningView
|
||||
var last = snapshot.Models.LastOrDefault(m => m.Version is not null);
|
||||
var (title, text) = Words(summary, state, now);
|
||||
|
||||
var live = activation.Scores.Bands;
|
||||
// What really happened: the weights by maturation serve the decisions, not the sentence "è andata bene".
|
||||
var live = Judge.Bands(inCharge);
|
||||
var history = !live.Any(b => b.Cases >= Judge.BandMin);
|
||||
var verified = Verified(champion);
|
||||
var bands = (history ? verified?.Bands ?? [] : live).Select(Band).ToList();
|
||||
@@ -224,7 +228,7 @@ internal sealed record LearningView
|
||||
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}",
|
||||
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
|
||||
Bands = bands,
|
||||
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
|
||||
BandsFromHistory = history && bands.Count > 0,
|
||||
@@ -239,6 +243,7 @@ internal sealed record LearningView
|
||||
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,
|
||||
GainOnReference = champion?.Report.AllStrategiesCounted == true,
|
||||
Found = discoveries.Found,
|
||||
News = discoveries.News,
|
||||
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
|
||||
@@ -248,13 +253,15 @@ internal sealed record LearningView
|
||||
{
|
||||
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) : [],
|
||||
Weeks = [.. Health.Weeks(snapshot.Of(champion.Id), DayOf(now)).Select(w => new LearningWeek(w.Monday, Health.Shown(w.Precision)))],
|
||||
Checks = state.Health is not { } health ? []
|
||||
: health.Version is { } seen && seen != champion.Version ? [new("wait", "Il modello in carica è cambiato: il primo controllo è alle 03:00. " + AlarmText(events, now))]
|
||||
: 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)
|
||||
? WithTrial(view, TrialCheck.Of(snapshot.Pairs(champion.Id, challenger.Id), baseRates), challenger.ThresholdDone, summary.NextCheck, champion.Version, challenger.Version)
|
||||
: view with
|
||||
{
|
||||
TrialTitle = champion is null ? "Nessun modello ancora." : "Nessuno sfidante in prova.",
|
||||
@@ -274,7 +281,7 @@ internal sealed record LearningView
|
||||
$"{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."),
|
||||
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}"),
|
||||
_ => ("Sta imparando, ma non decide ancora.", $"{How} Quando avrà visto abbastanza casi potrà rimpicciolire le operazioni che giudica deboli. {Limits}"),
|
||||
@@ -363,7 +370,7 @@ internal sealed record LearningView
|
||||
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.";
|
||||
static string Few(string where, int cases) => $" {where} ha visto solo {(cases == 1 ? "un caso, troppo poco" : Format.Number(cases) + " 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) : "");
|
||||
}
|
||||
@@ -380,6 +387,7 @@ 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 text = rows.Count == 0 ? "Su casi mai visti nessuna informazione, da sola, ha migliorato le stime."
|
||||
: 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."
|
||||
: $"Le notizie contano, {(news + fear < 50 ? "ma meno dei prezzi" : "più dei prezzi")}: insieme a paura e avidità pesano {news + fear} su 100.";
|
||||
@@ -396,17 +404,17 @@ internal sealed record LearningView
|
||||
? 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)
|
||||
/// <param name="done">The last threshold already judged: at the next one, passed or not, there is a decision (SPEC 11.4).</param>
|
||||
private static LearningView WithTrial(LearningView view, TrialCheck check, int done, string nextCheck, int? champion, int? challenger)
|
||||
{
|
||||
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > check.Pairs, TrialCheck.Thresholds[^1]);
|
||||
var next = TrialCheck.Thresholds.FirstOrDefault(t => t > done, 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}: " +
|
||||
_ => $"{(check.Mean > 0 ? "Sembra un po' meglio" : "Per ora non sembra meglio")} su {check.Pairs} casi di confronto. {(check.Pairs >= next ? $"Si decide {At(nextCheck)}" : $"Si decide di nuovo a {next} casi")}: " +
|
||||
$"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 };
|
||||
@@ -422,7 +430,7 @@ internal sealed record LearningView
|
||||
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)),
|
||||
PrecisionCheck(health.Precision is { } p ? Health.Shown(p) : null, health.Cases, Points(verified?.Precision)),
|
||||
};
|
||||
if (health.ErrorDrift)
|
||||
{
|
||||
@@ -500,7 +508,7 @@ 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), champion.Version, challenger.Version);
|
||||
return WithTrial(WithWeights(view, named), new TrialCheck(demo.GetProperty("confronti").GetInt32(), 0, 0, 0, 1, 0, 0), 0, summary.NextCheck, champion.Version, challenger.Version);
|
||||
}
|
||||
|
||||
// ---- Words --------------------------------------------------------------------------------------------------
|
||||
@@ -536,6 +544,9 @@ internal sealed record LearningView
|
||||
|
||||
private static DateOnly DayOf(DateTimeOffset moment) => Zones.DayIn(moment, Zones.Rome);
|
||||
|
||||
/// <summary>"domenica 4 ottobre", with the year when it is another one.</summary>
|
||||
private static string LongDay(DateOnly day, DateTimeOffset now) => Format.Day(day) + (day.Year == DayOf(now).Year ? "" : day.ToString(" yyyy", CultureInfo.InvariantCulture));
|
||||
|
||||
/// <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);
|
||||
|
||||
|
||||
@@ -80,7 +80,8 @@ 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 + ": solo osservazione, non ha cambiato la dimensione";
|
||||
bool Is(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
|
||||
return said + (Is("counts") ? ": taglia piena" : Is("aside") ? ": era messo da parte, non ha cambiato la dimensione" : ": solo osservazione, non ha cambiato la dimensione");
|
||||
}
|
||||
|
||||
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
|
||||
|
||||
@@ -167,7 +167,7 @@ internal sealed record TradesView(
|
||||
private static async Task<(List<WhyLine> Bought, List<WhyLine> Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var (executions, decisions) = await services.Db.ReadAsync(async s =>
|
||||
var (executions, decisions, earlier) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var e = await s.QueryAsync(
|
||||
"SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " +
|
||||
@@ -178,7 +178,14 @@ internal sealed record TradesView(
|
||||
"SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id",
|
||||
r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")),
|
||||
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
|
||||
return (e, d);
|
||||
|
||||
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
|
||||
var m = d.Any(x => x.Stage == DecisionStages.Model) ? [] : await s.QueryAsync(
|
||||
"SELECT d.outcome, d.data FROM decisions d JOIN ml_features f ON f.decision_id = d.decision_id AND f.symbol = d.symbol LEFT JOIN ml_labels l ON l.feature_id = f.id " +
|
||||
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day > @o) ORDER BY d.created_at DESC LIMIT 1",
|
||||
r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), ("st", DecisionStages.Model), ("s", t.Strategy), ("sym", t.Symbol), ("t", t.OpenedAt.AddMinutes(5)),
|
||||
("o", DateOnly.FromDateTime(t.OpenedAt.UtcDateTime).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
return (e, d, m);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
|
||||
@@ -193,6 +200,7 @@ internal sealed record TradesView(
|
||||
: sell.Purpose is "stop" or "protective" ? "stop" : null;
|
||||
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
|
||||
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
|
||||
return (Lines(buy.Key), sold, entrySlip, exitSlip, code);
|
||||
List<WhyLine> bought = [.. Lines(buy.Key), .. earlier.SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
|
||||
return (bought, sold, entrySlip, exitSlip, code);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user