Merge branch 'fase9-fix-ombra' into fase-9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
d26d945818
23 files changed
+577
-126
No files matched your search
@@ -206,7 +206,7 @@
|
|||||||
<td>
|
<td>
|
||||||
@foreach (var l in m.Lines)
|
@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>
|
||||||
<td>@(m.Lines.Max(l => l.Cases) == 0 ? "—" : m.Trust)</td>
|
<td>@(m.Lines.Max(l => l.Cases) == 0 ? "—" : m.Trust)</td>
|
||||||
|
|||||||
@@ -44,7 +44,7 @@
|
|||||||
<tbody>
|
<tbody>
|
||||||
@Row("Esito", x => LabText.Verdict(x.Trial.Verdict))
|
@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("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("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("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))
|
@Row("Rendimento annuo", x => LabText.Percent(x.Report.Metrics.AnnualReturn, 1, true))
|
||||||
|
|||||||
@@ -68,9 +68,15 @@
|
|||||||
var c = r.Currency;
|
var c = r.Currency;
|
||||||
var m = r.Metrics;
|
var m = r.Metrics;
|
||||||
var b = r.Benchmark;
|
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">
|
<section class="panel" aria-labelledby="esito">
|
||||||
<h2 id="esito">Esito del protocollo</h2>
|
<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>
|
<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">
|
<div class="table-wrap">
|
||||||
<table class="table">
|
<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>
|
<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>
|
||||||
|
|
||||||
<section class="panel" aria-labelledby="risultato">
|
<section class="panel" aria-labelledby="risultato">
|
||||||
<h2 id="risultato">Risultato della variante scelta</h2>
|
<h2 id="risultato">Risultato @ofVariant</h2>
|
||||||
<div class="table-wrap">
|
<div class="table-wrap">
|
||||||
<table class="table">
|
<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>
|
<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">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>
|
<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>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<section class="panel" aria-labelledby="anni">
|
<section class="panel" aria-labelledby="anni">
|
||||||
@@ -162,7 +168,7 @@
|
|||||||
<h2 id="convalide">Convalide</h2>
|
<h2 id="convalide">Convalide</h2>
|
||||||
<h3>Sharpe corretto per il numero di prove</h3>
|
<h3>Sharpe corretto per il numero di prove</h3>
|
||||||
@{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); }
|
@{ 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>
|
<h3>Probabilità di sovra-adattamento</h3>
|
||||||
@if (r.Overfitting is { } pbo)
|
@if (r.Overfitting is { } pbo)
|
||||||
@@ -231,9 +237,9 @@
|
|||||||
@foreach (var v in r.Variants)
|
@foreach (var v in r.Variants)
|
||||||
{
|
{
|
||||||
<tr>
|
<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.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.Money(v.NetResult, c, true)</td>
|
||||||
<td class="num">@LabText.Percent(v.MaxDrawdown)</td>
|
<td class="num">@LabText.Percent(v.MaxDrawdown)</td>
|
||||||
<td class="num">@v.Trades</td>
|
<td class="num">@v.Trades</td>
|
||||||
|
|||||||
@@ -39,7 +39,7 @@
|
|||||||
}
|
}
|
||||||
@if (line.InUse is { } used)
|
@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>
|
||||||
<td>@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) {<div>@text</div>}</td>
|
<td>@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) {<div>@text</div>}</td>
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ internal static class ReviewView
|
|||||||
ReviewVerdicts.Passed => "Superata",
|
ReviewVerdicts.Passed => "Superata",
|
||||||
ReviewVerdicts.Rejected => "Non superata",
|
ReviewVerdicts.Rejected => "Non superata",
|
||||||
ReviewVerdicts.Error => "Non riuscita",
|
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
|
public static string? VerdictClass(ReviewLine line) => line.Verdict switch
|
||||||
|
|||||||
@@ -237,7 +237,7 @@ public static class CryptoTrendProtocol
|
|||||||
Verdict = verdict,
|
Verdict = verdict,
|
||||||
Report = report,
|
Report = report,
|
||||||
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
|
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),
|
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
|
||||||
ExpectedSlippageBp = slippage,
|
ExpectedSlippageBp = slippage,
|
||||||
RoundTripCost = Math.Round(2m * (fee + (slippage / 10_000m)), 6),
|
RoundTripCost = Math.Round(2m * (fee + (slippage / 10_000m)), 6),
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ public static class ReviewStatuses
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The figures of a variant on the broad universe.</summary>
|
/// <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>
|
/// <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
|
public sealed record ReviewLine
|
||||||
@@ -41,6 +45,9 @@ public sealed record ReviewLine
|
|||||||
/// <summary>The verdict in words.</summary>
|
/// <summary>The verdict in words.</summary>
|
||||||
public required string Text { get; init; }
|
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 IReadOnlyList<Guid> Trials { get; init; } = [];
|
||||||
|
|
||||||
public ReviewVariant? Chosen { 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).
|
// 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 through = new DateOnly(today.Year, today.Month, 1).AddDays(-1);
|
||||||
var id = await OpenAsync(open, quarter, through, cancellationToken).ConfigureAwait(false);
|
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 (missing is not null)
|
||||||
{
|
{
|
||||||
if (today <= StartOf(today).AddDays(LastDay - 1))
|
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));
|
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) =>
|
private Task<Guid> OpenAsync(Review? open, string quarter, DateOnly through, CancellationToken cancellationToken) =>
|
||||||
db.WriteAsync(async s =>
|
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 costs = await new CostBook(db, clock).TableAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var stage = await stages.GetAsync(CryptoTrendProtocol.Strategy, cancellationToken).ConfigureAwait(false);
|
var stage = await stages.GetAsync(CryptoTrendProtocol.Strategy, cancellationToken).ConfigureAwait(false);
|
||||||
var qualified = stage is { Stage: not StrategyStages.Observation };
|
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);
|
var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), through, cancellationToken).ConfigureAwait(false);
|
||||||
return await db.WriteAsync(async s =>
|
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 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);
|
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,
|
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 previous = (await ListAsync(db, cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Id != id && r.Status == ReviewStatuses.Done);
|
||||||
var now = clock.UtcNow;
|
var now = clock.UtcNow;
|
||||||
var today = Zones.DayIn(now, Zones.Rome);
|
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 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 crypto = await CryptoAsync(id, quarter, missing, trials, cancellationToken).ConfigureAwait(false);
|
||||||
var before = await learning.BaseRatesAsync(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 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 examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false);
|
||||||
|
var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var report = new ReviewReport
|
var report = new ReviewReport
|
||||||
{
|
{
|
||||||
Missing = missing,
|
Missing = missing,
|
||||||
RatesBefore = before,
|
RatesBefore = before,
|
||||||
RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)),
|
RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)),
|
||||||
RestrictionsFrom = Zones.DayIn(from, Zones.Rome),
|
RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome),
|
||||||
Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, cancellationToken).ConfigureAwait(false),
|
Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false),
|
||||||
RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, cancellationToken).ConfigureAwait(false),
|
RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, now, cancellationToken).ConfigureAwait(false),
|
||||||
};
|
};
|
||||||
var lines = new List<ReviewLine>();
|
var lines = new List<ReviewLine>();
|
||||||
foreach (var stage in all)
|
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),
|
Signals = live.Count(e => e.Strategy == stage.Strategy && e.IsLabelled),
|
||||||
Won = live.Count(e => e.Strategy == stage.Strategy && e.Label is { Win: true }),
|
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 =>
|
await db.WriteAsync(async s =>
|
||||||
@@ -315,6 +345,10 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
|
|||||||
LogPublished(_logger, quarter, crypto.Verdict);
|
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)
|
private async Task<CryptoResult> CryptoAsync(Guid id, string quarter, string? missing, IReadOnlyList<Trial> trials, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (missing is not null)
|
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 passed = runs.All(r => r.Report.Passed);
|
||||||
var title = new Review(id, quarter, default, "", null, default, null).Title;
|
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
|
var text = passed
|
||||||
? $"Revisione del {title}: protocollo superato su entrambi gli universi."
|
? $"Revisione del {title}: protocollo superato su entrambi gli universi{used}."
|
||||||
: $"Revisione del {title}: protocollo non superato. {CryptoTrendProtocol.Failures(runs)}.";
|
: $"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);
|
var outcome = CryptoTrendProtocol.Measured(runs[0], CryptoTrendProtocol.Strategy, passed, text, "/laboratorio/revisione/" + id);
|
||||||
return new CryptoResult(passed ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, text, outcome, runs);
|
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;
|
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;
|
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 : stage.Qualification?.Parameters;
|
var used = stage.Stage == StrategyStages.Observation ? null : report.Judged ?? stage.Qualification?.Parameters;
|
||||||
var since = DateOnly.FromDateTime((stage.StageSince ?? DateTimeOffset.MaxValue).UtcDateTime);
|
var since = DateOnly.FromDateTime((stage.StageSince ?? DateTimeOffset.MaxValue).UtcDateTime);
|
||||||
var days = report.Curve.Where(p => p.Day >= since).ToList();
|
var days = report.Curve.Where(p => p.Day >= since).ToList();
|
||||||
return line with
|
return line with
|
||||||
@@ -403,13 +443,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
|
|||||||
return text + " Il rapporto è nel Laboratorio.";
|
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>
|
/// <summary>What a review said and did of a strategy, in a few words.</summary>
|
||||||
public static string ActionText(ReviewLine line)
|
public static string ActionText(ReviewLine line)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(line);
|
ArgumentNullException.ThrowIfNull(line);
|
||||||
return line.Verdict switch
|
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",
|
ReviewVerdicts.Error => "un test non è riuscito, resta valido l'esito precedente",
|
||||||
_ => line.Action switch
|
_ => 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}")]
|
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} waits: {Missing}")]
|
||||||
private static partial void LogWaiting(ILogger logger, string quarter, string 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}")]
|
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} published, crypto_trend: {Verdict}")]
|
||||||
private static partial void LogPublished(ILogger logger, string quarter, string verdict);
|
private static partial void LogPublished(ILogger logger, string quarter, string verdict);
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,11 @@ public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? Fir
|
|||||||
public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark);
|
public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark);
|
||||||
|
|
||||||
/// <summary>A variant of the grid with its full-period figures.</summary>
|
/// <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>
|
/// <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);
|
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>
|
/// <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; }
|
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 string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
|
||||||
|
|
||||||
public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize<BacktestReport>(text, TrialPlan.Json) ?? throw new JsonException("Empty report");
|
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>
|
/// <summary>
|
||||||
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own
|
/// 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
|
/// 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>
|
/// </summary>
|
||||||
public static class TrialRunner
|
public static class TrialRunner
|
||||||
{
|
{
|
||||||
@@ -141,14 +150,22 @@ public static class TrialRunner
|
|||||||
var scores = Validation.PlateauScores(variants, sharpes);
|
var scores = Validation.PlateauScores(variants, sharpes);
|
||||||
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
|
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
|
||||||
var chosen = variants[chosenIndex];
|
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);
|
var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear);
|
||||||
|
|
||||||
progress?.Invoke("costi doppi e tripli, comprare e tenere");
|
progress?.Invoke("costi doppi e tripli, comprare e tenere");
|
||||||
var costs = new List<ReportCosts>();
|
var costs = new List<ReportCosts>();
|
||||||
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
|
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);
|
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));
|
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).
|
// 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 trials = prior.Variants + variants.Count;
|
||||||
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
|
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");
|
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,
|
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}")]);
|
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
|
||||||
|
|
||||||
@@ -220,7 +237,9 @@ public static class TrialRunner
|
|||||||
benchmark,
|
benchmark,
|
||||||
costs,
|
costs,
|
||||||
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
|
[.. 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,
|
walkForward,
|
||||||
combinatorial,
|
combinatorial,
|
||||||
overfitting,
|
overfitting,
|
||||||
@@ -229,12 +248,14 @@ public static class TrialRunner
|
|||||||
lookAhead,
|
lookAhead,
|
||||||
checks,
|
checks,
|
||||||
passed,
|
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,
|
curve,
|
||||||
[.. run.Trades.TakeLast(MaxTrades)],
|
[.. run.Trades.TakeLast(MaxTrades)],
|
||||||
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
|
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
|
||||||
now,
|
now,
|
||||||
watch.Elapsed.TotalSeconds);
|
watch.Elapsed.TotalSeconds)
|
||||||
|
{ Judged = plan.Judged is null ? null : judged.ToString() };
|
||||||
if (StrategyPipeline.ResearchShare(family.Id) is not null)
|
if (StrategyPipeline.ResearchShare(family.Id) is not null)
|
||||||
{
|
{
|
||||||
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||||
@@ -243,12 +264,12 @@ public static class TrialRunner
|
|||||||
report = report with
|
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),
|
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))],
|
.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);
|
dsr.Value, pbo?.Probability, sharpes);
|
||||||
return (report, summary);
|
return (report, summary);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
/// <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)
|
public readonly record struct Moments(int Count, double Mean, double StandardDeviation, double Skewness, double Kurtosis)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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>
|
/// <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; }
|
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()
|
public static readonly JsonSerializerOptions Json = new()
|
||||||
{
|
{
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ public sealed partial class MarketDataService : IDisposable
|
|||||||
private readonly DataDirectory? _data;
|
private readonly DataDirectory? _data;
|
||||||
private readonly HttpClient _http;
|
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 HttpClient _signed;
|
||||||
private readonly Func<IWebSocketTransport>? _sockets;
|
private readonly Func<IWebSocketTransport>? _sockets;
|
||||||
private readonly ILogger _logger;
|
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>
|
/// <summary>
|
||||||
/// The sectors of the companies from the SEC (SPEC 8.7). Without the user's contact, which the SEC asks for in the
|
/// 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.
|
/// request, nothing is asked.
|
||||||
@@ -240,7 +243,7 @@ public sealed partial class MarketDataService : IDisposable
|
|||||||
|
|
||||||
await StepAsync(Edgar.Source, async () =>
|
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";
|
return $"settori: {read} letti";
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ public sealed record Example(Guid Id, string Strategy, string Symbol, string Sou
|
|||||||
|
|
||||||
public CaseLabel? Label { get; init; }
|
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>
|
/// <summary>A label that can train: the operation started and closed.</summary>
|
||||||
[JsonIgnore]
|
[JsonIgnore]
|
||||||
public bool IsLabelled => Label is { Win: not null, ClosedDay: not null };
|
public bool IsLabelled => Label is { Win: not null, ClosedDay: not null };
|
||||||
|
|||||||
@@ -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 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 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 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);
|
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;
|
_failed = failed;
|
||||||
_outside = outside;
|
_outside = outside;
|
||||||
_collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
|
_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>
|
/// <summary>
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ public sealed class LearningStore(Database db, IClock clock)
|
|||||||
{
|
{
|
||||||
private const string Columns =
|
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, " +
|
"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>
|
/// <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)
|
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"),
|
DecisionId = r.IdOrNull("decision_id"),
|
||||||
Multiplier = r.Measure("multiplier"),
|
Multiplier = r.Measure("multiplier"),
|
||||||
Label = label,
|
Label = label,
|
||||||
|
LabelledAt = r.MomentOrNull("labelled_at"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -46,13 +46,21 @@ public static class RestrictionBalance
|
|||||||
_ => code,
|
_ => code,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>The balance of the entries blocked; each example counts once, under its strictest row.</summary>
|
/// <summary>
|
||||||
public static RestrictionReport Of(IReadOnlyList<BlockedEntry> blocked, IReadOnlyList<Example> examples, IReadOnlyList<HeldTrade> trades, IReadOnlyDictionary<string, double> capitals)
|
/// 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(blocked);
|
||||||
ArgumentNullException.ThrowIfNull(examples);
|
ArgumentNullException.ThrowIfNull(examples);
|
||||||
ArgumentNullException.ThrowIfNull(trades);
|
ArgumentNullException.ThrowIfNull(trades);
|
||||||
ArgumentNullException.ThrowIfNull(capitals);
|
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 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)>();
|
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))
|
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();
|
.OrderByDescending(e => e.At).FirstOrDefault();
|
||||||
if (example is null || own.Any(t => t.OpenedAt < block.At && (t.ClosedAt is null || t.ClosedAt > block.At)))
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,19 +90,28 @@ public static class RestrictionBalance
|
|||||||
var first = blocks[0].At;
|
var first = blocks[0].At;
|
||||||
var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue;
|
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.
|
// In observation nothing is ever bought: an entry only put off would have been made at its end. A later block of
|
||||||
var delayed = example.Stage == StrategyStages.Observation
|
// 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)
|
? blocks.All(b => b.Postponed)
|
||||||
: trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last);
|
: trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last);
|
||||||
if (delayed)
|
DateTimeOffset? settled = delayed && !observed
|
||||||
{
|
? trades.Where(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first).Min(t => t.OpenedAt)
|
||||||
lines[code] = line with { Delayed = line.Delayed + 1 };
|
: example.Label is null ? null : example.LabelledAt > first ? example.LabelledAt : last > first ? last : first;
|
||||||
}
|
if (settled is not { } known || known > until)
|
||||||
else if (example.Label is not { } label)
|
|
||||||
{
|
{
|
||||||
lines[code] = line with { Open = line.Open + 1 };
|
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 };
|
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)]);
|
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>
|
/// <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, CancellationToken cancellationToken)
|
public static async Task<RestrictionReport> LoadAsync(Database db, IClock clock, DateTimeOffset from, DateTimeOffset until, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(db);
|
ArgumentNullException.ThrowIfNull(db);
|
||||||
var rows = await db.ReadAsync(s => s.QueryAsync(
|
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")),
|
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>();
|
var blocked = new List<BlockedEntry>();
|
||||||
foreach (var row in rows)
|
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",
|
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);
|
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();
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,6 +66,12 @@ public sealed record ShadowBook
|
|||||||
|
|
||||||
public string Day { get; init; } = "";
|
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 IReadOnlyDictionary<string, double> Returns { get; init; } = new Dictionary<string, double>();
|
||||||
|
|
||||||
public static string KeyOf(string strategy) => "shadow_book:" + strategy;
|
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 sealed record ShadowInput(IReadOnlyList<ShadowBook> OtherBooks, IReadOnlyDictionary<string, string> Sectors)
|
||||||
{
|
{
|
||||||
public static readonly ShadowInput Nothing = new([], new Dictionary<string, string>());
|
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>
|
/// <summary>
|
||||||
/// The improvements beside one decision. Both steps return the very list they were given: what they find is written
|
/// 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.
|
/// apart, and a failure of theirs changes nothing.
|
||||||
/// </summary>
|
/// </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 = [];
|
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; }
|
public ShadowBook? Book { get; private set; }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>After the collector, on what the strategy proposed.</summary>
|
/// <summary>After the collector, on what the strategy proposed.</summary>
|
||||||
public IIntentStage OnProposals => new Step(day, Proposals);
|
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);
|
Book = ShadowBook.Of(context, weights, share) with { Stage = stage };
|
||||||
if (ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
|
if (!input.Whole || ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
|
||||||
{
|
{
|
||||||
return;
|
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>
|
/// <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>
|
/// <summary>Fewer months than these give no interval: the signals of a month move together, so a month counts as one.</summary>
|
||||||
public (double Low, double High)? Interval => Mean is { } m && Error is { } e ? (m - (1.96 * e), m + (1.96 * e)) : null;
|
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>
|
/// <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 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>
|
/// <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);
|
private readonly CompanySectors _sectors = new(db, clock);
|
||||||
|
|
||||||
/// <summary>What the decision of a strategy needs from outside it.</summary>
|
/// <summary>
|
||||||
public async Task<ShadowInput> InputAsync(string strategy, DateOnly day, CancellationToken cancellationToken)
|
/// 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 books = new List<ShadowBook>();
|
||||||
|
var whole = true;
|
||||||
foreach (var (name, _, _) in StrategyNames.Base.Where(b => b.Name != strategy))
|
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
|
if (await store.StateAsync<ShadowBook>(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is not { } last)
|
||||||
&& Math.Abs(day.DayNumber - BarStore.ParseDay(book.Day).DayNumber) <= ShadowBook.MaxAgeDays)
|
{
|
||||||
|
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);
|
books.Add(book);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var sectors = strategy == StrategyNames.EquityMomentum ? await _sectors.GroupsAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<string, string>();
|
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
|
private sealed record Stored
|
||||||
{
|
{
|
||||||
public IReadOnlyDictionary<string, double> Numbers { get; init; } = new Dictionary<string, double>();
|
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)
|
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);
|
private sealed record Open(Guid Id, string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, Stored Data);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -512,26 +554,27 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The mean effect and its error, over which the signals decided in the same month count as one: they move together,
|
/// 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>
|
/// </summary>
|
||||||
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
|
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
|
||||||
{
|
{
|
||||||
if (values.Count == 0)
|
if (values.Count == 0)
|
||||||
{
|
{
|
||||||
return new ImprovementLine(label, 0, null, null);
|
return new ImprovementLine(label, 0, 0, null, null);
|
||||||
}
|
|
||||||
|
|
||||||
var mean = values.Average(v => v.Effect);
|
|
||||||
if (values.Count < 2)
|
|
||||||
{
|
|
||||||
return new ImprovementLine(label, values.Count, mean, null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var n = values.Count;
|
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 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;
|
if (months.Count < ImprovementLine.MinMonths)
|
||||||
return new ImprovementLine(label, n, mean, Math.Max(simple, clustered));
|
{
|
||||||
|
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>
|
/// <summary>The improvements with enough cases for a sentence, among the discoveries of SPEC 11.6.</summary>
|
||||||
|
|||||||
@@ -211,6 +211,25 @@ public sealed class StrategyParameters
|
|||||||
|
|
||||||
public static StrategyParameters None { get; } = new([]);
|
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 IReadOnlyDictionary<string, decimal> Values => _values;
|
||||||
|
|
||||||
public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name);
|
public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name);
|
||||||
|
|||||||
@@ -1533,19 +1533,7 @@ public sealed partial class LiveEngine : IDisposable
|
|||||||
public static IStrategy CreateStrategy(string strategy, string? parameters)
|
public static IStrategy CreateStrategy(string strategy, string? parameters)
|
||||||
{
|
{
|
||||||
var family = StrategyCatalog.Find(strategy) ?? throw new ArgumentException("Unknown strategy " + strategy, nameof(strategy));
|
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);
|
return family.Create(StrategyParameters.Of(family, parameters));
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Runs ---------------------------------------------------------------------------------------------------
|
// ---- Runs ---------------------------------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ public sealed class LaboratoryScreenTests
|
|||||||
Live = new Anubis.Trading.StageFigures(clock.UtcNow, 0.031m, 0.05m, 6.2m, 4, 0.1m), ExpectedFall = 0.32m, ExpectedSlippageBp = 7m, BacktestOverSameDays = 0.025,
|
Live = new Anubis.Trading.StageFigures(clock.UtcNow, 0.031m, 0.05m, 6.2m, 4, 0.1m), ExpectedFall = 0.32m, ExpectedSlippageBp = 7m, BacktestOverSameDays = 0.025,
|
||||||
},
|
},
|
||||||
new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMomentum, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", Signals = 10, Won = 6 },
|
new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMomentum, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", Signals = 10, Won = 6 },
|
||||||
|
new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMeanrev, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", NoProtocol = true },
|
||||||
],
|
],
|
||||||
RatesBefore = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 },
|
RatesBefore = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 },
|
||||||
RatesAfter = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.398 },
|
RatesAfter = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.398 },
|
||||||
@@ -120,7 +121,7 @@ public sealed class LaboratoryScreenTests
|
|||||||
{
|
{
|
||||||
"1º trimestre 2027", "Non superata", "Non superata, resta in simulazione e non può passare ai soldi veri", $"href=\"/laboratorio/{trial}\"", "calo massimo 38,2%, oltre il 25%", "Variante in uso: coin_vol 15",
|
"1º trimestre 2027", "Non superata", "Non superata, resta in simulazione e non può passare ai soldi veri", $"href=\"/laboratorio/{trial}\"", "calo massimo 38,2%, oltre il 25%", "Variante in uso: coin_vol 15",
|
||||||
"Non cambia da sola", "Risultato +3,1%; il backtest negli stessi giorni circa +2,5%.", "Scostamento dei prezzi 6,2 punti base, atteso 7 punti base.", "decisioni identiche al backtest del giorno dopo 90,0%",
|
"Non cambia da sola", "Risultato +3,1%; il backtest negli stessi giorni circa +2,5%.", "Scostamento dei prezzi 6,2 punti base, atteso 7 punti base.", "decisioni identiche al backtest del giorno dopo 90,0%",
|
||||||
"In attesa dei dati", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}",
|
"In attesa dei dati", "Non riprovata</span>", "Non riprovata: il protocollo per le azioni arriva con una versione successiva", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}",
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
StringAssert.Contains(page, part, $"Missing \"{part}\".");
|
StringAssert.Contains(page, part, $"Missing \"{part}\".");
|
||||||
|
|||||||
@@ -285,7 +285,7 @@ public sealed class NewsRulesTests
|
|||||||
var rows = await live.Rig.QueryAsync("SELECT symbol, stage, outcome, reasons FROM decisions WHERE stage = @o", r => (Symbol: r.TextOrNull("symbol"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons")),
|
var rows = await live.Rig.QueryAsync("SELECT symbol, stage, outcome, reasons FROM decisions WHERE stage = @o", r => (Symbol: r.TextOrNull("symbol"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons")),
|
||||||
("o", DecisionStages.Order)).ConfigureAwait(false);
|
("o", DecisionStages.Order)).ConfigureAwait(false);
|
||||||
CollectionAssert.AreEquivalent(new[] { "ETH-EUR", "SOL-EUR" }, rows.Where(r => r.Outcome == DecisionOutcomes.Refused && r.Reasons.Contains(NewsReasons.Severe, StringComparison.Ordinal)).Select(r => r.Symbol).ToList());
|
CollectionAssert.AreEquivalent(new[] { "ETH-EUR", "SOL-EUR" }, rows.Where(r => r.Outcome == DecisionOutcomes.Refused && r.Reasons.Contains(NewsReasons.Severe, StringComparison.Ordinal)).Select(r => r.Symbol).ToList());
|
||||||
var balance = await Anubis.Learning.RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none).ConfigureAwait(false);
|
var balance = await Anubis.Learning.RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, live.Rig.Clock.UtcNow, _none).ConfigureAwait(false);
|
||||||
Assert.AreEqual(2, balance.Lines.Single().Open);
|
Assert.AreEqual(2, balance.Lines.Single().Open);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,22 +35,25 @@ public sealed class QuarterlyReviewTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A report of the protocol on those coins, whose verdict each test chooses.
|
// A report of the protocol on those coins, whose verdict each test chooses.
|
||||||
private static readonly Lazy<Task<BacktestReport>> _report = new(async () =>
|
private static readonly Lazy<Task<BacktestReport>> _report = new(async () => (await TrialAsync(null).ConfigureAwait(false)).Report);
|
||||||
|
|
||||||
|
private static async Task<(BacktestReport Report, TrialSummary Summary)> TrialAsync(string? judged)
|
||||||
{
|
{
|
||||||
var folder = TempFolder.Create("review-report");
|
var folder = TempFolder.Create("review-report");
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await WriteHistoryAsync(folder).ConfigureAwait(false);
|
await WriteHistoryAsync(folder).ConfigureAwait(false);
|
||||||
var (plan, _) = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
|
var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
|
||||||
CryptoTrendProtocol.Capital, null), At(2027, 1, 5));
|
CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan with
|
||||||
|
{ Judged = judged };
|
||||||
var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false);
|
var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false);
|
||||||
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5)).Report;
|
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5));
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
TempFolder.Delete(folder);
|
TempFolder.Delete(folder);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
private sealed class ReviewRig : IAsyncDisposable
|
private sealed class ReviewRig : IAsyncDisposable
|
||||||
{
|
{
|
||||||
@@ -64,6 +67,8 @@ public sealed class QuarterlyReviewTests
|
|||||||
|
|
||||||
public string? Missing { get; set; }
|
public string? Missing { get; set; }
|
||||||
|
|
||||||
|
public Exception? Failure { get; set; }
|
||||||
|
|
||||||
public List<DateOnly> Prepared { get; } = [];
|
public List<DateOnly> Prepared { get; } = [];
|
||||||
|
|
||||||
public Database Db => Live.Rig.Db;
|
public Database Db => Live.Rig.Db;
|
||||||
@@ -96,7 +101,7 @@ public sealed class QuarterlyReviewTests
|
|||||||
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
|
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
|
||||||
{
|
{
|
||||||
Prepared.Add(to);
|
Prepared.Add(to);
|
||||||
return Task.FromResult(Missing);
|
return Failure is { } failure ? Task.FromException<string?>(failure) : Task.FromResult(Missing);
|
||||||
});
|
});
|
||||||
Lab.ReviewTrialEnded = Review.ConcludeAsync;
|
Lab.ReviewTrialEnded = Review.ConcludeAsync;
|
||||||
}
|
}
|
||||||
@@ -226,6 +231,33 @@ public sealed class QuarterlyReviewTests
|
|||||||
Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
|
Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AnErrorWhilePreparingTheHistoryIsAMissingReasonLikeTheOthers()
|
||||||
|
{
|
||||||
|
await using var rig = await ReviewRig.CreateAsync(history: false);
|
||||||
|
await rig.NightAsync(At(2026, 12, 10));
|
||||||
|
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
|
||||||
|
await rig.NightAsync(At(2027, 1, 5));
|
||||||
|
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
|
||||||
|
|
||||||
|
// A wait that ran out is an error too; the stop of the program is not, and the review stays as it is.
|
||||||
|
rig.Failure = new TaskCanceledException();
|
||||||
|
await rig.NightAsync(At(2027, 1, 6));
|
||||||
|
rig.Clock.Set(At(2027, 1, 17));
|
||||||
|
using var stop = new CancellationTokenSource();
|
||||||
|
await stop.CancelAsync();
|
||||||
|
await Assert.ThrowsAsync<OperationCanceledException>(() => rig.Review.RunIfDueAsync(stop.Token));
|
||||||
|
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
|
||||||
|
|
||||||
|
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
|
||||||
|
await rig.NightAsync(At(2027, 1, 18));
|
||||||
|
var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
|
||||||
|
Assert.AreEqual(ReviewStatuses.Done, done.Status);
|
||||||
|
Assert.AreEqual("lo storico non si è potuto preparare per un errore", done.Report!.Missing);
|
||||||
|
Assert.AreEqual("Non riprovata, dati mancanti: lo storico non si è potuto preparare per un errore. Resta valido l'esito precedente.", done.Report.Strategies.Single().Text);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- The run ----------------------------------------------------------------------------------------------------
|
// ---- The run ----------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
/// <summary>The real trials, with a restart in the middle: each trial counts once, the review concludes once.</summary>
|
/// <summary>The real trials, with a restart in the middle: each trial counts once, the review concludes once.</summary>
|
||||||
@@ -406,6 +438,78 @@ public sealed class QuarterlyReviewTests
|
|||||||
Assert.IsTrue((await DemotionAsync()).Met);
|
Assert.IsTrue((await DemotionAsync()).Met);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- The variant in use -----------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>The grid says how much was searched; the figures, the checks and the curve are those of the variant the strategy works with.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public async Task ATrialJudgesTheVariantInUseAndCountsTheSameTries()
|
||||||
|
{
|
||||||
|
var chosen = await _report.Value;
|
||||||
|
Assert.IsNull(chosen.Judged);
|
||||||
|
var used = chosen.Variants.First(v => !v.Chosen && v.NetResult != chosen.Metrics.NetResult);
|
||||||
|
var (report, summary) = await TrialAsync(used.Parameters);
|
||||||
|
Assert.AreEqual((used.Parameters, chosen.Chosen), (report.Judged, report.Chosen));
|
||||||
|
Assert.AreEqual((used.NetResult, used.MaxDrawdown), (report.Metrics.NetResult, report.Metrics.MaxDrawdown));
|
||||||
|
Assert.AreEqual(used.NetResult, report.Costs.Single(c => c.Multiplier == 1m).NetResult);
|
||||||
|
Assert.AreNotEqual(chosen.Costs.Single(c => c.Multiplier == 2m).NetResult, report.Costs.Single(c => c.Multiplier == 2m).NetResult);
|
||||||
|
Assert.AreEqual(used.MaxDrawdown, report.Checks.Single(c => c.Key == ReportCheckKeys.Drawdown).Value);
|
||||||
|
Assert.AreEqual(used.Sharpe, report.DeflatedSharpe.Sharpe);
|
||||||
|
Assert.AreEqual(report.DeflatedSharpe.Value, report.Checks.Single(c => c.Key == ReportCheckKeys.DeflatedSharpe).Value);
|
||||||
|
Assert.AreEqual(CryptoTrendProtocol.Capital + used.NetResult, report.Curve[^1].Equity, 0.01m);
|
||||||
|
CollectionAssert.AreNotEqual(chosen.ExpectedPathP5!.ToList(), report.ExpectedPathP5!.ToList());
|
||||||
|
Assert.AreEqual((used.Parameters, used.NetResult), (summary.Chosen, summary.NetResult));
|
||||||
|
|
||||||
|
// What the grid decided stays.
|
||||||
|
CollectionAssert.AreEqual(chosen.Variants.ToList(), report.Variants.ToList());
|
||||||
|
Assert.AreEqual(chosen.Overfitting, report.Overfitting);
|
||||||
|
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark), (report.TrialsCounted, report.DeflatedSharpe.Benchmark));
|
||||||
|
Assert.IsFalse(report.Limitations.Any(l => l.Contains("griglia", StringComparison.Ordinal)));
|
||||||
|
|
||||||
|
// Not among the variants of the grid: judged all the same, and it says so.
|
||||||
|
var (outside, tries) = await TrialAsync("coin_vol=12;max_stop=20");
|
||||||
|
var added = outside.Variants.Single(v => v.OutsideGrid);
|
||||||
|
Assert.AreEqual(("coin_vol=12;max_stop=20", false), (added.Parameters, added.Chosen));
|
||||||
|
Assert.AreEqual((added.NetResult, added.MaxDrawdown), (outside.Metrics.NetResult, outside.Metrics.MaxDrawdown));
|
||||||
|
CollectionAssert.AreEqual(chosen.Variants.ToList(), outside.Variants.Where(v => !v.OutsideGrid).ToList());
|
||||||
|
Assert.HasCount(chosen.Variants.Count, tries.VariantSharpes);
|
||||||
|
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark, chosen.Overfitting), (outside.TrialsCounted, outside.DeflatedSharpe.Benchmark, outside.Overfitting));
|
||||||
|
Assert.Contains("La variante in uso non è nella griglia", string.Join(" ", outside.Limitations));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
[DataRow(StrategyStages.Observation, "coin_vol=10;max_stop=20", null)]
|
||||||
|
[DataRow(StrategyStages.Simulation, "coin_vol=10;max_stop=20", "coin_vol=10;max_stop=20")]
|
||||||
|
[DataRow(StrategyStages.Simulation, "coin_vol=12.0;max_stop=20", "coin_vol=12;max_stop=20")]
|
||||||
|
[DataRow(StrategyStages.Simulation, null, "coin_vol=15;max_stop=15")]
|
||||||
|
public async Task ThePlanOfAReviewFixesTheVariantInUse(string stage, string? parameters, string? judged)
|
||||||
|
{
|
||||||
|
await using var rig = await ReviewRig.CreateAsync(stage, qualification: Old(true) with { Parameters = parameters });
|
||||||
|
var review = await rig.OpenAsync();
|
||||||
|
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(Old(true) with { Parameters = "coin_vol=20;max_stop=20" }, Qualification.Json)))), _none);
|
||||||
|
rig.Start();
|
||||||
|
var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none);
|
||||||
|
Assert.HasCount(2, trials);
|
||||||
|
Assert.IsTrue(trials.All(t => t.PlanIntact && t.Plan.Judged == judged && t.Variants == 9), string.Join(" ", trials.Select(t => t.Plan.Judged)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheVerdictOnAStrategyWithCapitalIsOfTheVariantInUse()
|
||||||
|
{
|
||||||
|
const string used = "coin_vol=12;max_stop=20";
|
||||||
|
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true) with { Parameters = used });
|
||||||
|
var review = await rig.ReviewAsync(passed: true, r => r with { Judged = used, Variants = [.. r.Variants, new ReportVariant(used, 0.05, 0, 321m, 0.11, 7, false) { OutsideGrid = true }] });
|
||||||
|
var line = review.Report!.Strategies.Single();
|
||||||
|
Assert.AreEqual((ReviewVerdicts.Passed, ReviewActions.Confirmed), (line.Verdict, line.Action));
|
||||||
|
Assert.AreEqual("Revisione del 1º trimestre 2027: protocollo superato su entrambi gli universi con la variante in uso. La variante in uso non è nella griglia: è giudicata lo stesso.", line.Text);
|
||||||
|
Assert.AreEqual((used, 321m, true), (line.InUse!.Parameters, line.InUse.NetResult, line.InUse.OutsideGrid));
|
||||||
|
Assert.AreEqual((await _report.Value).Chosen, line.Chosen!.Parameters);
|
||||||
|
var outcome = JsonSerializer.Deserialize<Qualification>((await rig.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT qualification FROM review_outcomes", r => r.Json("qualification").Text), _none))!, Qualification.Json)!;
|
||||||
|
Assert.AreEqual(used, outcome.Parameters, "the parameters the figures are of");
|
||||||
|
}
|
||||||
|
|
||||||
internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s =>
|
internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s =>
|
||||||
{
|
{
|
||||||
var id = Ids.NewId(clock);
|
var id = Ids.NewId(clock);
|
||||||
@@ -433,6 +537,21 @@ public sealed class QuarterlyReviewTests
|
|||||||
var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
|
var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
|
||||||
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action));
|
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action));
|
||||||
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none));
|
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none));
|
||||||
|
Assert.AreEqual((false, "non riprovata, mancano i dati"), (stock.NoProtocol, QuarterlyReview.ActionText(stock)));
|
||||||
|
|
||||||
|
// With the bars collected what is missing is the protocol, not the data.
|
||||||
|
var share = await new InstrumentCatalog(rig.Db, rig.Clock).EnsureAsync(StrategyData.Share("AAA"), _none);
|
||||||
|
await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(share.Id, [new DailyBar(new DateOnly(2027, 1, 4), 50, 51, 49, 50, 1000)], "test", _none);
|
||||||
|
await rig.NightAsync(At(2027, 4, 5));
|
||||||
|
await rig.EndAsync((await QuarterlyReview.ListAsync(rig.Db, _none))[0], passed: false);
|
||||||
|
await rig.Review.ConcludeAsync(_none);
|
||||||
|
stock = (await QuarterlyReview.ListAsync(rig.Db, _none))[0].Report!.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
|
||||||
|
const string text = "non riprovata: il protocollo per le azioni arriva con una versione successiva";
|
||||||
|
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None, true), (stock.Verdict, stock.Action, stock.NoProtocol));
|
||||||
|
Assert.AreEqual(text, QuarterlyReview.ActionText(stock));
|
||||||
|
Assert.StartsWith("Non riprovata: il protocollo per le azioni", stock.Text);
|
||||||
|
Assert.Contains(text, (await NewsRulesTests.DiaryAsync(rig.Db)).Last(m => m.StartsWith("Revisione trimestrale pronta (2º", StringComparison.Ordinal)));
|
||||||
|
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review' AND message LIKE '%versione successiva%'"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Base rates -------------------------------------------------------------------------------------------------
|
// ---- Base rates -------------------------------------------------------------------------------------------------
|
||||||
@@ -619,6 +738,50 @@ public sealed class QuarterlyReviewTests
|
|||||||
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
|
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>A block is of the period in which its outcome became known, so the periods add up to the whole.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ThePeriodsOfTheBalanceAddUpToTheWhole()
|
||||||
|
{
|
||||||
|
var first = _t0.AddDays(3);
|
||||||
|
var second = _t0.AddDays(30);
|
||||||
|
var early = Case("AAA", true, 0.05, 2) with { LabelledAt = _t0.AddDays(2.5) };
|
||||||
|
var lost = Case("BBB", false, -0.1, 5) with { LabelledAt = _t0.AddDays(6) };
|
||||||
|
var off = Case("CCC", false, -0.2, 2) with { LabelledAt = first.AddDays(1) };
|
||||||
|
var open = Case("DDD", null, null, null, labelled: false);
|
||||||
|
var bought = Case("EEE", false, -0.2, 5) with { LabelledAt = _t0.AddDays(6) };
|
||||||
|
var seen = Case("FFF", false, -0.2, 5, stage: StrategyStages.Observation) with { LabelledAt = _t0.AddDays(6) };
|
||||||
|
var never = Case("GGG", null, null, 1) with { LabelledAt = _t0.AddDays(1) };
|
||||||
|
IReadOnlyList<BlockedEntry> blocks =
|
||||||
|
[
|
||||||
|
.. new[] { early, lost, off, open, bought, never }.Select(e => Block(e, NewsReasons.Severe)), Block(seen, CorrectiveReasons.CalendarEvent, postponed: true),
|
||||||
|
new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, _t0), new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, first.AddDays(2)),
|
||||||
|
];
|
||||||
|
RestrictionReport Of(DateTimeOffset from, DateTimeOffset until) => RestrictionBalance.Of(blocks, [early, lost, off, open, bought, seen, never], [new HeldTrade(Crypto, "EEE", _t0.AddDays(4), null)], _capital, from, until);
|
||||||
|
RestrictionLine? Line(RestrictionReport r, string code) => r.Lines.SingleOrDefault(l => l.Code == code);
|
||||||
|
var (one, two, ever) = (Of(DateTimeOffset.UnixEpoch, first), Of(first, second), Of(DateTimeOffset.UnixEpoch, second));
|
||||||
|
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 1, 0m, 40m, 4, 1, 0, 1), Line(one, NewsReasons.Severe), "what was not known yet is open");
|
||||||
|
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 240m, 0m, 1, 0, 1, 1), Line(two, NewsReasons.Severe), "known after the first review, even what closed before it");
|
||||||
|
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 3, 240m, 40m, 1, 1, 1, 2), Line(ever, NewsReasons.Severe));
|
||||||
|
Assert.AreEqual(1, Line(one, CorrectiveReasons.CalendarEvent)!.Open);
|
||||||
|
Assert.AreEqual((1, 0), (Line(two, CorrectiveReasons.CalendarEvent)!.Delayed, Line(two, CorrectiveReasons.CalendarEvent)!.Open));
|
||||||
|
Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheFirstReviewCountsTheRestrictionsFromTheStart()
|
||||||
|
{
|
||||||
|
await using var rig = await ReviewRig.CreateAsync();
|
||||||
|
rig.Clock.Set(new DateTimeOffset(2026, 8, 15, 10, 0, 0, TimeSpan.Zero));
|
||||||
|
await rig.Db.WriteAsync(s => DecisionLog.WriteAsync(s, rig.Clock, new DecisionRow(Guid.NewGuid(), Crypto, null, "ETH-EUR", DecisionStages.Order, DecisionOutcomes.Refused, [NewsReasons.Severe],
|
||||||
|
new Dictionary<string, object?>(), rig.Clock.UtcNow), _none), _none);
|
||||||
|
var report = (await rig.ReviewAsync(passed: false)).Report!;
|
||||||
|
Assert.AreEqual(1, report.RestrictionsEver.Lines.Single().Increases);
|
||||||
|
Assert.AreEqual(report.RestrictionsEver.Lines.Single(), report.Restrictions.Lines.SingleOrDefault());
|
||||||
|
Assert.AreEqual(new DateOnly(2026, 8, 15), report.RestrictionsFrom);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>
|
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
[TestCategory(Category.Integration)]
|
[TestCategory(Category.Integration)]
|
||||||
@@ -634,10 +797,13 @@ public sealed class QuarterlyReviewTests
|
|||||||
await live.DayAsync(day);
|
await live.DayAsync(day);
|
||||||
var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList();
|
var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList();
|
||||||
Assert.HasCount(2, cases);
|
Assert.HasCount(2, cases);
|
||||||
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
|
var first = live.Rig.Clock.UtcNow;
|
||||||
|
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none);
|
||||||
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open);
|
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open);
|
||||||
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open);
|
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open);
|
||||||
|
|
||||||
|
// The outcomes arrive after the first review.
|
||||||
|
live.Rig.Clock.Set(first.AddDays(20));
|
||||||
foreach (var e in cases)
|
foreach (var e in cases)
|
||||||
{
|
{
|
||||||
var loses = e.Symbol == "ETH-EUR";
|
var loses = e.Symbol == "ETH-EUR";
|
||||||
@@ -645,11 +811,15 @@ public sealed class QuarterlyReviewTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto];
|
var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto];
|
||||||
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
|
var now = live.Rig.Clock.UtcNow;
|
||||||
|
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, now, _none);
|
||||||
decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2);
|
decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2);
|
||||||
Assert.IsGreaterThan(0m, r.Avoided);
|
Assert.IsGreaterThan(0m, r.Avoided);
|
||||||
Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m);
|
Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m);
|
||||||
Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m);
|
Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m);
|
||||||
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, live.Rig.Clock.UtcNow.AddDays(1), _none)).IsEmpty);
|
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, now, now.AddDays(1), _none)).IsEmpty, "each outcome in one period only");
|
||||||
|
var since = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, first, now, _none);
|
||||||
|
Assert.AreEqual((r.Avoided, r.GivenUp), (since.Avoided, since.GivenUp), "blocked before the first review, known after it");
|
||||||
|
Assert.AreEqual(2, (await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none)).Lines.Sum(l => l.Open));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,19 +271,9 @@ public sealed partial class SecurityTests
|
|||||||
[TestCategory(Category.Integration)]
|
[TestCategory(Category.Integration)]
|
||||||
public async Task AKeyNeverFollowsARedirect()
|
public async Task AKeyNeverFollowsARedirect()
|
||||||
{
|
{
|
||||||
var builder = WebApplication.CreateSlimBuilder();
|
|
||||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
|
||||||
await using var other = builder.Build();
|
|
||||||
var reached = 0;
|
var reached = 0;
|
||||||
other.MapFallback(() => Interlocked.Increment(ref reached));
|
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
|
||||||
await other.StartAsync();
|
await using var broker = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path, permanent: false, preserveMethod: true));
|
||||||
var target = other.Urls.Single();
|
|
||||||
|
|
||||||
builder = WebApplication.CreateSlimBuilder();
|
|
||||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
|
||||||
await using var broker = builder.Build();
|
|
||||||
broker.MapFallback((HttpContext c) => Results.Redirect(target + c.Request.Path, permanent: false, preserveMethod: true));
|
|
||||||
await broker.StartAsync();
|
|
||||||
var address = new Uri(broker.Urls.Single());
|
var address = new Uri(broker.Urls.Single());
|
||||||
|
|
||||||
using var http = Outgoing.KeyedClient();
|
using var http = Outgoing.KeyedClient();
|
||||||
@@ -298,6 +288,32 @@ public sealed partial class SecurityTests
|
|||||||
Assert.AreEqual(0, reached, "The other host must never be reached.");
|
Assert.AreEqual(0, reached, "The other host must never be reached.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task<WebApplication> FallbackAsync(Func<HttpContext, IResult> answer)
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateSlimBuilder();
|
||||||
|
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||||
|
var app = builder.Build();
|
||||||
|
app.MapFallback(answer);
|
||||||
|
await app.StartAsync();
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The contact for the SEC is the user's own e-mail (ADR 0020): another host must never see it, on the client the service really uses.</summary>
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheContactOfTheSecNeverFollowsARedirect()
|
||||||
|
{
|
||||||
|
var reached = 0;
|
||||||
|
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
|
||||||
|
await using var sec = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path));
|
||||||
|
await using var test = await DatabaseTests.MigratedAsync();
|
||||||
|
var bus = new EventBus();
|
||||||
|
using var market = new MarketDataService(test.Db, SystemClock.Instance, bus, new SettingsStore(test.Db, SystemClock.Instance, bus), new SecretStore(test.Db, SystemClock.Instance, new byte[32]), null);
|
||||||
|
var agent = new Dictionary<string, string> { ["User-Agent"] = Edgar.UserAgent("prova@esempio.it")! };
|
||||||
|
await Assert.ThrowsAsync<MarketDataException>(() => market.Sec.GetBytesAsync(new Uri(sec.Urls.Single() + "/files/company_tickers"), null, agent, CancellationToken.None));
|
||||||
|
Assert.AreEqual(0, reached);
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
[TestCategory(Category.Unit)]
|
[TestCategory(Category.Unit)]
|
||||||
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
|
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
|
||||||
|
|||||||
@@ -33,10 +33,11 @@ public sealed class ShadowTests
|
|||||||
|
|
||||||
private static Intent Entry(string symbol, double strength = 0, decimal weight = 0.1m) => new(symbol, weight, "entry") { StopOffset = 1m, Strength = strength };
|
private static Intent Entry(string symbol, double strength = 0, decimal weight = 0.1m) => new(symbol, weight, "entry") { StopOffset = 1m, Strength = strength };
|
||||||
|
|
||||||
private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList<Intent> intents, ShadowInput? input = null, Func<StrategyContext, Intent, double?>? probability = null)
|
private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList<Intent> intents, ShadowInput? input = null, Func<StrategyContext, Intent, double?>? probability = null,
|
||||||
|
string stage = StrategyStages.Observation)
|
||||||
{
|
{
|
||||||
var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day);
|
var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day);
|
||||||
var turn = new ShadowTurn(strategy, context.Day, collector, input ?? ShadowInput.Nothing, probability ?? ((_, _) => null), () => new EquityMeanrev());
|
var turn = new ShadowTurn(strategy, stage, context.Day, collector, input ?? ShadowInput.Nothing, probability ?? ((_, _) => null), () => new EquityMeanrev());
|
||||||
Assert.AreSame(intents, collector.Apply(context, intents));
|
Assert.AreSame(intents, collector.Apply(context, intents));
|
||||||
Assert.AreSame(intents, turn.OnProposals.Apply(context, intents), "the very same list: nothing changes");
|
Assert.AreSame(intents, turn.OnProposals.Apply(context, intents), "the very same list: nothing changes");
|
||||||
Assert.AreSame(intents, turn.OnFinal.Apply(context, intents));
|
Assert.AreSame(intents, turn.OnFinal.Apply(context, intents));
|
||||||
@@ -76,7 +77,7 @@ public sealed class ShadowTests
|
|||||||
// Another day of the run says nothing.
|
// Another day of the run says nothing.
|
||||||
var other = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 - i)], day: _days[^2]);
|
var other = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 - i)], day: _days[^2]);
|
||||||
var collector = new CaseCollector(StrategyNames.EquityMeanrev, (_, _) => true, null, Today);
|
var collector = new CaseCollector(StrategyNames.EquityMeanrev, (_, _) => true, null, Today);
|
||||||
var turn = new ShadowTurn(StrategyNames.EquityMeanrev, Today, collector, ShadowInput.Nothing, (_, _) => null, () => new EquityMeanrev());
|
var turn = new ShadowTurn(StrategyNames.EquityMeanrev, StrategyStages.Observation, Today, collector, ShadowInput.Nothing, (_, _) => null, () => new EquityMeanrev());
|
||||||
turn.OnProposals.Apply(other, collector.Apply(other, [Entry("AAA")]));
|
turn.OnProposals.Apply(other, collector.Apply(other, [Entry("AAA")]));
|
||||||
Assert.IsEmpty(turn.Cases);
|
Assert.IsEmpty(turn.Cases);
|
||||||
}
|
}
|
||||||
@@ -106,6 +107,65 @@ public sealed class ShadowTests
|
|||||||
Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement);
|
Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly IReadOnlyList<BacktestInstrument> _moving = [Stock("AAA", i => i % 2 == 0 ? 100 : 102)];
|
||||||
|
|
||||||
|
private static Task DecideAsync(TradingRig rig, string strategy, string stage, DateOnly day) => rig.Db.WriteAsync(s =>
|
||||||
|
ShadowDesk.WriteAsync(s, rig.Clock, Guid.NewGuid(), Turn(strategy, Context(_moving, day: day), [Entry("AAA", weight: 1m)], stage: stage), strategy, _none), _none);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AStrategyThatTradesCountsOnlyWhatTheOthersReallyHold()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync();
|
||||||
|
var desk = new LearningDesk(rig.Db, rig.Clock).Shadow;
|
||||||
|
async Task<string> BooksAsync(string stage) => string.Join(",", (await desk.InputAsync(StrategyNames.CryptoTrend, stage, Today, _none)).OtherBooks.Select(b => b.Stage).Order(StringComparer.Ordinal));
|
||||||
|
await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, Today);
|
||||||
|
await DecideAsync(rig, StrategyNames.EquityMeanrev, StrategyStages.Simulation, Today);
|
||||||
|
Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Simulation));
|
||||||
|
Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Real));
|
||||||
|
Assert.AreEqual("observation,simulation", await BooksAsync(StrategyStages.Observation), "one that only observes is measured on the three");
|
||||||
|
|
||||||
|
// The entry of one that trades is not shrunk by what another only looks at.
|
||||||
|
async Task<double> FactorAsync(string stage) => Turn(StrategyNames.EquityMeanrev, Context(_moving), [Entry("AAA", weight: 0.2m)],
|
||||||
|
await desk.InputAsync(StrategyNames.EquityMeanrev, stage, Today, _none), stage: stage).Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor;
|
||||||
|
Assert.AreEqual(1.0, await FactorAsync(StrategyStages.Simulation));
|
||||||
|
Assert.IsLessThan(1.0, await FactorAsync(StrategyStages.Observation));
|
||||||
|
|
||||||
|
// From the first decision it makes after its promotion, it counts.
|
||||||
|
await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Simulation, Today);
|
||||||
|
Assert.AreEqual("simulation,simulation", await BooksAsync(StrategyStages.Reduced));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ADecisionRecoveredLateNeverSeesABookOfALaterDay()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync();
|
||||||
|
var desk = new LearningDesk(rig.Db, rig.Clock).Shadow;
|
||||||
|
Task DecideOnAsync(DateOnly day) => DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, day);
|
||||||
|
async Task<string> SeenAsync(DateOnly day) => await desk.InputAsync(StrategyNames.EquityMeanrev, StrategyStages.Observation, day, _none) is var i && i.Whole
|
||||||
|
? string.Join(",", i.OtherBooks.Select(b => b.Day)) : "unknown";
|
||||||
|
Assert.AreEqual("", await SeenAsync(Today), "no decision yet, nothing held");
|
||||||
|
await DecideOnAsync(_days[^4]);
|
||||||
|
await DecideOnAsync(Today);
|
||||||
|
Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today));
|
||||||
|
Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2]), "the one in force that day");
|
||||||
|
Assert.AreEqual("unknown", await SeenAsync(_days[^5]));
|
||||||
|
Assert.AreEqual("", await SeenAsync(Today.AddDays(ShadowBook.MaxAgeDays + 1)), "too old to say what it holds");
|
||||||
|
|
||||||
|
// The same day again keeps the one before; a late decision of the same strategy never takes the place of a newer one.
|
||||||
|
await DecideOnAsync(Today);
|
||||||
|
Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2]));
|
||||||
|
await DecideOnAsync(_days[^3]);
|
||||||
|
Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today));
|
||||||
|
Assert.AreEqual(BarStore.DayText(_days[^3]), await SeenAsync(_days[^2]));
|
||||||
|
|
||||||
|
// Without the whole portfolio there is no case, but the book is there for the others.
|
||||||
|
var turn = Turn(StrategyNames.EquityMomentum, Context(_moving), [Entry("AAA", weight: 1m)], ShadowInput.Nothing with { Whole = false });
|
||||||
|
Assert.IsNotNull(turn.Book);
|
||||||
|
Assert.IsFalse(turn.Cases.Any(c => c.Improvement == Improvements.VolatilityCap));
|
||||||
|
}
|
||||||
|
|
||||||
[TestMethod]
|
[TestMethod]
|
||||||
[TestCategory(Category.Unit)]
|
[TestCategory(Category.Unit)]
|
||||||
public void TheModelWouldChooseOtherCandidates()
|
public void TheModelWouldChooseOtherCandidates()
|
||||||
@@ -138,18 +198,51 @@ public sealed class ShadowTests
|
|||||||
Assert.IsNull(ShadowDesk.Summary(null, []).Mean);
|
Assert.IsNull(ShadowDesk.Summary(null, []).Mean);
|
||||||
Assert.IsNull(ShadowDesk.Summary(null, [(Monday, 0.01)]).Interval);
|
Assert.IsNull(ShadowDesk.Summary(null, [(Monday, 0.01)]).Interval);
|
||||||
|
|
||||||
// Ten equal signals in each of two months: the spread between months is what counts.
|
// Ten equal signals in each of six months: the spread between months is what counts, not the sixty signals.
|
||||||
var many = ShadowDesk.Summary(null, [.. Enumerable.Range(0, 20).Select(i => (Monday.AddDays(i < 10 ? 0 : 40), i < 10 ? 0.02 : -0.01))]);
|
ImprovementLine Months(int months) => ShadowDesk.Summary(null, [.. Enumerable.Range(0, months * 10).Select(i => (Monday.AddMonths(i / 10), (i / 10) % 2 == 0 ? 0.02 : -0.01))]);
|
||||||
|
var many = Months(6);
|
||||||
|
Assert.AreEqual((60, 6), (many.Cases, many.Months));
|
||||||
Assert.AreEqual(0.005, many.Mean!.Value, 1e-9);
|
Assert.AreEqual(0.005, many.Mean!.Value, 1e-9);
|
||||||
Assert.IsGreaterThan(0.01, many.Error!.Value);
|
Assert.AreEqual(Math.Sqrt(6 * 0.15 * 0.15 * 6 / 5) / 60, many.Error!.Value, 1e-9);
|
||||||
var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 0.004, 0.001)], "", false, null);
|
Assert.IsGreaterThan(3 * 0.015 / Math.Sqrt(59), many.Error.Value, "three times the error of independent signals");
|
||||||
|
Assert.AreEqual(0.005 + (2.5706 * many.Error.Value), many.Interval!.Value.High, 1e-5, "five degrees of freedom, not the normal");
|
||||||
|
Assert.IsNull(many.Missing);
|
||||||
|
var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 12, 0.004, 0.001)], "", false, null);
|
||||||
Assert.AreEqual("un indizio discreto", view.Trust);
|
Assert.AreEqual("un indizio discreto", view.Trust);
|
||||||
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 0, 0.1)] }).Trust);
|
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 12, 0, 0.1)] }).Trust);
|
||||||
Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 0, 0.1)] }).Trust);
|
Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 12, 0, 0.1)] }).Trust);
|
||||||
var said = ShadowDesk.Discoveries([view]).Single();
|
var said = ShadowDesk.Discoveries([view]).Single();
|
||||||
StringAssert.EndsWith(said.Title, "avrebbe aiutato");
|
StringAssert.EndsWith(said.Title, "avrebbe aiutato");
|
||||||
StringAssert.Contains(said.Detail, "+0,40%");
|
StringAssert.Contains(said.Detail, "+0,40%");
|
||||||
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [new ImprovementLine(null, 9, 0.1, 0.01)] }]));
|
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [new ImprovementLine(null, 9, 12, 0.1, 0.01)] }]));
|
||||||
|
|
||||||
|
// With fewer months there is a mean and nothing else, however many the signals.
|
||||||
|
foreach (var months in new[] { 1, 2, 5 })
|
||||||
|
{
|
||||||
|
var few = Months(months);
|
||||||
|
Assert.AreEqual(months * 10, few.Cases);
|
||||||
|
Assert.IsNotNull(few.Mean);
|
||||||
|
Assert.IsNull(few.Error);
|
||||||
|
Assert.IsNull(few.Interval);
|
||||||
|
Assert.AreEqual($"troppo pochi mesi per un intervallo: {months}, ne servono 6", few.Missing);
|
||||||
|
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [few] }]));
|
||||||
|
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [few with { Cases = 500 }] }).Trust);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsNull(ShadowDesk.Summary(null, []).Missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheQuantilesOfStudentMatchTheTables()
|
||||||
|
{
|
||||||
|
foreach (var (freedom, expected) in new[] { (5, 2.5706), (6, 2.4469), (7, 2.3646), (10, 2.2281), (11, 2.2010), (23, 2.0687), (30, 2.0423), (60, 2.0003), (120, 1.9799) })
|
||||||
|
{
|
||||||
|
Assert.AreEqual(expected, StudentT.Quantile(0.975, freedom), 0.0005);
|
||||||
|
Assert.AreEqual(-expected, StudentT.Quantile(0.025, freedom), 0.0005);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(Normal.Quantile(0.975), StudentT.Quantile(0.975, 1_000_000), 1e-5);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The same decisions with and without the shadow, also when it cannot be written; then its measure.</summary>
|
/// <summary>The same decisions with and without the shadow, also when it cannot be written; then its measure.</summary>
|
||||||
|
|||||||
Reference in new issue
Block a user