@@ -162,7 +168,7 @@
Convalide
Sharpe corretto per il numero di prove
@{ var d = r.DeflatedSharpe; var annual = Math.Sqrt(r.PeriodsPerYear); }
- Deflated Sharpe Ratio @LabText.Number(d.Value): 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).
+ Deflated Sharpe Ratio @LabText.Number(d.Value): 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).
Probabilità di sovra-adattamento
@if (r.Overfitting is { } pbo)
@@ -231,9 +237,9 @@
@foreach (var v in r.Variants)
{
- | @LabText.Parameters(v.Parameters)@if (v.Chosen) { scelta} |
+ @LabText.Parameters(v.Parameters)@if (v.Chosen) { scelta}@if (v.Parameters == r.Judged) { in uso} |
@LabText.Number(v.Sharpe * annual) |
- @LabText.Number(v.PlateauScore * annual) |
+ @(v.OutsideGrid ? LabText.Missing : LabText.Number(v.PlateauScore * annual)) |
@LabText.Money(v.NetResult, c, true) |
@LabText.Percent(v.MaxDrawdown) |
@v.Trades |
diff --git a/src/Anubis.Server/Components/ReviewReportView.razor b/src/Anubis.Server/Components/ReviewReportView.razor
index abbe955..6a9484f 100644
--- a/src/Anubis.Server/Components/ReviewReportView.razor
+++ b/src/Anubis.Server/Components/ReviewReportView.razor
@@ -39,7 +39,7 @@
}
@if (line.InUse is { } used)
{
-
Variante in uso: @LabText.Parameters(used.Parameters), Sharpe @LabText.Number(used.Sharpe), calo massimo @LabText.Percent(used.MaxDrawdown). Non cambia da sola.
+
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.
}
@foreach (var text in ReviewView.Live(line, r.RatesAfter ?? r.RatesBefore)) { @text } |
diff --git a/src/Anubis.Server/ReviewView.cs b/src/Anubis.Server/ReviewView.cs
index 6fd598e..b97fab6 100644
--- a/src/Anubis.Server/ReviewView.cs
+++ b/src/Anubis.Server/ReviewView.cs
@@ -19,7 +19,7 @@ internal static class ReviewView
ReviewVerdicts.Passed => "Superata",
ReviewVerdicts.Rejected => "Non superata",
ReviewVerdicts.Error => "Non riuscita",
- _ => "In attesa dei dati",
+ _ => line.NoProtocol ? "Non riprovata" : "In attesa dei dati",
};
public static string? VerdictClass(ReviewLine line) => line.Verdict switch
diff --git a/src/Anubis/Backtest/Protocol.cs b/src/Anubis/Backtest/Protocol.cs
index 966fb45..0055cfb 100644
--- a/src/Anubis/Backtest/Protocol.cs
+++ b/src/Anubis/Backtest/Protocol.cs
@@ -237,7 +237,7 @@ public static class CryptoTrendProtocol
Verdict = verdict,
Report = report,
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
- Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
+ Parameters = main.Report.Judged ?? main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
ExpectedSlippageBp = slippage,
RoundTripCost = Math.Round(2m * (fee + (slippage / 10_000m)), 6),
diff --git a/src/Anubis/Backtest/QuarterlyReview.cs b/src/Anubis/Backtest/QuarterlyReview.cs
index 0670aef..e3c6a11 100644
--- a/src/Anubis/Backtest/QuarterlyReview.cs
+++ b/src/Anubis/Backtest/QuarterlyReview.cs
@@ -24,7 +24,11 @@ public static class ReviewStatuses
}
/// The figures of a variant on the broad universe.
-public sealed record ReviewVariant(string Parameters, double Sharpe, decimal NetResult, double MaxDrawdown);
+public sealed record ReviewVariant(string Parameters, double Sharpe, decimal NetResult, double MaxDrawdown)
+{
+ /// The variant in use when the grid does not have it.
+ public bool OutsideGrid { get; init; }
+}
/// A strategy in the report of a review: the verdict, what it did, and how the strategy did live.
public sealed record ReviewLine
@@ -41,6 +45,9 @@ public sealed record ReviewLine
/// The verdict in words.
public required string Text { get; init; }
+ /// The history is there, but this version has no protocol to try the strategy again.
+ public bool NoProtocol { get; init; }
+
public IReadOnlyList Trials { get; init; } = [];
public ReviewVariant? Chosen { get; init; }
@@ -165,7 +172,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
// Several quarters missed make one review, on the history there is now (SPEC 5.6).
var through = new DateOnly(today.Year, today.Month, 1).AddDays(-1);
var id = await OpenAsync(open, quarter, through, cancellationToken).ConfigureAwait(false);
- var missing = await prepare(through, cancellationToken).ConfigureAwait(false);
+ var missing = await PrepareAsync(quarter, through, cancellationToken).ConfigureAwait(false);
if (missing is not null)
{
if (today <= StartOf(today).AddDays(LastDay - 1))
@@ -181,6 +188,20 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
lab.Enqueue(await PlanAsync(id, through, cancellationToken).ConfigureAwait(false));
}
+ // A fault that repeats every night must not keep the review from ever being published: it waits like a missing archive.
+ private async Task 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 OpenAsync(Review? open, string quarter, DateOnly through, CancellationToken cancellationToken) =>
db.WriteAsync(async s =>
{
@@ -204,6 +225,8 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var costs = await new CostBook(db, clock).TableAsync(cancellationToken).ConfigureAwait(false);
var stage = await stages.GetAsync(CryptoTrendProtocol.Strategy, cancellationToken).ConfigureAwait(false);
var qualified = stage is { Stage: not StrategyStages.Observation };
+ var family = StrategyCatalog.Find(CryptoTrendProtocol.Strategy) ?? throw new InvalidOperationException("crypto_trend non è nel catalogo.");
+ var judged = qualified ? StrategyParameters.Of(family, stage!.Qualification?.Parameters).ToString() : null;
var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), through, cancellationToken).ConfigureAwait(false);
return await db.WriteAsync(async s =>
{
@@ -212,7 +235,7 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
{
var request = new TrialRequest(CryptoTrendProtocol.Strategy, TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, through, CryptoTrendProtocol.Capital, null);
var (plan, variants) = Laboratory.BuildPlan(request, clock.UtcNow, costs);
- ids.Add(await TrialStore.PlanAsync(s, clock, plan with { Priors = qualified ? ReviewPriors.Review : ReviewPriors.All }, variants, id, cancellationToken).ConfigureAwait(false));
+ ids.Add(await TrialStore.PlanAsync(s, clock, plan with { Priors = qualified ? ReviewPriors.Review : ReviewPriors.All, Judged = judged }, variants, id, cancellationToken).ConfigureAwait(false));
}
await s.ExecuteAsync("UPDATE quarterly_reviews SET status = @r, costs = @c, started_at = @t, updated_at = @t WHERE id = @id", cancellationToken,
@@ -241,20 +264,25 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var previous = (await ListAsync(db, cancellationToken).ConfigureAwait(false)).FirstOrDefault(r => r.Id != id && r.Status == ReviewStatuses.Done);
var now = clock.UtcNow;
var today = Zones.DayIn(now, Zones.Rome);
- var from = previous?.FinishedAt ?? new DateTimeOffset(StartOf(today).AddMonths(-3).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
+
+ // The first review covers everything since the start, so the periods always add up to the whole.
+ var from = previous?.FinishedAt ?? DateTimeOffset.UnixEpoch;
+ var start = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(created_at) AS t FROM decisions", r => r.MomentOrNull("t")), cancellationToken).ConfigureAwait(false)
+ ?? new DateTimeOffset(StartOf(today).AddMonths(-3).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
var all = (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => StrategyPipeline.IsBase(s.Strategy)).ToList();
var crypto = await CryptoAsync(id, quarter, missing, trials, cancellationToken).ConfigureAwait(false);
var before = await learning.BaseRatesAsync(cancellationToken).ConfigureAwait(false);
var live = (await learning.Store.AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList();
var examples = await ExamplesAsync(through, crypto, all, cancellationToken).ConfigureAwait(false);
+ var stockBars = await HasStockBarsAsync(cancellationToken).ConfigureAwait(false);
var report = new ReviewReport
{
Missing = missing,
RatesBefore = before,
RatesAfter = examples is null ? null : LearningDesk.Merge(before, Trainer.SharesOf(examples)),
- RestrictionsFrom = Zones.DayIn(from, Zones.Rome),
- Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, cancellationToken).ConfigureAwait(false),
- RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, cancellationToken).ConfigureAwait(false),
+ RestrictionsFrom = Zones.DayIn(from > start ? from : start, Zones.Rome),
+ Restrictions = await RestrictionBalance.LoadAsync(db, clock, from, now, cancellationToken).ConfigureAwait(false),
+ RestrictionsEver = await RestrictionBalance.LoadAsync(db, clock, DateTimeOffset.UnixEpoch, now, cancellationToken).ConfigureAwait(false),
};
var lines = new List();
foreach (var stage in all)
@@ -272,7 +300,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
Signals = live.Count(e => e.Strategy == stage.Strategy && e.IsLabelled),
Won = live.Count(e => e.Strategy == stage.Strategy && e.Label is { Win: true }),
};
- lines.Add(stage.Strategy == CryptoTrendProtocol.Strategy ? Measured(line, stage, crypto, trials) : line);
+ lines.Add(stage.Strategy == CryptoTrendProtocol.Strategy ? Measured(line, stage, crypto, trials)
+ : stockBars ? line with { NoProtocol = true, Text = char.ToUpperInvariant(NoProtocolText[0]) + NoProtocolText[1..] + "." }
+ : line);
}
await db.WriteAsync(async s =>
@@ -315,6 +345,10 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
LogPublished(_logger, quarter, crypto.Verdict);
}
+ private Task 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 CryptoAsync(Guid id, string quarter, string? missing, IReadOnlyList trials, CancellationToken cancellationToken)
{
if (missing is not null)
@@ -337,9 +371,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
var passed = runs.All(r => r.Report.Passed);
var title = new Review(id, quarter, default, "", null, default, null).Title;
+ var used = runs[0].Report.Judged is null ? "" : " con la variante in uso";
var text = passed
- ? $"Revisione del {title}: protocollo superato su entrambi gli universi."
- : $"Revisione del {title}: protocollo non superato. {CryptoTrendProtocol.Failures(runs)}.";
+ ? $"Revisione del {title}: protocollo superato su entrambi gli universi{used}."
+ : $"Revisione del {title}: protocollo non superato{used}. {CryptoTrendProtocol.Failures(runs)}.";
+ if (runs[0].Report.Variants.Any(v => v.OutsideGrid))
+ {
+ text += " La variante in uso non è nella griglia: è giudicata lo stesso.";
+ }
+
var outcome = CryptoTrendProtocol.Measured(runs[0], CryptoTrendProtocol.Strategy, passed, text, "/laboratorio/revisione/" + id);
return new CryptoResult(passed ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, text, outcome, runs);
}
@@ -353,8 +393,8 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
}
var report = crypto.Runs[0].Report;
- ReviewVariant? Variant(Func which) => report.Variants.FirstOrDefault(which) is { } v ? new ReviewVariant(v.Parameters, v.Sharpe, v.NetResult, v.MaxDrawdown) : null;
- var used = stage.Stage == StrategyStages.Observation ? null : stage.Qualification?.Parameters;
+ ReviewVariant? Variant(Func which) => report.Variants.FirstOrDefault(which) is { } v ? new ReviewVariant(v.Parameters, v.Sharpe, v.NetResult, v.MaxDrawdown) { OutsideGrid = v.OutsideGrid } : null;
+ var used = stage.Stage == StrategyStages.Observation ? null : report.Judged ?? stage.Qualification?.Parameters;
var since = DateOnly.FromDateTime((stage.StageSince ?? DateTimeOffset.MaxValue).UtcDateTime);
var days = report.Curve.Where(p => p.Day >= since).ToList();
return line with
@@ -403,13 +443,15 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
return text + " Il rapporto è nel Laboratorio.";
}
+ private const string NoProtocolText = "non riprovata: il protocollo per le azioni arriva con una versione successiva";
+
/// What a review said and did of a strategy, in a few words.
public static string ActionText(ReviewLine line)
{
ArgumentNullException.ThrowIfNull(line);
return line.Verdict switch
{
- ReviewVerdicts.Waiting => "non riprovata, mancano i dati",
+ ReviewVerdicts.Waiting => line.NoProtocol ? NoProtocolText : "non riprovata, mancano i dati",
ReviewVerdicts.Error => "un test non è riuscito, resta valido l'esito precedente",
_ => line.Action switch
{
@@ -427,6 +469,9 @@ public sealed partial class QuarterlyReview(Database db, IClock clock, Laborator
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} waits: {Missing}")]
private static partial void LogWaiting(ILogger logger, string quarter, string missing);
+ [LoggerMessage(Level = LogLevel.Warning, Message = "History of the quarterly review {Quarter} not prepared")]
+ private static partial void LogPrepareFailed(ILogger logger, Exception exception, string quarter);
+
[LoggerMessage(Level = LogLevel.Information, Message = "Quarterly review {Quarter} published, crypto_trend: {Verdict}")]
private static partial void LogPublished(ILogger logger, string quarter, string verdict);
diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs
index 5a95cdb..60e4e1d 100644
--- a/src/Anubis/Backtest/Report.cs
+++ b/src/Anubis/Backtest/Report.cs
@@ -14,7 +14,11 @@ public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? Fir
public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark);
/// A variant of the grid with its full-period figures.
-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)
+{
+ /// The variant in use when the grid does not have it: judged all the same, never counted as a try.
+ public bool OutsideGrid { get; init; }
+}
/// The chosen variant with costs multiplied (SPEC 12.2 point 3).
public sealed record ReportCosts(decimal Multiplier, decimal NetResult, double TotalReturn, double Sharpe, double MaxDrawdown, decimal Fees);
@@ -88,6 +92,9 @@ public sealed record BacktestReport(
/// The 5th percentile of the expected path (SPEC 12.3) of the chosen variant; null for the examples.
public IReadOnlyList? ExpectedPathP5 { get; init; }
+ /// The variant in use, when the figures, the checks and the curve are its own (); null when they are those of the chosen one.
+ public string? Judged { get; init; }
+
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty report");
@@ -96,7 +103,9 @@ public sealed record BacktestReport(
///
/// Runs a trial from its plan, on data already loaded (pure computation, no database: the laboratory runs it on its own
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily
-/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs.
+/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan
+/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice,
+/// the overfitting and the number of tries.
///
public static class TrialRunner
{
@@ -141,14 +150,22 @@ public static class TrialRunner
var scores = Validation.PlateauScores(variants, sharpes);
var chosenIndex = Validation.ChoosePlateau(variants, sharpes);
var chosen = variants[chosenIndex];
- var run = runs[chosenIndex];
+ var judged = plan.Judged is null ? chosen.Parameters : StrategyParameters.Of(family, plan.Judged);
+ var judgedIndex = plan.Judged is null ? chosenIndex : variants.ToList().FindIndex(x => x.ToString() == judged.ToString());
+ if (judgedIndex < 0)
+ {
+ progress?.Invoke("variante in uso");
+ }
+
+ var run = judgedIndex < 0 ? BacktestEngine.Run(family.Create(judged), data, options) : runs[judgedIndex];
+ var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{
- var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
+ var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(judged), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
}
@@ -175,10 +192,10 @@ public static class TrialRunner
// Every variant of every finished trial of this strategy counts as a try (SPEC 12.2 point 1).
var trials = prior.Variants + variants.Count;
var spread = Moments.Of([.. prior.Sharpes, .. sharpes]).StandardDeviation;
- var dsr = SharpeTests.Deflated(returns[chosenIndex], trials, spread * spread);
+ var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti");
- var look = LookAheadCheck.Run(_ => family.Create(chosen.Parameters), data, options, v.LookAheadCuts);
+ var look = LookAheadCheck.Run(_ => family.Create(judged), data, options, v.LookAheadCuts);
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -220,7 +237,9 @@ public static class TrialRunner
benchmark,
costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
- Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex))],
+ Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
+ .. judgedIndex >= 0 ? Array.Empty()
+ : [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward,
combinatorial,
overfitting,
@@ -229,12 +248,14 @@ public static class TrialRunner
lookAhead,
checks,
passed,
- Limitations(plan, family, data),
+ judgedIndex >= 0 ? Limitations(plan, family, data)
+ : [.. Limitations(plan, family, data), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."],
curve,
[.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now,
- watch.Elapsed.TotalSeconds);
+ watch.Elapsed.TotalSeconds)
+ { Judged = plan.Judged is null ? null : judged.ToString() };
if (StrategyPipeline.ResearchShare(family.Id) is not null)
{
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
@@ -243,12 +264,12 @@ public static class TrialRunner
report = report with
{
ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null),
- ExpectedPathP5 = [.. PathBootstrap.Percentile(returns[chosenIndex], CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
+ ExpectedPathP5 = [.. PathBootstrap.Percentile(judgedReturns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
.Select(x => Math.Round(x, 4))],
};
}
- var summary = new TrialSummary(data.Currency, chosen.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
+ var summary = new TrialSummary(data.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes);
return (report, summary);
}
diff --git a/src/Anubis/Backtest/Statistics.cs b/src/Anubis/Backtest/Statistics.cs
index 2ac0e3d..edc0f7b 100644
--- a/src/Anubis/Backtest/Statistics.cs
+++ b/src/Anubis/Backtest/Statistics.cs
@@ -85,6 +85,24 @@ public static class Normal
}
}
+/// Student's t distribution, for the mean of few independent groups.
+public static class StudentT
+{
+ /// The quantile with the first terms of the Cornish-Fisher expansion: within 0.0005 at 0.975 from 5 degrees of freedom on.
+ 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)));
+ }
+}
+
/// Moments of a series of returns, as the formulas of Bailey and López de Prado use them.
public readonly record struct Moments(int Count, double Mean, double StandardDeviation, double Skewness, double Kurtosis)
{
diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs
index 0b96103..93366f5 100644
--- a/src/Anubis/Backtest/Trials.cs
+++ b/src/Anubis/Backtest/Trials.cs
@@ -79,6 +79,12 @@ public sealed record TrialPlan(
/// Which tries a trial of a quarterly review counts in its DSR (); null for the user's trials.
public string? Priors { get; init; }
+ ///
+ /// 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.
+ ///
+ public string? Judged { get; init; }
+
public static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs
index 4d487c0..5ca2f35 100644
--- a/src/Anubis/Data/MarketDataService.cs
+++ b/src/Anubis/Data/MarketDataService.cs
@@ -42,7 +42,7 @@ public sealed partial class MarketDataService : IDisposable
private readonly DataDirectory? _data;
private readonly HttpClient _http;
- // For what carries a key in a header: Alpaca's data, the language model.
+ // For what carries a key or a datum of the user in a header: Alpaca's data, the language model, the SEC.
private readonly HttpClient _signed;
private readonly Func? _sockets;
private readonly ILogger _logger;
@@ -220,6 +220,9 @@ public sealed partial class MarketDataService : IDisposable
}
}
+ /// The requests to the SEC carry the user's contact, which no other host must receive: they never follow a redirect.
+ internal ApiHttp Sec => new(_signed, _clock, Edgar.Source);
+
///
/// The sectors of the companies from the SEC (SPEC 8.7). Without the user's contact, which the SEC asks for in the
/// request, nothing is asked.
@@ -240,7 +243,7 @@ public sealed partial class MarketDataService : IDisposable
await StepAsync(Edgar.Source, async () =>
{
- var read = await new CompanySectors(_db, _clock).RefreshAsync(new ApiHttp(_http, _clock, Edgar.Source), agent, symbols, cancellationToken).ConfigureAwait(false);
+ var read = await new CompanySectors(_db, _clock).RefreshAsync(Sec, agent, symbols, cancellationToken).ConfigureAwait(false);
return $"settori: {read} letti";
}, cancellationToken).ConfigureAwait(false);
}
diff --git a/src/Anubis/Learning/Examples.cs b/src/Anubis/Learning/Examples.cs
index 3a47e35..cfa6391 100644
--- a/src/Anubis/Learning/Examples.cs
+++ b/src/Anubis/Learning/Examples.cs
@@ -26,6 +26,10 @@ public sealed record Example(Guid Id, string Strategy, string Symbol, string Sou
public CaseLabel? Label { get; init; }
+ /// When the outcome became known: days after the close if the bot was off. Null for an example not read from the archive.
+ [JsonIgnore]
+ public DateTimeOffset? LabelledAt { get; init; }
+
/// A label that can train: the operation started and closed.
[JsonIgnore]
public bool IsLabelled => Label is { Win: not null, ClosedDay: not null };
diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs
index 612c60e..c6fae41 100644
--- a/src/Anubis/Learning/LearningDesk.cs
+++ b/src/Anubis/Learning/LearningDesk.cs
@@ -272,7 +272,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
var gate = await OrAsync(() => GateAsync(cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
- var shadow = await OrAsync(() => Shadow.InputAsync(strategy, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
+ var shadow = await OrAsync(() => Shadow.InputAsync(strategy, stage, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy), shadow, create);
}
@@ -359,7 +359,7 @@ public sealed class LearningTurn
_failed = failed;
_outside = outside;
_collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
- _shadow = new ShadowTurn(strategy, day, _collector, shadow, ProbabilityOf, create);
+ _shadow = new ShadowTurn(strategy, stage, day, _collector, shadow, ProbabilityOf, create);
}
///
diff --git a/src/Anubis/Learning/LearningStore.cs b/src/Anubis/Learning/LearningStore.cs
index af2d379..6230285 100644
--- a/src/Anubis/Learning/LearningStore.cs
+++ b/src/Anubis/Learning/LearningStore.cs
@@ -10,7 +10,7 @@ public sealed class LearningStore(Database db, IClock clock)
{
private const string Columns =
"f.id, f.strategy, f.symbol, f.source, f.decided_day, f.decided_at, f.decision_id, f.stage, f.reason, f.weight, f.stop, f.stop_offset, f.features, f.multiplier, " +
- "l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
+ "l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason, l.created_at AS labelled_at FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id";
/// Saves an example as part of the decision that made it. One already there (same day) stays as it is: null.
public static async Task AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken)
@@ -109,6 +109,7 @@ public sealed class LearningStore(Database db, IClock clock)
DecisionId = r.IdOrNull("decision_id"),
Multiplier = r.Measure("multiplier"),
Label = label,
+ LabelledAt = r.MomentOrNull("labelled_at"),
};
}
diff --git a/src/Anubis/Learning/RestrictionBalance.cs b/src/Anubis/Learning/RestrictionBalance.cs
index 0919bfb..16efe3c 100644
--- a/src/Anubis/Learning/RestrictionBalance.cs
+++ b/src/Anubis/Learning/RestrictionBalance.cs
@@ -46,13 +46,21 @@ public static class RestrictionBalance
_ => code,
};
- /// The balance of the entries blocked; each example counts once, under its strictest row.
- public static RestrictionReport Of(IReadOnlyList blocked, IReadOnlyList examples, IReadOnlyList trades, IReadOnlyDictionary 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 and by , whenever it was
+ /// blocked: so the periods add up to the whole. One not known by then is open in every period.
+ ///
+ public static RestrictionReport Of(IReadOnlyList blocked, IReadOnlyList examples, IReadOnlyList trades, IReadOnlyDictionary capitals,
+ DateTimeOffset? from = null, DateTimeOffset? until = null)
{
ArgumentNullException.ThrowIfNull(blocked);
ArgumentNullException.ThrowIfNull(examples);
ArgumentNullException.ThrowIfNull(trades);
ArgumentNullException.ThrowIfNull(capitals);
+ bool InPeriod(DateTimeOffset at) => (from is null || at > from) && (until is null || at <= until);
+ blocked = [.. blocked.Where(b => until is null || b.At <= until)];
+ trades = [.. trades.Where(t => until is null || t.OpenedAt <= until)];
var lines = Codes.ToDictionary(c => c, c => new RestrictionLine(c, 0, 0m, 0m, 0, 0, 0, 0), StringComparer.Ordinal);
var cases = new Dictionary Blocks)>();
foreach (var block in blocked.Where(b => lines.ContainsKey(b.Code)).OrderBy(b => b.At))
@@ -63,7 +71,7 @@ public static class RestrictionBalance
.OrderByDescending(e => e.At).FirstOrDefault();
if (example is null || own.Any(t => t.OpenedAt < block.At && (t.ClosedAt is null || t.ClosedAt > block.At)))
{
- lines[block.Code] = lines[block.Code] with { Increases = lines[block.Code].Increases + 1 };
+ lines[block.Code] = lines[block.Code] with { Increases = lines[block.Code].Increases + (InPeriod(block.At) ? 1 : 0) };
continue;
}
@@ -82,19 +90,28 @@ public static class RestrictionBalance
var first = blocks[0].At;
var last = example.Label?.ClosedDay is { } closed ? new DateTimeOffset(closed.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero) : DateTimeOffset.MaxValue;
- // In observation nothing is ever bought: an entry only put off would have been made at its end.
- var delayed = example.Stage == StrategyStages.Observation
+ // In observation nothing is ever bought: an entry only put off would have been made at its end. A later block of
+ // the same example can still stop it, so it is settled with the outcome.
+ var observed = example.Stage == StrategyStages.Observation;
+ var delayed = observed
? blocks.All(b => b.Postponed)
: trades.Any(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first && t.OpenedAt < last);
- if (delayed)
- {
- lines[code] = line with { Delayed = line.Delayed + 1 };
- }
- else if (example.Label is not { } label)
+ DateTimeOffset? settled = delayed && !observed
+ ? trades.Where(t => t.Strategy == example.Strategy && t.Symbol == example.Symbol && t.OpenedAt >= first).Min(t => t.OpenedAt)
+ : example.Label is null ? null : example.LabelledAt > first ? example.LabelledAt : last > first ? last : first;
+ if (settled is not { } known || known > until)
{
lines[code] = line with { Open = line.Open + 1 };
}
- else if (label.Win is null || label.Result is not { } result)
+ else if (!InPeriod(known))
+ {
+ continue;
+ }
+ else if (delayed)
+ {
+ lines[code] = line with { Delayed = line.Delayed + 1 };
+ }
+ else if (example.Label is not { Win: not null, Result: { } result })
{
lines[code] = line with { NeverStarted = line.NeverStarted + 1 };
}
@@ -108,14 +125,14 @@ public static class RestrictionBalance
return new RestrictionReport([.. Codes.Select(c => lines[c]).Where(l => l.Stopped + l.Open + l.NeverStarted + l.Delayed + l.Increases > 0)]);
}
- /// The balance of the entries blocked from a moment on.
- public static async Task LoadAsync(Database db, IClock clock, DateTimeOffset from, CancellationToken cancellationToken)
+ /// The balance of the entries blocked whose outcome became known in a period.
+ public static async Task LoadAsync(Database db, IClock clock, DateTimeOffset from, DateTimeOffset until, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var rows = await db.ReadAsync(s => s.QueryAsync(
- "SELECT decision_id, strategy, symbol, outcome, reasons, created_at FROM decisions WHERE symbol IS NOT NULL AND stage IN (@c, @o) AND outcome IN (@r, @p) AND created_at >= @f ORDER BY created_at, id",
+ "SELECT decision_id, strategy, symbol, outcome, reasons, created_at FROM decisions WHERE symbol IS NOT NULL AND stage IN (@c, @o) AND outcome IN (@r, @p) ORDER BY created_at, id",
r => (Id: r.Id("decision_id"), Strategy: r.Text("strategy"), Symbol: r.Text("symbol"), Outcome: r.Text("outcome"), Reasons: r.Json("reasons").Text, At: r.Moment("created_at")),
- ("c", DecisionStages.Correctives), ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed), ("f", from)), cancellationToken).ConfigureAwait(false);
+ ("c", DecisionStages.Correctives), ("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed)), cancellationToken).ConfigureAwait(false);
var blocked = new List();
foreach (var row in rows)
{
@@ -134,6 +151,6 @@ public static class RestrictionBalance
var trades = await db.ReadAsync(s => s.QueryAsync("SELECT t.strategy, i.symbol, t.opened_at, t.closed_at FROM trades t JOIN instruments i ON i.id = t.instrument_id",
r => new HeldTrade(r.Text("strategy"), r.Text("symbol"), r.Moment("opened_at"), r.MomentOrNull("closed_at"))), cancellationToken).ConfigureAwait(false);
var examples = (await new LearningStore(db, clock).AllAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.Source == CaseSources.Live).ToList();
- return Of(blocked, examples, trades, await LearningCycle.CapitalsAsync(db, clock, cancellationToken).ConfigureAwait(false));
+ return Of(blocked, examples, trades, await LearningCycle.CapitalsAsync(db, clock, cancellationToken).ConfigureAwait(false), from, until);
}
}
diff --git a/src/Anubis/Learning/Shadow.cs b/src/Anubis/Learning/Shadow.cs
index 37b7bda..cbf02ca 100644
--- a/src/Anubis/Learning/Shadow.cs
+++ b/src/Anubis/Learning/Shadow.cs
@@ -66,6 +66,12 @@ public sealed record ShadowBook
public string Day { get; init; } = "";
+ /// The stage of the strategy at that decision: in observation the positions are only what it would hold.
+ public string Stage { get; init; } = "";
+
+ /// The book of the decision before, for a decision of another strategy recovered late; it has no previous of its own.
+ public ShadowBook? Previous { get; init; }
+
public IReadOnlyDictionary Returns { get; init; } = new Dictionary();
public static string KeyOf(string strategy) => "shadow_book:" + strategy;
@@ -110,13 +116,16 @@ public sealed record ShadowBook
public sealed record ShadowInput(IReadOnlyList OtherBooks, IReadOnlyDictionary Sectors)
{
public static readonly ShadowInput Nothing = new([], new Dictionary());
+
+ /// False when what another strategy held on that day is no longer known: the portfolio cannot be judged.
+ public bool Whole { get; init; } = true;
}
///
/// 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.
///
-internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector collector, ShadowInput input, Func probability, Func create)
+internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, CaseCollector collector, ShadowInput input, Func probability, Func create)
{
private readonly List _cases = [];
@@ -124,6 +133,8 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
public ShadowBook? Book { get; private set; }
+
+
/// After the collector, on what the strategy proposed.
public IIntentStage OnProposals => new Step(day, Proposals);
@@ -273,8 +284,8 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
}
}
- Book = ShadowBook.Of(context, weights, share);
- if (ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
+ Book = ShadowBook.Of(context, weights, share) with { Stage = stage };
+ if (!input.Whole || ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
{
return;
}
@@ -288,16 +299,23 @@ internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector co
}
/// How many signals an improvement changed and what it would have been worth, on one alternative.
-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)
{
- /// The interval that holds the mean effect 95 times in 100; null with too few cases.
- public (double Low, double High)? Interval => Mean is { } m && Error is { } e ? (m - (1.96 * e), m + (1.96 * e)) : null;
+ /// Fewer months than these give no interval: the signals of a month move together, so a month counts as one.
+ public const int MinMonths = 6;
+
+ /// What is missing for an interval, in words; null when nothing is.
+ public string? Missing => Cases > 0 && Months < MinMonths ? $"troppo pochi mesi per un intervallo: {Months}, ne servono {MinMonths}" : null;
+
+ /// The interval that holds the mean effect 95 times in 100; null with too few months.
+ 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;
}
/// An improvement as the pages show it.
public sealed record ImprovementView(Improvement Improvement, int Examined, IReadOnlyList Lines, string State, bool Waiting, string? Note)
{
- public string Trust => Discovery.TrustOf(Lines.Count == 0 ? 0 : Lines.Max(l => l.Cases));
+ /// The signals of too few months say little, however many they are.
+ public string Trust => Discovery.TrustOf(Lines.Where(l => l.Missing is null).Select(l => l.Cases).DefaultIfEmpty(0).Max());
}
/// Saves the shadow of each decision, measures it when the outcomes are known and sums it up.
@@ -310,23 +328,37 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
private readonly CompanySectors _sectors = new(db, clock);
- /// What the decision of a strategy needs from outside it.
- public async Task InputAsync(string strategy, DateOnly day, CancellationToken cancellationToken)
+ ///
+ /// What the decision of a strategy needs from outside it. The others count as they were on : one
+ /// that trades looks only at those that traded too, one that only observes at what the three of them would hold.
+ ///
+ public async Task InputAsync(string strategy, string stage, DateOnly day, CancellationToken cancellationToken)
{
var books = new List();
+ var whole = true;
foreach (var (name, _, _) in StrategyNames.Base.Where(b => b.Name != strategy))
{
- if (await store.StateAsync(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is { } book && book.Day.Length > 0
- && Math.Abs(day.DayNumber - BarStore.ParseDay(book.Day).DayNumber) <= ShadowBook.MaxAgeDays)
+ if (await store.StateAsync(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is not { } last)
+ {
+ continue; // It never decided: it holds nothing.
+ }
+
+ if ((IsBy(last, day) ? last : last.Previous) is not { } book || !IsBy(book, day))
+ {
+ whole = false;
+ }
+ else if (day.DayNumber - BarStore.ParseDay(book.Day).DayNumber <= ShadowBook.MaxAgeDays && (stage == StrategyStages.Observation || book.Stage is not ("" or StrategyStages.Observation)))
{
books.Add(book);
}
}
var sectors = strategy == StrategyNames.EquityMomentum ? await _sectors.GroupsAsync(cancellationToken).ConfigureAwait(false) : new Dictionary();
- return new ShadowInput(books, sectors);
+ return new ShadowInput(books, sectors) { Whole = whole };
}
+ private static bool IsBy(ShadowBook book, DateOnly day) => BarStore.ParseDay(book.Day) <= day;
+
private sealed record Stored
{
public IReadOnlyDictionary Numbers { get; init; } = new Dictionary();
@@ -351,10 +383,20 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
if (turn.Book is { } book)
{
- await LearningStore.SaveStateAsync(s, clock, ShadowBook.KeyOf(strategy), book, cancellationToken).ConfigureAwait(false);
+ var key = ShadowBook.KeyOf(strategy);
+ var json = await s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
+ var kept = json is null ? null : JsonSerializer.Deserialize(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().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);
///
@@ -512,26 +554,27 @@ public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
///
/// 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.
///
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
{
if (values.Count == 0)
{
- return new ImprovementLine(label, 0, null, null);
- }
-
- var mean = values.Average(v => v.Effect);
- if (values.Count < 2)
- {
- return new ImprovementLine(label, values.Count, mean, null);
+ return new ImprovementLine(label, 0, 0, null, null);
}
var n = values.Count;
- var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
+ var mean = values.Average(v => v.Effect);
var months = values.GroupBy(v => (v.Day.Year, v.Day.Month)).Select(g => g.Sum(v => v.Effect - mean)).ToList();
- var clustered = months.Count > 1 ? Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n : 0;
- return new ImprovementLine(label, n, mean, Math.Max(simple, clustered));
+ if (months.Count < ImprovementLine.MinMonths)
+ {
+ return new ImprovementLine(label, n, months.Count, mean, null);
+ }
+
+ // Months that happen to cancel out never make the error smaller than that of independent signals.
+ var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
+ var clustered = Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n;
+ return new ImprovementLine(label, n, months.Count, mean, Math.Max(simple, clustered));
}
/// The improvements with enough cases for a sentence, among the discoveries of SPEC 11.6.
diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs
index da36652..3623a9a 100644
--- a/src/Anubis/Strategies/Strategy.cs
+++ b/src/Anubis/Strategies/Strategy.cs
@@ -211,6 +211,25 @@ public sealed class StrategyParameters
public static StrategyParameters None { get; } = new([]);
+ /// The parameters a text such as fast=20;slow=100 gives to a family: its defaults where the text says nothing, or nothing it accepts.
+ 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(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 Values => _values;
public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name);
diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs
index 393477b..97f9ea0 100644
--- a/src/Anubis/Trading/LiveEngine.cs
+++ b/src/Anubis/Trading/LiveEngine.cs
@@ -1533,19 +1533,7 @@ public sealed partial class LiveEngine : IDisposable
public static IStrategy CreateStrategy(string strategy, string? parameters)
{
var family = StrategyCatalog.Find(strategy) ?? throw new ArgumentException("Unknown strategy " + strategy, nameof(strategy));
- var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal);
- var values = new Dictionary(defaults, StringComparer.Ordinal);
- foreach (var part in (parameters ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
- {
- var pair = part.Split('=', 2);
- if (pair.Length == 2 && values.ContainsKey(pair[0]) && decimal.TryParse(pair[1], NumberStyles.Number, CultureInfo.InvariantCulture, out var value))
- {
- values[pair[0]] = value;
- }
- }
-
- var chosen = new StrategyParameters(values);
- return family.Accepts(chosen) ? family.Create(chosen) : family.Create(new StrategyParameters(defaults));
+ return family.Create(StrategyParameters.Of(family, parameters));
}
// ---- Runs ---------------------------------------------------------------------------------------------------
diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs
index 24212f7..e7fbfdd 100644
--- a/tests/Anubis.Tests/LaboratoryScreenTests.cs
+++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs
@@ -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,
},
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 { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 },
RatesAfter = new Dictionary { [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",
"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", "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}\".");
diff --git a/tests/Anubis.Tests/NewsRulesTests.cs b/tests/Anubis.Tests/NewsRulesTests.cs
index e93c07f..5adfa99 100644
--- a/tests/Anubis.Tests/NewsRulesTests.cs
+++ b/tests/Anubis.Tests/NewsRulesTests.cs
@@ -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")),
("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());
- 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);
}
diff --git a/tests/Anubis.Tests/QuarterlyReviewTests.cs b/tests/Anubis.Tests/QuarterlyReviewTests.cs
index 95b18c1..5a41a54 100644
--- a/tests/Anubis.Tests/QuarterlyReviewTests.cs
+++ b/tests/Anubis.Tests/QuarterlyReviewTests.cs
@@ -35,22 +35,25 @@ public sealed class QuarterlyReviewTests
}
// A report of the protocol on those coins, whose verdict each test chooses.
- private static readonly Lazy> _report = new(async () =>
+ private static readonly Lazy> _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");
try
{
await WriteHistoryAsync(folder).ConfigureAwait(false);
- var (plan, _) = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
- CryptoTrendProtocol.Capital, null), At(2027, 1, 5));
+ var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
+ CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan with
+ { Judged = judged };
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
{
TempFolder.Delete(folder);
}
- });
+ }
private sealed class ReviewRig : IAsyncDisposable
{
@@ -64,6 +67,8 @@ public sealed class QuarterlyReviewTests
public string? Missing { get; set; }
+ public Exception? Failure { get; set; }
+
public List Prepared { get; } = [];
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, _) =>
{
Prepared.Add(to);
- return Task.FromResult(Missing);
+ return Failure is { } failure ? Task.FromException(failure) : Task.FromResult(Missing);
});
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'"));
}
+ [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(() => 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 real trials, with a restart in the middle: each trial counts once, the review concludes once.
@@ -406,6 +438,78 @@ public sealed class QuarterlyReviewTests
Assert.IsTrue((await DemotionAsync()).Met);
}
+ // ---- The variant in use -----------------------------------------------------------------------------------------
+
+ /// The grid says how much was searched; the figures, the checks and the curve are those of the variant the strategy works with.
+ [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((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 =>
{
var id = Ids.NewId(clock);
@@ -433,6 +537,21 @@ public sealed class QuarterlyReviewTests
var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action));
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 -------------------------------------------------------------------------------------------------
@@ -619,6 +738,50 @@ public sealed class QuarterlyReviewTests
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
}
+ /// A block is of the period in which its outcome became known, so the periods add up to the whole.
+ [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 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(), 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);
+ }
+
/// The decisions of the live engine, as they are written, give the balance.
[TestMethod]
[TestCategory(Category.Integration)]
@@ -634,10 +797,13 @@ public sealed class QuarterlyReviewTests
await live.DayAsync(day);
var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList();
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.Negative).Open);
+ // The outcomes arrive after the first review.
+ live.Rig.Clock.Set(first.AddDays(20));
foreach (var e in cases)
{
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 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);
Assert.IsGreaterThan(0m, r.Avoided);
Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 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));
}
}
diff --git a/tests/Anubis.Tests/SecurityTests.cs b/tests/Anubis.Tests/SecurityTests.cs
index 2dc9120..17d09a0 100644
--- a/tests/Anubis.Tests/SecurityTests.cs
+++ b/tests/Anubis.Tests/SecurityTests.cs
@@ -271,19 +271,9 @@ public sealed partial class SecurityTests
[TestCategory(Category.Integration)]
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;
- other.MapFallback(() => Interlocked.Increment(ref reached));
- await other.StartAsync();
- 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();
+ await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
+ await using var broker = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path, permanent: false, preserveMethod: true));
var address = new Uri(broker.Urls.Single());
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.");
}
+ private static async Task FallbackAsync(Func 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;
+ }
+
+ /// 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.
+ [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 { ["User-Agent"] = Edgar.UserAgent("prova@esempio.it")! };
+ await Assert.ThrowsAsync(() => market.Sec.GetBytesAsync(new Uri(sec.Urls.Single() + "/files/company_tickers"), null, agent, CancellationToken.None));
+ Assert.AreEqual(0, reached);
+ }
+
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
diff --git a/tests/Anubis.Tests/ShadowTests.cs b/tests/Anubis.Tests/ShadowTests.cs
index e575637..a5ffa09 100644
--- a/tests/Anubis.Tests/ShadowTests.cs
+++ b/tests/Anubis.Tests/ShadowTests.cs
@@ -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 ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList intents, ShadowInput? input = null, Func? probability = null)
+ private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList intents, ShadowInput? input = null, Func? probability = null,
+ string stage = StrategyStages.Observation)
{
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, turn.OnProposals.Apply(context, intents), "the very same list: nothing changes");
Assert.AreSame(intents, turn.OnFinal.Apply(context, intents));
@@ -76,7 +77,7 @@ public sealed class ShadowTests
// Another day of the run says nothing.
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 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")]));
Assert.IsEmpty(turn.Cases);
}
@@ -106,6 +107,65 @@ public sealed class ShadowTests
Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement);
}
+ private static readonly IReadOnlyList _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 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 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 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]
[TestCategory(Category.Unit)]
public void TheModelWouldChooseOtherCandidates()
@@ -138,18 +198,51 @@ public sealed class ShadowTests
Assert.IsNull(ShadowDesk.Summary(null, []).Mean);
Assert.IsNull(ShadowDesk.Summary(null, [(Monday, 0.01)]).Interval);
- // Ten equal signals in each of two months: the spread between months is what counts.
- var many = ShadowDesk.Summary(null, [.. Enumerable.Range(0, 20).Select(i => (Monday.AddDays(i < 10 ? 0 : 40), i < 10 ? 0.02 : -0.01))]);
+ // Ten equal signals in each of six months: the spread between months is what counts, not the sixty signals.
+ 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.IsGreaterThan(0.01, many.Error!.Value);
- var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 0.004, 0.001)], "", false, null);
+ Assert.AreEqual(Math.Sqrt(6 * 0.15 * 0.15 * 6 / 5) / 60, many.Error!.Value, 1e-9);
+ 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("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 0, 0.1)] }).Trust);
- Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 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, 12, 0, 0.1)] }).Trust);
var said = ShadowDesk.Discoveries([view]).Single();
StringAssert.EndsWith(said.Title, "avrebbe aiutato");
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);
}
/// The same decisions with and without the shadow, also when it cannot be written; then its measure.