Put the candidate strategies in observation without capital
Relative momentum among coins and all-time highs on stocks are now in the code as candidates: they collect signals, have no share, no capital and no order path, and every way forward refuses them. The crypto one ran the protocol once and failed it (DSR 0.744, worst fall 35.3%), so it is archived and decides nothing; the stock one waits for the Alpaca history. refs #74 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9d1a4f2f69
commit
fb0ab223a5
33 files changed
+1747
-82
No files matched your search
@@ -485,7 +485,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.observing dt { font-weight: 650; padding-right: 32px; }
|
||||
.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); }
|
||||
.observing form { margin: 0; flex: none; }
|
||||
.attention { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.attention, .observing .clock { display: inline-flex; align-items: center; gap: 6px; }
|
||||
|
||||
/* ---- Rischio ---- */
|
||||
.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
|
||||
|
||||
@@ -14,18 +14,19 @@ namespace Anubis.Server;
|
||||
/// Binance daily archives (each checked against its SHA-256) and the ECB rates into the research history, converts
|
||||
/// them to euro, runs the protocol of <c>crypto_trend</c> on both universes and writes reports and outcome files.
|
||||
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
|
||||
/// "anubis backtest candidates" does the same for the candidates of SPEC 8.4 and leaves the other files alone.
|
||||
/// </summary>
|
||||
internal static class BacktestCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis backtest base [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||
"Uso: anubis backtest base|candidates [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||
HttpMessageHandler? handler = null)
|
||||
{
|
||||
output ??= Console.Out;
|
||||
if (args.Length < 1 || args[0] != "base")
|
||||
if (args.Length < 1 || args[0] is not ("base" or "candidates"))
|
||||
{
|
||||
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -66,23 +67,30 @@ internal static class BacktestCommand
|
||||
var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").ConfigureAwait(false);
|
||||
|
||||
var outcome = await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||
var candidates = args[0] == "candidates";
|
||||
var name = candidates ? StrategyNames.CryptoRelativeMomentum : StrategyNames.CryptoTrend;
|
||||
var outcome = candidates
|
||||
? await CandidateProtocol.RunCryptoAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false)
|
||||
: await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||
var notes = DataNotes(outcome, rates);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.md"),
|
||||
ProtocolReport.Markdown(outcome, "crypto_trend", notes, "anubis backtest base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, name + ".md"),
|
||||
ProtocolReport.Markdown(outcome, name, notes, $"anubis backtest {args[0]} --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, name + ".outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||
foreach (var run in outcome.Runs)
|
||||
{
|
||||
// The full reports (curve, trades) stay with the data: the repository keeps the summary and the outcome.
|
||||
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, "crypto_trend-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, name + "-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") })
|
||||
(string Strategy, string Name, Qualification Waiting, IReadOnlyList<string> Lines)[] waiting = candidates
|
||||
? [(StrategyNames.StockAthBreakout, StrategyNames.Label(StrategyNames.StockAthBreakout), CandidateProtocol.StockWaiting(), CandidateProtocol.StockExplanation)]
|
||||
: [(StrategyNames.EquityMomentum, "Momentum azioni", EquityProtocol.Waiting(StrategyNames.EquityMomentum), EquityProtocol.Explanation),
|
||||
(StrategyNames.EquityMeanrev, "Ritorno alla media azioni", EquityProtocol.Waiting(StrategyNames.EquityMeanrev), EquityProtocol.Explanation)];
|
||||
foreach (var w in waiting)
|
||||
{
|
||||
var waiting = EquityProtocol.Waiting(strategy);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".md"), ProtocolReport.Waiting(w.Strategy, w.Name, w.Waiting, w.Lines)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".outcome.json"), BacktestOutcomes.ToJson(w.Waiting)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false);
|
||||
|
||||
@@ -23,12 +23,14 @@
|
||||
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
|
||||
{
|
||||
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
|
||||
// The candidates count among the observed ones, the discarded ones no more (mockup 04).
|
||||
var count = here.Count + (stage == StrategyStages.Observation ? v.Candidates.Count(x => !x.Archived) : 0);
|
||||
<li class="@(here.Count > 0 ? "here" : null)">
|
||||
<span class="step">@(i + 1)</span>
|
||||
<strong>@Capital(StrategyStages.Label(stage))</strong>
|
||||
<p>@StageText(stage)</p>
|
||||
<p class="stage-count">
|
||||
@if (here.Count == 0)
|
||||
@if (count == 0)
|
||||
{
|
||||
<span class="muted">Nessuna strategia</span>
|
||||
}
|
||||
@@ -38,7 +40,7 @@
|
||||
{
|
||||
<span class="swatch round" style="background: @x.Color"></span>
|
||||
}
|
||||
<strong>@(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")</strong>
|
||||
<strong>@(count == 1 ? "1 strategia" : $"{count} strategie")</strong>
|
||||
}
|
||||
</p>
|
||||
</li>
|
||||
@@ -189,9 +191,9 @@
|
||||
<h2 id="osservazione">In osservazione</h2>
|
||||
<a href="/laboratorio">Prova una nuova strategia nel laboratorio</a>
|
||||
</div>
|
||||
@if (watching.Count == 0)
|
||||
@if (watching.Count == 0 && v.Candidates.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna strategia di base in osservazione.</p>
|
||||
<p class="note">Nessuna strategia in osservazione.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -209,7 +211,26 @@
|
||||
}
|
||||
else if (!passed)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")</span>
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(StrategiesView.IsWaiting(s.Stage) ? "In attesa dei dati" : "Non supera i test")</span>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
@foreach (var s in v.Candidates)
|
||||
{
|
||||
<dt>@s.Name</dt>
|
||||
<dd>
|
||||
<span>@s.Text@if (!Shell.IsDemo && StrategiesView.ReportOf(s.Stage) is { } report) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||
@if (s.Archived)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />Non supera i test</span>
|
||||
}
|
||||
else if (s.Waiting)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />In attesa dei dati</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="nowrap clock"><Icon Name="clock" Size="16" />@(Math.Min(s.Days, StageBook.ObservationDays)) giorni su @StageBook.ObservationDays</span>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
|
||||
@@ -34,11 +34,45 @@ internal sealed record StrategyCard(
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
|
||||
/// strategy with its requirements, and the ones in observation with the reason.
|
||||
/// A candidate of SPEC 8.4 on the same screen: only the signals collected so far, or why it was discarded. It has no
|
||||
/// capital, no card and no button.
|
||||
/// </summary>
|
||||
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
|
||||
internal sealed record CandidateLine(StrategyStage Stage, string Name, int Signals, int Days)
|
||||
{
|
||||
public bool Archived => StageBook.IsArchived(Stage);
|
||||
|
||||
public bool Waiting => StrategiesView.IsWaiting(Stage);
|
||||
|
||||
public string Text
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Archived)
|
||||
{
|
||||
return Stage.Qualification!.Verdict;
|
||||
}
|
||||
|
||||
var signals = $"Raccoglie segnali senza fare ordini: {Signals} in {Days} {(Days == 1 ? "giorno" : "giorni")}.";
|
||||
return signals + " " + (Waiting ? Stage.Qualification!.Verdict
|
||||
: Days < StageBook.ObservationDays ? $"Servono almeno {StageBook.ObservationDays} giorni per giudicarla."
|
||||
: $"I {StageBook.ObservationDays} giorni di segnali sono raccolti; resta senza capitale.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
|
||||
/// strategy with its requirements, and the ones in observation with the reason, the candidates of 8.4 among them.
|
||||
/// </summary>
|
||||
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, IReadOnlyList<CandidateLine> Candidates, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
|
||||
{
|
||||
/// <summary>Whether a strategy's backtest could not be run yet for lack of data: not the same as having failed it.</summary>
|
||||
public static bool IsWaiting(StrategyStage stage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stage);
|
||||
return stage.Qualification is { Passed: false, PlanHash: null };
|
||||
}
|
||||
|
||||
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
|
||||
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
|
||||
{
|
||||
@@ -82,9 +116,19 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
|
||||
.ConfigureAwait(false) ?? "?";
|
||||
var cards = new List<StrategyCard>();
|
||||
var candidates = new List<CandidateLine>();
|
||||
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
|
||||
if (StrategyNames.IsCandidate(stage.Strategy))
|
||||
{
|
||||
var observedFrom = stage.StageSince ?? clock.UtcNow;
|
||||
var signals = await services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l AND strategy = @s AND decided_at >= @f",
|
||||
("l", Anubis.Learning.CaseSources.Live), ("s", stage.Strategy), ("f", observedFrom)), cancellationToken).ConfigureAwait(false);
|
||||
candidates.Add(new CandidateLine(stage, StrategyNames.Label(stage.Strategy), (int)signals, Math.Max(0, (int)(clock.UtcNow - observedFrom).TotalDays)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!StrategyNames.IsBase(stage.Strategy))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -174,7 +218,8 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
}
|
||||
|
||||
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
|
||||
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
|
||||
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))],
|
||||
[.. candidates.OrderBy(c => c.Archived).ThenBy(c => c.Name, StringComparer.Ordinal)], liveAllowed, live);
|
||||
}
|
||||
|
||||
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
|
||||
|
||||
Reference in new issue
Block a user