Fix the defects of the Phase 4 review (refs #34 #35 #36)
ci / test (postgres) (push) Successful in 2m41s
ci / test (sqlite) (push) Successful in 1m56s
ci / test (postgres) (pull_request) Successful in 3m45s
ci / test (sqlite) (pull_request) Successful in 2m22s
ci / image (push) Successful in 1m10s
ci / image (pull_request) Successful in 13s
ci / test (postgres) (push) Successful in 2m41s
ci / test (sqlite) (push) Successful in 1m56s
ci / test (postgres) (pull_request) Successful in 3m45s
ci / test (sqlite) (pull_request) Successful in 2m22s
ci / image (push) Successful in 1m10s
ci / image (pull_request) Successful in 13s
- An error of the database (PostgreSQL restarting) no longer stops the laboratory until the next start: the queue logs it, waits 30 seconds on the injectable clock and tries the same trial again. - Buy and hold, the comparison of every report, buys an instrument whose history starts later at its first close, with the share kept free for it; before, it was never bought and the others took its weight. Its version goes to 2. - The comparison page reads a and b as text: a malformed id shows "two finished tests needed" instead of an error page. - A trial re-checks the hash of its plan before running and refuses a plan that no longer matches it. - Parameters that count days take whole numbers only (10.5 would run as 10 and count twice in the DSR); the capital starts from 1, as the message says. ADR 0010 says so, and corrects the estimated minimum of the research history: 5 does refuse smaller orders, like the exchanges' minimums. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
af7528560f
commit
f278ff4f67
10 files changed
+158
-28
No files matched your search
@@ -71,11 +71,12 @@
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
// Text, not Guid: a malformed value must give "servono due test", not an error page.
|
||||
[SupplyParameterFromQuery(Name = "a")]
|
||||
public Guid? A { get; set; }
|
||||
public string? A { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "b")]
|
||||
public Guid? B { get; set; }
|
||||
public string? B { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
@@ -85,9 +86,9 @@
|
||||
_b = await ReadAsync(store, B, ct);
|
||||
}
|
||||
|
||||
private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, Guid? id, CancellationToken ct)
|
||||
private static async Task<(Trial, BacktestReport)?> ReadAsync(TrialStore store, string? id, CancellationToken ct)
|
||||
{
|
||||
if (id is not { } key || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json)
|
||||
if (!Guid.TryParse(id, out var key) || await store.GetAsync(key, ct) is not { } trial || await store.ReportJsonAsync(key, ct) is not { } json)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -50,6 +50,9 @@ public sealed partial class Laboratory : IDisposable
|
||||
|
||||
public const int MaxVariants = 200;
|
||||
|
||||
/// <summary>The pause after an error of the queue itself (the database out of reach), before trying again.</summary>
|
||||
public static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly Database _db;
|
||||
private readonly IClock _clock;
|
||||
private readonly string _researchRoot;
|
||||
@@ -107,7 +110,7 @@ public sealed partial class Laboratory : IDisposable
|
||||
throw new TrialRequestException(TrialRequestErrors.Dates, "La data di inizio deve venire prima di quella di fine.");
|
||||
}
|
||||
|
||||
if (request.InitialCapital is <= 0m or > 10_000_000m)
|
||||
if (request.InitialCapital is < 1m or > 10_000_000m)
|
||||
{
|
||||
throw new TrialRequestException(TrialRequestErrors.Capital, "Il capitale iniziale deve essere tra 1 e 10.000.000.");
|
||||
}
|
||||
@@ -121,6 +124,12 @@ public sealed partial class Laboratory : IDisposable
|
||||
throw new TrialRequestException(TrialRequestErrors.Grid, string.Create(CultureInfo.GetCultureInfo("it-IT"), $"{p.Label}: i valori vanno da {p.Min} a {p.Max}."));
|
||||
}
|
||||
|
||||
// A whole parameter given 10.5 would run as 10: two variants that are the same would count twice in the DSR.
|
||||
if (p.Whole && values.Any(x => x != decimal.Truncate(x)))
|
||||
{
|
||||
throw new TrialRequestException(TrialRequestErrors.Grid, p.Label + ": servono numeri interi.");
|
||||
}
|
||||
|
||||
grid[p.Name] = [.. values.Distinct().Order()];
|
||||
}
|
||||
|
||||
@@ -150,16 +159,42 @@ public sealed partial class Laboratory : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>Runs the queue until stopped: first the trials left planned or halfway by the last run, then the new ones.</summary>
|
||||
/// <remarks>
|
||||
/// An error of the queue itself (the database out of reach) never stops it: it waits <see cref="RetryDelay"/> and
|
||||
/// tries the same trial again. A trial left running by such an error is planned again at the next start.
|
||||
/// </remarks>
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var id in await Trials.ResumeAsync(cancellationToken).ConfigureAwait(false))
|
||||
while (true)
|
||||
{
|
||||
await _queue.Writer.WriteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
foreach (var id in await Trials.ResumeAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await _queue.Writer.WriteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogQueueFailed(_logger, ex);
|
||||
await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await foreach (var id in _queue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await ProcessAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await ProcessAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogQueueFailed(_logger, ex);
|
||||
await _clock.WaitUntilAsync(_clock.UtcNow + RetryDelay, cancellationToken).ConfigureAwait(false);
|
||||
_queue.Writer.TryWrite(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,10 +206,15 @@ public sealed partial class Laboratory : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
var trial = (await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false))!;
|
||||
_progress[id] = "lettura dei dati";
|
||||
try
|
||||
{
|
||||
var trial = await Trials.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Prova non trovata.");
|
||||
if (!trial.PlanIntact)
|
||||
{
|
||||
throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte.");
|
||||
}
|
||||
|
||||
var family = StrategyCatalog.Find(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy);
|
||||
if (family.Version != trial.StrategyVersion)
|
||||
{
|
||||
@@ -285,6 +325,9 @@ public sealed partial class Laboratory : IDisposable
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Backtest trial {Id} of {Strategy} finished, passed: {Passed}")]
|
||||
private static partial void LogFinished(ILogger logger, Guid id, string strategy, bool passed);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Laboratory queue error, trying again shortly")]
|
||||
private static partial void LogQueueFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Backtest trial {Id} failed")]
|
||||
private static partial void LogFailed(ILogger logger, Guid id, Exception exception);
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ public static class TrialRunner
|
||||
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
|
||||
}
|
||||
|
||||
var benchmarkRun = BacktestEngine.Run(new BuyAndHold(), data, options);
|
||||
var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Instruments.Count), data, options);
|
||||
var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear);
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -112,6 +112,9 @@ public sealed record Trial(
|
||||
DateTimeOffset? FinishedAt)
|
||||
{
|
||||
public bool IsFinished => Status is TrialStatuses.Done or TrialStatuses.Failed;
|
||||
|
||||
/// <summary>The stored plan text still gives the stored hash: nobody changed it after it was written.</summary>
|
||||
public bool PlanIntact { get; init; } = true;
|
||||
}
|
||||
|
||||
/// <summary>The trials before this one of the same strategy: how many variants they tried and their Sharpe ratios.</summary>
|
||||
@@ -210,6 +213,9 @@ public sealed class TrialStore(Database db, IClock clock)
|
||||
r.TextOrNull("error"),
|
||||
r.Moment("created_at"),
|
||||
r.MomentOrNull("started_at"),
|
||||
r.MomentOrNull("finished_at"));
|
||||
r.MomentOrNull("finished_at"))
|
||||
{
|
||||
PlanIntact = TrialPlan.Hash(plan) == r.Text("plan_hash"),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>
|
||||
/// Buy at the first close in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2,
|
||||
/// step 6. It decides only from its own book, so it can restart from any recorded state.
|
||||
/// Buy in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2, step 6. Each
|
||||
/// instrument is bought at its first close, so one whose history starts later is bought then, with the share kept for
|
||||
/// it. It decides only from its own book, so it can restart from any recorded state.
|
||||
/// </summary>
|
||||
public sealed class BuyAndHold : IStrategy
|
||||
/// <param name="instruments">How many instruments share the capital; null means those available at each decision.</param>
|
||||
public sealed class BuyAndHold(int? instruments = null) : IStrategy
|
||||
{
|
||||
/// <summary>A little cash stays aside for the fees, so the last purchase is not cut short.</summary>
|
||||
public const decimal Invested = 0.995m;
|
||||
|
||||
public string Id => BuyAndHoldFamily.FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
public string Version => "2";
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
@@ -24,13 +26,14 @@ public sealed class BuyAndHold : IStrategy
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (context.Portfolio.Holdings.Count > 0 || context.Universe.Count == 0)
|
||||
var parts = Math.Max(instruments ?? context.Universe.Count, context.Universe.Count);
|
||||
if (parts == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var weight = Invested / context.Universe.Count;
|
||||
return [.. context.Universe.Select(s => new Intent(s, weight, "buy_and_hold"))];
|
||||
var weight = Invested / parts;
|
||||
return [.. context.Universe.Where(s => context.Portfolio.Of(s) is null).Select(s => new Intent(s, weight, "buy_and_hold"))];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,11 +45,11 @@ public sealed class BuyAndHoldFamily : IStrategyFamily
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
public string Version => "2";
|
||||
|
||||
public string Name => "Comprare e tenere";
|
||||
|
||||
public string Description => "Compra in parti uguali alla prima chiusura e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla.";
|
||||
public string Description => "Compra in parti uguali alla prima chiusura di ogni strumento e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters => [];
|
||||
|
||||
@@ -123,8 +126,8 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m),
|
||||
new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m),
|
||||
new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m, Whole: true),
|
||||
new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m, Whole: true),
|
||||
];
|
||||
|
||||
public bool Accepts(StrategyParameters parameters)
|
||||
|
||||
@@ -185,8 +185,11 @@ public interface IStrategy
|
||||
IReadOnlyList<Intent> Decide(StrategyContext context);
|
||||
}
|
||||
|
||||
/// <summary>A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results).</summary>
|
||||
public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList<decimal> Grid, decimal Min, decimal Max);
|
||||
/// <summary>
|
||||
/// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results).
|
||||
/// <see cref="Whole"/> parameters take only whole numbers, such as a number of days.
|
||||
/// </summary>
|
||||
public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList<decimal> Grid, decimal Min, decimal Max, bool Whole = false);
|
||||
|
||||
/// <summary>A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid.</summary>
|
||||
public interface IStrategyFamily
|
||||
|
||||
Reference in new issue
Block a user