Judge the variant in use and count the shadow cases for what they are

The quarterly review judged the best variant of the grid instead of the one
that trades: the plan now fixes the variant in use and the protocol measures
that one, while the tries are still those of the grid. A failure while the
history is prepared is a reason in the report and no longer stops the review,
and a strategy whose protocol does not exist says so when its data are there.

The volatility improvement compared books of different days and stages: the
book keeps its stage and its previous day, and a case without a book valid on
its day is left out. Fewer than six months give no interval, the others use
the clustered error with the Student t.

The restriction balance counts a case in the period in which its outcome
became known, so no case is lost or counted twice between two reviews.

The contact given to the SEC travels only on the client that never follows a
redirect, so it cannot reach another site.

refs #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 22:26:06 +01:00
1 parent 24e20584d4
commit 3543f29aba
23 files changed
+577 -126

No files matched your search

@@ -206,7 +206,7 @@
<td>
@foreach (var l in m.Lines)
{
<div>@(l.Label is null ? "" : l.Label + ": ")@(l.Mean is { } mean ? Anubis.Learning.ImprovementText.Percent(mean) : "—")@if (l.Interval is { } i) {<span class="note"> tra @Anubis.Learning.ImprovementText.Percent(i.Low) e @Anubis.Learning.ImprovementText.Percent(i.High)</span>}</div>
<div>@(l.Label is null ? "" : l.Label + ": ")@(l.Mean is { } mean ? Anubis.Learning.ImprovementText.Percent(mean) : "—")@if (l.Interval is { } i) {<span class="note"> tra @Anubis.Learning.ImprovementText.Percent(i.Low) e @Anubis.Learning.ImprovementText.Percent(i.High)</span>}@if (l.Missing is { } missing) {<span class="note"> (@missing)</span>}</div>
}
</td>
<td>@(m.Lines.Max(l => l.Cases) == 0 ? "—" : m.Trust)</td>
@@ -44,7 +44,7 @@
<tbody>
@Row("Esito", x => LabText.Verdict(x.Trial.Verdict))
@Row("Dati", x => LabText.Symbols(x.Trial.Plan.Data.Symbols) + ", " + LabText.Period(x.Trial.Plan.Data.From, x.Trial.Plan.Data.To))
@Row("Variante scelta", x => LabText.Parameters(x.Report.Chosen) + $" (di {x.Trial.Variants})")
@Row("Variante giudicata", x => x.Report.Judged is { } judged ? LabText.Parameters(judged) + " (in uso)" : LabText.Parameters(x.Report.Chosen) + $" (scelta, di {x.Trial.Variants})")
@Row("Risultato netto", x => LabText.Money(x.Report.Metrics.NetResult, x.Report.Currency, withSign: true))
@Row("Con costi doppi", x => x.Report.Costs.FirstOrDefault(k => k.Multiplier == 2m) is { } k ? LabText.Money(k.NetResult, x.Report.Currency, withSign: true) : LabText.Missing)
@Row("Rendimento annuo", x => LabText.Percent(x.Report.Metrics.AnnualReturn, 1, true))
@@ -68,9 +68,15 @@
var c = r.Currency;
var m = r.Metrics;
var b = r.Benchmark;
var variant = r.Judged is null ? "Variante scelta" : "Variante in uso";
var ofVariant = r.Judged is null ? "della variante scelta" : "della variante in uso";
<section class="panel" aria-labelledby="esito">
<h2 id="esito">Esito del protocollo</h2>
<p>Variante scelta: <strong>@LabText.Parameters(r.Chosen)</strong>, la migliore zona della griglia e non il singolo punto migliore.</p>
@if (r.Judged is { } judged)
{
<p>Il giudizio è sulla variante in uso: <strong>@LabText.Parameters(judged)</strong>.@(r.Variants.Any(v => v.OutsideGrid) ? " Non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più." : "")</p>
}
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Controllo</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Soglia</th><th scope="col">Esito</th></tr></thead>
@@ -103,10 +109,10 @@
</section>
<section class="panel" aria-labelledby="risultato">
<h2 id="risultato">Risultato della variante scelta</h2>
<h2 id="risultato">Risultato @ofVariant</h2>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col"></th><th scope="col" class="num">Variante scelta</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
<thead><tr><th scope="col"></th><th scope="col" class="num">@variant</th><th scope="col" class="num">Comprare e tenere</th></tr></thead>
<tbody>
<tr><th scope="row">Risultato netto</th><td class="num">@LabText.Money(m.NetResult, c, withSign: true)</td><td class="num">@LabText.Money(b.NetResult, c, withSign: true)</td></tr>
<tr><th scope="row">Rendimento totale</th><td class="num">@LabText.Percent(m.TotalReturn, 1, true)</td><td class="num">@LabText.Percent(b.TotalReturn, 1, true)</td></tr>
@@ -123,7 +129,7 @@
</tbody>
</table>
</div>
<EquityChart Points="_curve" Currency="@c" Native="true" Label="Patrimonio della variante scelta e di comprare e tenere" EquityLabel="Variante scelta" BenchmarkLabel="Comprare e tenere gli stessi strumenti" EquityColumn="Variante scelta" BenchmarkColumn="Comprare e tenere" />
<EquityChart Points="_curve" Currency="@c" Native="true" Label="@($"Patrimonio {ofVariant} e di comprare e tenere")" EquityLabel="@variant" BenchmarkLabel="Comprare e tenere gli stessi strumenti" EquityColumn="@variant" BenchmarkColumn="Comprare e tenere" />
</section>
<section class="panel" aria-labelledby="anni">
@@ -162,7 +168,7 @@
<h2 id="convalide">Convalide</h2>
<h3>Sharpe corretto per il numero di prove</h3>
@{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); }
<p>Deflated Sharpe Ratio <strong>@LabText.Number(d.Value)</strong>: la probabilità che lo Sharpe della variante scelta (@LabText.Number(d.Sharpe * annual) all'anno) superi quello che il migliore di @d.Trials tentativi mostrerebbe per caso (@LabText.Number(d.Benchmark * annual) all'anno). Contati tutti i test di questa strategia: @r.TrialsCounted varianti. Su @d.Observations sedute, asimmetria @LabText.Number(d.Skewness), curtosi @LabText.Number(d.Kurtosis).</p>
<p>Deflated Sharpe Ratio <strong>@LabText.Number(d.Value)</strong>: la probabilità che lo Sharpe @ofVariant (@LabText.Number(d.Sharpe * annual) all'anno) superi quello che il migliore di @d.Trials tentativi mostrerebbe per caso (@LabText.Number(d.Benchmark * annual) all'anno). Contati tutti i test di questa strategia: @r.TrialsCounted varianti. Su @d.Observations sedute, asimmetria @LabText.Number(d.Skewness), curtosi @LabText.Number(d.Kurtosis).</p>
<h3>Probabilità di sovra-adattamento</h3>
@if (r.Overfitting is { } pbo)
@@ -231,9 +237,9 @@
@foreach (var v in r.Variants)
{
<tr>
<td>@LabText.Parameters(v.Parameters)@if (v.Chosen) {<span class="tag"> scelta</span>}</td>
<td>@LabText.Parameters(v.Parameters)@if (v.Chosen) {<span class="tag"> scelta</span>}@if (v.Parameters == r.Judged) {<span class="tag"> in uso</span>}</td>
<td class="num">@LabText.Number(v.Sharpe * annual)</td>
<td class="num">@LabText.Number(v.PlateauScore * annual)</td>
<td class="num">@(v.OutsideGrid ? LabText.Missing : LabText.Number(v.PlateauScore * annual))</td>
<td class="num">@LabText.Money(v.NetResult, c, true)</td>
<td class="num">@LabText.Percent(v.MaxDrawdown)</td>
<td class="num">@v.Trades</td>
@@ -39,7 +39,7 @@
}
@if (line.InUse is { } used)
{
<br /><span class="note">Variante in uso: @LabText.Parameters(used.Parameters), Sharpe @LabText.Number(used.Sharpe), calo massimo @LabText.Percent(used.MaxDrawdown). Non cambia da sola.</span>
<br /><span class="note">Variante in uso: @LabText.Parameters(used.Parameters), Sharpe @LabText.Number(used.Sharpe), calo massimo @LabText.Percent(used.MaxDrawdown).@(used.OutsideGrid ? " Non è nella griglia." : "") Non cambia da sola.</span>
}
</td>
<td>@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) {<div>@text</div>}</td>
+1 -1
View File
@@ -19,7 +19,7 @@ internal static class ReviewView
ReviewVerdicts.Passed => "Superata",
ReviewVerdicts.Rejected => "Non superata",
ReviewVerdicts.Error => "Non riuscita",
_ => "In attesa dei dati",
_ => line.NoProtocol ? "Non riprovata" : "In attesa dei dati",
};
public static string? VerdictClass(ReviewLine line) => line.Verdict switch
+1 -1
View File
@@ -237,7 +237,7 @@ public static class CryptoTrendProtocol
Verdict = verdict,
Report = report,
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
Parameters = main.Report.Judged ?? main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
ExpectedSlippageBp = slippage,
RoundTripCost = Math.Round(2m * (fee + (slippage / 10_000m)), 6),
+58 -13
View File
@@ -24,7 +24,11 @@ public static class ReviewStatuses
}
/// <summary>The figures of a variant on the broad universe.</summary>
public sealed record ReviewVariant(string Parameters, double Sharpe, decimal NetResult, double MaxDrawdown);
public sealed record ReviewVariant(string Parameters, double Sharpe, decimal NetResult, double MaxDrawdown)
{
/// <summary>The variant in use when the grid does not have it.</summary>
public bool OutsideGrid { get; init; }
}
/// <summary>A strategy in the report of a review: the verdict, what it did, and how the strategy did live.</summary>
public sealed record ReviewLine
@@ -41,6 +45,9 @@ public sealed record ReviewLine
/// <summary>The verdict in words.</summary>
public required string Text { get; init; }
/// <summary>The history is there, but this version has no protocol to try the strategy again.</summary>
public bool NoProtocol { get; init; }
public IReadOnlyList<Guid> Trials { get; init; } = [];
public ReviewVariant? Chosen { get; init; }
@@ -165,7 +172,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
// Several quarters missed make one review, on the history there is now (SPEC 5.6).
var through = new DateOnly(today.Year, today.Month, 1).AddDays(-1);
var id = await OpenAsync(open, quarter, through, cancellationToken).ConfigureAwait(false);
var missing = await prepare(through, cancellationToken).ConfigureAwait(false);
var missing = await PrepareAsync(quarter, through, cancellationToken).ConfigureAwait(false);
if (missing is not null)
{
if (today <= StartOf(today).AddDays(LastDay - 1))
@@ -181,6 +188,20 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
lab.Enqueue(await PlanAsync(id, through, cancellationToken).ConfigureAwait(false));
}
// A fault that repeats every night must not keep the review from ever being published: it waits like a missing archive.
private async Task<string?> PrepareAsync(string quarter, DateOnly through, CancellationToken cancellationToken)
{
try
{
return await prepare(through, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
LogPrepareFailed(_logger, ex, quarter);
return "lo storico non si è potuto preparare per un errore";
}
}
private Task<Guid> OpenAsync(Review? open, string quarter, DateOnly through, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
@@ -204,6 +225,8 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var costs = await new CostBook(db, clock).TableAsync(cancellationToken).ConfigureAwait(false);
var stage = await stages.GetAsync(CryptoTrendProtocol.Strategy, cancellationToken).ConfigureAwait(false);
var qualified = stage is { Stage: not StrategyStages.Observation };
var family = StrategyCatalog.Find(CryptoTrendProtocol.Strategy) ?? throw new InvalidOperationException("crypto_trend non è nel catalogo.");
var judged = qualified ? StrategyParameters.Of(family, stage!.Qualification?.Parameters).ToString() : null;
var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), through, cancellationToken).ConfigureAwait(false);
return await db.WriteAsync(async s =>
{
@@ -212,7 +235,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
{
var request = new TrialRequest(CryptoTrendProtocol.Strategy, TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, through, CryptoTrendProtocol.Capital, null);
var (plan, variants) = Laboratory.BuildPlan(request, clock.UtcNow, costs);
ids.Add(await TrialStore.PlanAsync(s, clock, plan with { Priors = qualified ? ReviewPriors.Review : ReviewPriors.All }, variants, id, cancellationToken).ConfigureAwait(false));
ids.Add(await TrialStore.PlanAsync(s, clock, plan with { Priors = qualified ? ReviewPriors.Review : ReviewPriors.All, Judged = judged }, variants, id, cancellationToken).ConfigureAwait(false));
}
await s.ExecuteAsync("UPDATE quarterly_reviews SET status = @r, costs = @c, started_at = @t, updated_at = @t WHERE id = @id", cancellationToken,
@@ -241,20 +264,25 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var previous = (await ListAsync(db, cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Id != id && r.Status == ReviewStatuses.Done);
var now = clock.UtcNow;
var today = Zones.DayIn(now, Zones.Rome);
var from = previous?.FinishedAt ?? new DateTimeOffset(StartOf(today).AddMonths(-3).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
// The first review covers everything since the start, so the periods always add up to the whole.
var from = previous?.FinishedAt ?? DateTimeOffset.UnixEpoch;
var start = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(created_at) AS t FROM decisions", r => r.MomentOrNull("t")), cancellationToken).ConfigureAwait(false)
?? new DateTimeOffset(StartOf(today).AddMonths(-3).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
var all = (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => StrategyPipeline.IsBase(s.Strategy)).ToList();
var crypto = await CryptoAsync(id, quarter, missing, trials, cancellationToken).ConfigureAwait(false);
var before = await learning.BaseRatesAsync(cancellationToken).ConfigureAwait(false);
var live = (await learning.Store.AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList();
var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false);
var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false);
var report = new ReviewReport
{
Missing = missing,
RatesBefore = before,
RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)),
RestrictionsFrom = Zones.DayIn(from, Zones.Rome),
Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, cancellationToken).ConfigureAwait(false),
RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, cancellationToken).ConfigureAwait(false),
RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome),
Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false),
RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, now, cancellationToken).ConfigureAwait(false),
};
var lines = new List<ReviewLine>();
foreach (var stage in all)
@@ -272,7 +300,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
Signals = live.Count(e => e.Strategy == stage.Strategy && e.IsLabelled),
Won = live.Count(e => e.Strategy == stage.Strategy && e.Label is { Win: true }),
};
lines.Add(stage.Strategy == CryptoTrendProtocol.Strategy ? Measured(line, stage, crypto, trials) : line);
lines.Add(stage.Strategy == CryptoTrendProtocol.Strategy ? Measured(line, stage, crypto, trials)
: stockBars ? line with { NoProtocol = true, Text = char.ToUpperInvariant(NoProtocolText[0]) + NoProtocolText[1..] + "." }
: line);
}
await db.WriteAsync(async s =>
@@ -315,6 +345,10 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
LogPublished(_logger, quarter, crypto.Verdict);
}
private Task<bool> HasStockBarsAsync(CancellationToken cancellationToken) =>
db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM instruments i WHERE i.asset_class = @c AND EXISTS (SELECT 1 FROM bars_1d b WHERE b.instrument_id = i.id)",
("c", AssetClasses.Equity)).ConfigureAwait(false) > 0, cancellationToken);
private async Task<CryptoResult> CryptoAsync(Guid id, string quarter, string? missing, IReadOnlyList<Trial> trials, CancellationToken cancellationToken)
{
if (missing is not null)
@@ -337,9 +371,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var passed = runs.All(r => r.Report.Passed);
var title = new Review(id, quarter, default, "", null, default, null).Title;
var used = runs[0].Report.Judged is null ? "" : " con la variante in uso";
var text = passed
? $"Revisione del {title}: protocollo superato su entrambi gli universi."
: $"Revisione del {title}: protocollo non superato. {CryptoTrendProtocol.Failures(runs)}.";
? $"Revisione del {title}: protocollo superato su entrambi gli universi{used}."
: $"Revisione del {title}: protocollo non superato{used}. {CryptoTrendProtocol.Failures(runs)}.";
if (runs[0].Report.Variants.Any(v => v.OutsideGrid))
{
text += " La variante in uso non è nella griglia: è giudicata lo stesso.";
}
var outcome = CryptoTrendProtocol.Measured(runs[0], CryptoTrendProtocol.Strategy, passed, text, "/laboratorio/revisione/" + id);
return new CryptoResult(passed ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, text, outcome, runs);
}
@@ -353,8 +393,8 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
}
var report = crypto.Runs[0].Report;
ReviewVariant? Variant(Func<ReportVariant, bool> which) => report.Variants.FirstOrDefault(which) is { } v ? new ReviewVariant(v.Parameters, v.Sharpe, v.NetResult, v.MaxDrawdown) : null;
var used = stage.Stage == StrategyStages.Observation ? null : stage.Qualification?.Parameters;
ReviewVariant? Variant(Func<ReportVariant, bool> which) => report.Variants.FirstOrDefault(which) is { } v ? new ReviewVariant(v.Parameters, v.Sharpe, v.NetResult, v.MaxDrawdown) { OutsideGrid = v.OutsideGrid } : null;
var used = stage.Stage == StrategyStages.Observation ? null : report.Judged ?? stage.Qualification?.Parameters;
var since = DateOnly.FromDateTime((stage.StageSince ?? DateTimeOffset.MaxValue).UtcDateTime);
var days = report.Curve.Where(p => p.Day >= since).ToList();
return line with
@@ -403,13 +443,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
return text + " Il rapporto è nel Laboratorio.";
}
private const string NoProtocolText = "non riprovata: il protocollo per le azioni arriva con una versione successiva";
/// <summary>What a review said and did of a strategy, in a few words.</summary>
public static string ActionText(ReviewLine line)
{
ArgumentNullException.ThrowIfNull(line);
return line.Verdict switch
{
ReviewVerdicts.Waiting => "non riprovata, mancano i dati",
ReviewVerdicts.Waiting => line.NoProtocol ? NoProtocolText : "non riprovata, mancano i dati",
ReviewVerdicts.Error => "un test non è riuscito, resta valido l'esito precedente",
_ => line.Action switch
{
@@ -427,6 +469,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} waits: {Missing}")]
private static partial void LogWaiting(ILogger logger, string quarter, string missing);
[LoggerMessage(Level = LogLevel.Warning, Message = "History of the quarterly review {Quarter} not prepared")]
private static partial void LogPrepareFailed(ILogger logger, Exception exception, string quarter);
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} published, crypto_trend: {Verdict}")]
private static partial void LogPublished(ILogger logger, string quarter, string verdict);
+32 -11
View File
@@ -14,7 +14,11 @@ public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? Fir
public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark);
/// <summary>A variant of the grid with its full-period figures.</summary>
public sealed record ReportVariant(string Parameters, double Sharpe, double PlateauScore, decimal NetResult, double MaxDrawdown, int Trades, bool Chosen);
public sealed record ReportVariant(string Parameters, double Sharpe, double PlateauScore, decimal NetResult, double MaxDrawdown, int Trades, bool Chosen)
{
/// <summary>The variant in use when the grid does not have it: judged all the same, never counted as a try.</summary>
public bool OutsideGrid { get; init; }
}
/// <summary>The chosen variant with costs multiplied (SPEC 12.2 point 3).</summary>
public sealed record ReportCosts(decimal Multiplier, decimal NetResult, double TotalReturn, double Sharpe, double MaxDrawdown, decimal Fees);
@@ -88,6 +92,9 @@ public sealed record BacktestReport(
/// <summary>The 5th percentile of the expected path (SPEC 12.3) of the chosen variant; null for the examples.</summary>
public IReadOnlyList<double>? ExpectedPathP5 { get; init; }
/// <summary>The variant in use, when the figures, the checks and the curve are its own (<see cref="TrialPlan.Judged"/>); null when they are those of the chosen one.</summary>
public string? Judged { get; init; }
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize<BacktestReport>(text, TrialPlan.Json) ?? throw new JsonException("Empty report");
@@ -96,7 +103,9 @@ public sealed record BacktestReport(
/// <summary>
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs.
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan
/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice,
/// the overfitting and the number of tries.
/// </summary>
public static class TrialRunner
{
@@ -141,14 +150,22 @@ public static class TrialRunner
var scores = Validation.PlateauScores(variants, sharpes);
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var chosen = variants[chosenIndex];
var run = runs[chosenIndex];
var judged = plan.Judged is null ? chosen.Parameters : StrategyParameters.Of(family, plan.Judged);
var judgedIndex = plan.Judged is null ? chosenIndex : variants.ToList().FindIndex(x => x.ToString() == judged.ToString());
if (judgedIndex < 0)
{
progress?.Invoke("variante in uso");
}
var run = judgedIndex < 0 ? BacktestEngine.Run(family.Create(judged), data, options) : runs[judgedIndex];
var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List<ReportCosts>();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{
var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(judged), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
}
@@ -175,10 +192,10 @@ public static class TrialRunner
// Every variant of every finished trial of this strategy counts as a try (SPEC 12.2 point 1).
var trials = prior.Variants + variants.Count;
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
var dsr = SharpeTests.Deflated(returns[chosenIndex], trials, spread * spread);
var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti");
var look = LookAheadCheck.Run(_ => family.Create(chosen.Parameters), data, options, v.LookAheadCuts);
var look = LookAheadCheck.Run(_ => family.Create(judged), data, options, v.LookAheadCuts);
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -220,7 +237,9 @@ public static class TrialRunner
benchmark,
costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex))],
Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
.. judgedIndex >= 0 ? Array.Empty<ReportVariant>()
: [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward,
combinatorial,
overfitting,
@@ -229,12 +248,14 @@ public static class TrialRunner
lookAhead,
checks,
passed,
Limitations(plan, family, data),
judgedIndex >= 0 ? Limitations(plan, family, data)
: [.. Limitations(plan, family, data), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."],
curve,
[.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now,
watch.Elapsed.TotalSeconds);
watch.Elapsed.TotalSeconds)
{ Judged = plan.Judged is null ? null : judged.ToString() };
if (StrategyPipeline.ResearchShare(family.Id) is not null)
{
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
@@ -243,12 +264,12 @@ public static class TrialRunner
report = report with
{
ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null),
ExpectedPathP5 = [.. PathBootstrap.Percentile(returns[chosenIndex], CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
ExpectedPathP5 = [.. PathBootstrap.Percentile(judgedReturns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
.Select(x => Math.Round(x, 4))],
};
}
var summary = new TrialSummary(data.Currency, chosen.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
var summary = new TrialSummary(data.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes);
return (report, summary);
}
+18
View File
@@ -85,6 +85,24 @@ public static class Normal
}
}
/// <summary>Student's t distribution, for the mean of few independent groups.</summary>
public static class StudentT
{
/// <summary>The quantile with the first terms of the Cornish-Fisher expansion: within 0.0005 at 0.975 from 5 degrees of freedom on.</summary>
public static double Quantile(double p, int freedom)
{
ArgumentOutOfRangeException.ThrowIfLessThan(freedom, 5);
var x = Normal.Quantile(p);
var s = x * x;
double v = freedom;
return x * (1
+ ((s + 1) / (4 * v))
+ (((((5 * s) + 16) * s) + 3) / (96 * v * v))
+ (((((((3 * s) + 19) * s) + 17) * s) - 15) / (384 * v * v * v))
+ (((((((((79 * s) + 776) * s) + 1482) * s) - 1920) * s) - 945) / (92160 * v * v * v * v)));
}
}
/// <summary>Moments of a series of returns, as the formulas of Bailey and López de Prado use them.</summary>
public readonly record struct Moments(int Count, double Mean, double StandardDeviation, double Skewness, double Kurtosis)
{
+6
View File
@@ -79,6 +79,12 @@ public sealed record TrialPlan(
/// <summary>Which tries a trial of a quarterly review counts in its DSR (<see cref="ReviewPriors"/>); null for the user's trials.</summary>
public string? Priors { get; init; }
/// <summary>
/// The variant a trial of a review judges when the strategy already works with it: the grid then only says how much was
/// searched. It is fixed here, so a trial resumed after a restart judges the same. Null judges the one chosen in the grid.
/// </summary>
public string? Judged { get; init; }
public static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
+5 -2
View File
@@ -42,7 +42,7 @@ public sealed partial class MarketDataService : IDisposable
private readonly DataDirectory? _data;
private readonly HttpClient _http;
// For what carries a key in a header: Alpaca's data, the language model.
// For what carries a key or a datum of the user in a header: Alpaca's data, the language model, the SEC.
private readonly HttpClient _signed;
private readonly Func<IWebSocketTransport>? _sockets;
private readonly ILogger _logger;
@@ -220,6 +220,9 @@ public sealed partial class MarketDataService : IDisposable
}
}
/// <summary>The requests to the SEC carry the user's contact, which no other host must receive: they never follow a redirect.</summary>
internal ApiHttp Sec => new(_signed, _clock, Edgar.Source);
/// <summary>
/// The sectors of the companies from the SEC (SPEC 8.7). Without the user's contact, which the SEC asks for in the
/// request, nothing is asked.
@@ -240,7 +243,7 @@ public sealed partial class MarketDataService : IDisposable
await StepAsync(Edgar.Source, async () =>
{
var read = await new CompanySectors(_db, _clock).RefreshAsync(new ApiHttp(_http, _clock, Edgar.Source), agent, symbols, cancellationToken).ConfigureAwait(false);
var read = await new CompanySectors(_db, _clock).RefreshAsync(Sec, agent, symbols, cancellationToken).ConfigureAwait(false);
return $"settori: {read} letti";
}, cancellationToken).ConfigureAwait(false);
}
+4
View File
@@ -26,6 +26,10 @@ public sealed record Example(Guid Id, string Strategy, string Symbol, string Sou
public CaseLabel? Label { get; init; }
/// <summary>When the outcome became known: days after the close if the bot was off. Null for an example not read from the archive.</summary>
[JsonIgnore]
public DateTimeOffset? LabelledAt { get; init; }
/// <summary>A label that can train: the operation started and closed.</summary>
[JsonIgnore]
public bool IsLabelled => Label is { Win: not null, ClosedDay: not null };
+2 -2
View File
@@ -272,7 +272,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
var gate = await OrAsync(() => GateAsync(cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
var shadow = await OrAsync(() => Shadow.InputAsync(strategy, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
var shadow = await OrAsync(() => Shadow.InputAsync(strategy, stage, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy), shadow, create);
}
@@ -359,7 +359,7 @@ public sealed class LearningTurn
_failed = failed;
_outside = outside;
_collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
_shadow = new ShadowTurn(strategy, day, _collector, shadow, ProbabilityOf, create);
_shadow = new ShadowTurn(strategy, stage, day, _collector, shadow, ProbabilityOf, create);
}
/// <summary>
+2 -1
View File
@@ -10,7 +10,7 @@ public sealed class LearningStore(Database db, IClock clock)
{
private const string Columns =
"f.id, f.strategy, f.symbol, f.source, f.decided_day, f.decided_at, f.decision_id, f.stage, f.reason, f.weight, f.stop, f.stop_offset, f.features, f.multiplier, " +
"l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
"l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason, l.created_at AS labelled_at FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
/// <summary>Saves an example as part of the decision that made it. One already there (same day) stays as it is: null.</summary>
public static async Task<Guid?> AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
@@ -109,6 +109,7 @@ public sealed class LearningStore(Database db, IClock clock)
DecisionId = r.IdOrNull("decision_id"),
Multiplier = r.Measure("multiplier"),
Label = label,
LabelledAt = r.MomentOrNull("labelled_at"),
};
}
+33 -16
View File
@@ -46,13 +46,21 @@ public static class RestrictionBalance
_ => code,
};
/// <summary>The balance of the entries blocked; each example counts once, under its strictest row.</summary>
public static RestrictionReport Of(IReadOnlyList<BlockedEntry> blocked, IReadOnlyList<Example> examples, IReadOnlyList<HeldTrade> trades, IReadOnlyDictionary<string, double> capitals)
/// <summary>
/// The balance of the entries blocked; each example counts once, under its strictest row. A case is of the period in
/// which its outcome became known, after <paramref name="from"/> and by <paramref name="until"/>, whenever it was
/// blocked: so the periods add up to the whole. One not known by then is open in every period.
/// </summary>
public static RestrictionReport Of(IReadOnlyList<BlockedEntry> blocked, IReadOnlyList<Example> examples, IReadOnlyList<HeldTrade> trades, IReadOnlyDictionary<string, double> capitals,
DateTimeOffset? from = null, DateTimeOffset? until = null)
{
ArgumentNullException.ThrowIfNull(blocked);
ArgumentNullException.ThrowIfNull(examples);
ArgumentNullException.ThrowIfNull(trades);
ArgumentNullException.ThrowIfNull(capitals);
bool InPeriod(DateTimeOffset at) => (from is null || at > from) && (until is null || at <= until);
blocked = [.. blocked.Where(b => until is null || b.At <= until)];
trades = [.. trades.Where(t => until is null || t.OpenedAt <= until)];
var lines = Codes.ToDictionary(c => c, c => new RestrictionLine(c, 0, 0m, 0m, 0, 0, 0, 0), StringComparer.Ordinal);
var cases = new Dictionary<Guid, (Example Example, List<BlockedEntry> Blocks)>();
foreach (var block in blocked.Where(b => lines.ContainsKey(b.Code)).OrderBy(b => b.At))
@@ -63,7 +71,7 @@ public static class RestrictionBalance
.OrderByDescending(e => e.At).FirstOrDefault();
if (example is null || own.Any(t => t.OpenedAt < block.At && (t.ClosedAt is null || t.ClosedAt > block.At)))
{
lines[block.Code] = lines[block.Code] with { Increases = lines[block.Code].Increases + 1 };
lines[block.Code] = lines[block.Code] with { Increases = lines[block.Code].Increases + (InPeriod(block.At) ? 1 : 0) };
continue;
}
@@ -82,19 +90,28 @@ public static class RestrictionBalance
var first = blocks[0].At;
var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue;
// In observation nothing is ever bought: an entry only put off would have been made at its end.
var delayed = example.Stage == StrategyStages.Observation
// In observation nothing is ever bought: an entry only put off would have been made at its end. A later block of
// the same example can still stop it, so it is settled with the outcome.
var observed = example.Stage == StrategyStages.Observation;
var delayed = observed
? blocks.All(b => b.Postponed)
: trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last);
if (delayed)
{
lines[code] = line with { Delayed = line.Delayed + 1 };
}
else if (example.Label is not { } label)
DateTimeOffset? settled = delayed && !observed
? trades.Where(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first).Min(t => t.OpenedAt)
: example.Label is null ? null : example.LabelledAt > first ? example.LabelledAt : last > first ? last : first;
if (settled is not { } known || known > until)
{
lines[code] = line with { Open = line.Open + 1 };
}
else if (label.Win is null || label.Result is not { } result)
else if (!InPeriod(known))
{
continue;
}
else if (delayed)
{
lines[code] = line with { Delayed = line.Delayed + 1 };
}
else if (example.Label is not { Win: not null, Result: { } result })
{
lines[code] = line with { NeverStarted = line.NeverStarted + 1 };
}
@@ -108,14 +125,14 @@ public static class RestrictionBalance
return new RestrictionReport([.. Codes.Select(c => lines[c]).Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]);
}
/// <summary>The balance of the entries blocked from a moment on.</summary>
public static async Task<RestrictionReport> LoadAsync(Database db, IClock clock, DateTimeOffset from, CancellationToken cancellationToken)
/// <summary>The balance of the entries blocked whose outcome became known in a period.</summary>
public static async Task<RestrictionReport> LoadAsync(Database db, IClock clock, DateTimeOffset from, DateTimeOffset until, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var rows = await db.ReadAsync(s => s.QueryAsync(
"SELECT decision_id, strategy, symbol, outcome, reasons, created_at FROM decisions WHERE symbol IS NOT NULL AND stage IN (@c, @o) AND outcome IN (@r, @p) AND created_at >= @f ORDER BY created_at, id",
"SELECT decision_id, strategy, symbol, outcome, reasons, created_at FROM decisions WHERE symbol IS NOT NULL AND stage IN (@c, @o) AND outcome IN (@r, @p) ORDER BY created_at, id",
r => (Id: r.Id("decision_id"), Strategy: r.Text("strategy"), Symbol: r.Text("symbol"), Outcome: r.Text("outcome"), Reasons: r.Json("reasons").Text, At: r.Moment("created_at")),
("c", DecisionStages.Correctives), ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed), ("f", from)), cancellationToken).ConfigureAwait(false);
("c", DecisionStages.Correctives), ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed)), cancellationToken).ConfigureAwait(false);
var blocked = new List<BlockedEntry>();
foreach (var row in rows)
{
@@ -134,6 +151,6 @@ public static class RestrictionBalance
var trades = await db.ReadAsync(s => s.QueryAsync("SELECT t.strategy, i.symbol, t.opened_at, t.closed_at FROM trades t JOIN instruments i ON i.id = t.instrument_id",
r => new HeldTrade(r.Text("strategy"), r.Text("symbol"), r.Moment("opened_at"), r.MomentOrNull("closed_at"))), cancellationToken).ConfigureAwait(false);
var examples = (await new LearningStore(db, clock).AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList();
return Of(blocked, examples, trades, await LearningCycle.CapitalsAsync(db, clock, cancellationToken).ConfigureAwait(false));
return Of(blocked, examples, trades, await LearningCycle.CapitalsAsync(db, clock, cancellationToken).ConfigureAwait(false), from, until);
}
}
+67 -24
View File
@@ -66,6 +66,12 @@ public sealed record ShadowBook
public string Day { get; init; } = "";
/// <summary>The stage of the strategy at that decision: in observation the positions are only what it would hold.</summary>
public string Stage { get; init; } = "";
/// <summary>The book of the decision before, for a decision of another strategy recovered late; it has no previous of its own.</summary>
public ShadowBook? Previous { get; init; }
public IReadOnlyDictionary<string, double> Returns { get; init; } = new Dictionary<string, double>();
public static string KeyOf(string strategy) => "shadow_book:" + strategy;
@@ -110,13 +116,16 @@ public sealed record ShadowBook
public sealed record ShadowInput(IReadOnlyList<ShadowBook> OtherBooks, IReadOnlyDictionary<string, string> Sectors)
{
public static readonly ShadowInput Nothing = new([], new Dictionary<string, string>());
/// <summary>False when what another strategy held on that day is no longer known: the portfolio cannot be judged.</summary>
public bool Whole { get; init; } = true;
}
/// <summary>
/// The improvements beside one decision. Both steps return the very list they were given: what they find is written
/// apart, and a failure of theirs changes nothing.
/// </summary>
internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector collector, ShadowInput input, Func<StrategyContext, Intent, double?> probability, Func<IStrategy> create)
internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, CaseCollector collector, ShadowInput input, Func<StrategyContext, Intent, double?> probability, Func<IStrategy> create)
{
private readonly List<ShadowCase> _cases = [];
@@ -124,6 +133,8 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
public ShadowBook? Book { get; private set; }
/// <summary>After the collector, on what the strategy proposed.</summary>
public IIntentStage OnProposals => new Step(day, Proposals);
@@ -273,8 +284,8 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
}
}
Book = ShadowBook.Of(context, weights, share);
if (ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
Book = ShadowBook.Of(context, weights, share) with { Stage = stage };
if (!input.Whole || ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
{
return;
}
@@ -288,16 +299,23 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
}
/// <summary>How many signals an improvement changed and what it would have been worth, on one alternative.</summary>
public sealed record ImprovementLine(string? Label, int Cases, double? Mean, double? Error)
public sealed record ImprovementLine(string? Label, int Cases, int Months, double? Mean, double? Error)
{
/// <summary>The interval that holds the mean effect 95 times in 100; null with too few cases.</summary>
public (double Low, double High)? Interval => Mean is { } m && Error is { } e ? (m - (1.96 * e), m + (1.96 * e)) : null;
/// <summary>Fewer months than these give no interval: the signals of a month move together, so a month counts as one.</summary>
public const int MinMonths = 6;
/// <summary>What is missing for an interval, in words; null when nothing is.</summary>
public string? Missing => Cases > 0 && Months < MinMonths ? $"troppo pochi mesi per un intervallo: {Months}, ne servono {MinMonths}" : null;
/// <summary>The interval that holds the mean effect 95 times in 100; null with too few months.</summary>
public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile(0.975, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null;
}
/// <summary>An improvement as the pages show it.</summary>
public sealed record ImprovementView(Improvement Improvement, int Examined, IReadOnlyList<ImprovementLine> Lines, string State, bool Waiting, string? Note)
{
public string Trust => Discovery.TrustOf(Lines.Count == 0 ? 0 : Lines.Max(l => l.Cases));
/// <summary>The signals of too few months say little, however many they are.</summary>
public string Trust => Discovery.TrustOf(Lines.Where(l => l.Missing is null).Select(l => l.Cases).DefaultIfEmpty(0).Max());
}
/// <summary>Saves the shadow of each decision, measures it when the outcomes are known and sums it up.</summary>
@@ -310,23 +328,37 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
private readonly CompanySectors _sectors = new(db, clock);
/// <summary>What the decision of a strategy needs from outside it.</summary>
public async Task<ShadowInput> InputAsync(string strategy, DateOnly day, CancellationToken cancellationToken)
/// <summary>
/// What the decision of a strategy needs from outside it. The others count as they were on <paramref name="day"/>: one
/// that trades looks only at those that traded too, one that only observes at what the three of them would hold.
/// </summary>
public async Task<ShadowInput> InputAsync(string strategy, string stage, DateOnly day, CancellationToken cancellationToken)
{
var books = new List<ShadowBook>();
var whole = true;
foreach (var (name, _, _) in StrategyNames.Base.Where(b => b.Name != strategy))
{
if (await store.StateAsync<ShadowBook>(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is { } book && book.Day.Length > 0
&& Math.Abs(day.DayNumber - BarStore.ParseDay(book.Day).DayNumber) <= ShadowBook.MaxAgeDays)
if (await store.StateAsync<ShadowBook>(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is not { } last)
{
continue; // It never decided: it holds nothing.
}
if ((IsBy(last, day) ? last : last.Previous) is not { } book || !IsBy(book, day))
{
whole = false;
}
else if (day.DayNumber - BarStore.ParseDay(book.Day).DayNumber <= ShadowBook.MaxAgeDays && (stage == StrategyStages.Observation || book.Stage is not ("" or StrategyStages.Observation)))
{
books.Add(book);
}
}
var sectors = strategy == StrategyNames.EquityMomentum ? await _sectors.GroupsAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<string, string>();
return new ShadowInput(books, sectors);
return new ShadowInput(books, sectors) { Whole = whole };
}
private static bool IsBy(ShadowBook book, DateOnly day) => BarStore.ParseDay(book.Day) <= day;
private sealed record Stored
{
public IReadOnlyDictionary<string, double> Numbers { get; init; } = new Dictionary<string, double>();
@@ -351,10 +383,20 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
if (turn.Book is { } book)
{
await LearningStore.SaveStateAsync(s, clock, ShadowBook.KeyOf(strategy), book, cancellationToken).ConfigureAwait(false);
var key = ShadowBook.KeyOf(strategy);
var json = await s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
var kept = json is null ? null : JsonSerializer.Deserialize<ShadowBook>(json);
await LearningStore.SaveStateAsync(s, clock, key, After(kept, book), cancellationToken).ConfigureAwait(false);
}
}
// The last two days of decisions, whatever the order they were made in.
private static ShadowBook After(ShadowBook? kept, ShadowBook book)
{
var newest = new[] { book, kept, kept?.Previous }.OfType<ShadowBook>().DistinctBy(b => b.Day, StringComparer.Ordinal).OrderByDescending(b => b.Day, StringComparer.Ordinal).Take(2).ToList();
return newest[0] with { Previous = newest.Count > 1 ? newest[1] with { Previous = null } : null };
}
private sealed record Open(Guid Id, string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, Stored Data);
/// <summary>
@@ -512,26 +554,27 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
/// <summary>
/// The mean effect and its error, over which the signals decided in the same month count as one: they move together,
/// as in the discoveries (SPEC 11.6).
/// as in the discoveries (SPEC 11.6). With few months there is no error to speak of.
/// </summary>
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
{
if (values.Count == 0)
{
return new ImprovementLine(label, 0, null, null);
}
var mean = values.Average(v => v.Effect);
if (values.Count < 2)
{
return new ImprovementLine(label, values.Count, mean, null);
return new ImprovementLine(label, 0, 0, null, null);
}
var n = values.Count;
var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
var mean = values.Average(v => v.Effect);
var months = values.GroupBy(v => (v.Day.Year, v.Day.Month)).Select(g => g.Sum(v => v.Effect - mean)).ToList();
var clustered = months.Count > 1 ? Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n : 0;
return new ImprovementLine(label, n, mean, Math.Max(simple, clustered));
if (months.Count < ImprovementLine.MinMonths)
{
return new ImprovementLine(label, n, months.Count, mean, null);
}
// Months that happen to cancel out never make the error smaller than that of independent signals.
var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
var clustered = Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n;
return new ImprovementLine(label, n, months.Count, mean, Math.Max(simple, clustered));
}
/// <summary>The improvements with enough cases for a sentence, among the discoveries of SPEC 11.6.</summary>
+19
View File
@@ -211,6 +211,25 @@ public sealed class StrategyParameters
public static StrategyParameters None { get; } = new([]);
/// <summary>The parameters a text such as <c>fast=20;slow=100</c> gives to a family: its defaults where the text says nothing, or nothing it accepts.</summary>
public static StrategyParameters Of(IStrategyFamily family, string? text)
{
ArgumentNullException.ThrowIfNull(family);
var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal);
var values = new Dictionary<string, decimal>(defaults, StringComparer.Ordinal);
foreach (var part in (text ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var pair = part.Split('=', 2);
if (pair.Length == 2 && values.ContainsKey(pair[0]) && decimal.TryParse(pair[1], NumberStyles.Number, CultureInfo.InvariantCulture, out var value))
{
values[pair[0]] = value / 1.0000000000000000000000000000m; // 10.0 and 10 are the same variant and give the same text.
}
}
var chosen = new StrategyParameters(values);
return family.Accepts(chosen) ? chosen : new StrategyParameters(defaults);
}
public IReadOnlyDictionary<string, decimal> Values => _values;
public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name);
+1 -13
View File
@@ -1533,19 +1533,7 @@ public sealed partial class LiveEngine : IDisposable
public static IStrategy CreateStrategy(string strategy, string? parameters)
{
var family = StrategyCatalog.Find(strategy) ?? throw new ArgumentException("Unknown strategy " + strategy, nameof(strategy));
var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal);
var values = new Dictionary<string, decimal>(defaults, StringComparer.Ordinal);
foreach (var part in (parameters ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var pair = part.Split('=', 2);
if (pair.Length == 2 && values.ContainsKey(pair[0]) && decimal.TryParse(pair[1], NumberStyles.Number, CultureInfo.InvariantCulture, out var value))
{
values[pair[0]] = value;
}
}
var chosen = new StrategyParameters(values);
return family.Accepts(chosen) ? family.Create(chosen) : family.Create(new StrategyParameters(defaults));
return family.Create(StrategyParameters.Of(family, parameters));
}
// ---- Runs ---------------------------------------------------------------------------------------------------