Record the course the user chose on 2 December 2026 and make the container the only form of Anubis. - ADR 0021-0026: new roadmap (phases 10-24, readings per phase, the spec-to-ADR table, merge and tag only after the user's yes), Docker only, maths-only decisions, bans turned into limits on margin accounts, eToro Demo as currency venue and forward tests, strategy championship. ROADMAP rewritten from phase 10; STATE, CLAUDE.md, SVILUPPO, README, API-NOTES and the manuals without the desktop. - Remove the desktop: Anubis.Desktop, Anubis.Setup, deploy/windows, release-win and desktop-win, config.toml, PlatformKind, ANUBIS_PLATFORM, DPAPI with the ProtectedData package and the first-run wizard. Outside a container the server needs --data-dir, listens on 127.0.0.1 only and refuses foreign hosts; server and guard refuse --platform desktop with an Italian message and exit code 2. The demo keeps its key in a file and its error-page choices need no startup password. The diagnostics report says where the server runs from its own environment. - Lighter image: restore and publish for linux-x64 only, and leave out the Windows libraries ONNX Runtime copies anyway (829 MB to 410 MB on disk, /app from 282 MB to 42 MB). Rotating Docker logs in the Unraid template, the manual and the compose; backtest and learning run as one-shot commands. tasks dev uses artifacts/dev-data. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
9.3 KiB
C#
151 lines
9.3 KiB
C#
using System.Collections;
|
|
using System.Globalization;
|
|
using Anubis.Backtest;
|
|
using Anubis.Brokers;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Strategies;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Server;
|
|
|
|
/// <summary>
|
|
/// "anubis backtest base": the honest backtests of the base strategies (SPEC 12.2, issue #44). It downloads the
|
|
/// 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|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: [--data-dir <cartella>, obbligatoria fuori dal container]";
|
|
|
|
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] is not ("base" or "candidates"))
|
|
{
|
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
|
return 2;
|
|
}
|
|
|
|
var rest = args[1..].ToList();
|
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
|
var options = ServerOptions.Parse([.. rest.Where(a => a != "--offline")], environment);
|
|
var config = options.LoadConfig(environment);
|
|
var clock = new SystemClock();
|
|
var now = clock.UtcNow;
|
|
var to = Option(rest, "--to") is { } t
|
|
? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture)
|
|
: new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last month whose archive is published.
|
|
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "backtests"));
|
|
try
|
|
{
|
|
config.Data.Ensure();
|
|
Directory.CreateDirectory(outDir);
|
|
var store = new ResearchStore(config.Data.Research);
|
|
IReadOnlyList<FxRate> rates;
|
|
using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false))
|
|
{
|
|
http.Timeout = TimeSpan.FromMinutes(5);
|
|
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
|
rates = await RatesAsync(new ApiHttp(http, clock, "ecb"), config.Data.Research, rest.Contains("--offline"), output).ConfigureAwait(false);
|
|
if (!rest.Contains("--offline"))
|
|
{
|
|
var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), store, clock);
|
|
foreach (var symbol in CryptoTrendProtocol.Archives)
|
|
{
|
|
var result = await importer.ImportAsync(symbol, "1d", 2017, 8, CancellationToken.None).ConfigureAwait(false);
|
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{symbol}: {result.Bars} barre giornaliere")).ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false);
|
|
await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").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, 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, name + "-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
|
.ConfigureAwait(false);
|
|
}
|
|
|
|
(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)
|
|
{
|
|
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);
|
|
await output.WriteLineAsync("Rapporti scritti in " + outDir).ConfigureAwait(false);
|
|
return 0;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
|
|
or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException)
|
|
{
|
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
/// <summary>The ECB history of EUR/USD, kept next to the research data so an offline run uses the same rates.</summary>
|
|
private static async Task<IReadOnlyList<FxRate>> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output)
|
|
{
|
|
var path = Path.Combine(researchRoot, "ecb-eurofxref-hist.zip");
|
|
if (!offline || !File.Exists(path))
|
|
{
|
|
var zip = await http.GetBytesAsync(Ecb.History, null, null, CancellationToken.None).ConfigureAwait(false)
|
|
?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true);
|
|
await File.WriteAllBytesAsync(path, zip).ConfigureAwait(false);
|
|
}
|
|
|
|
var rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(await File.ReadAllBytesAsync(path).ConfigureAwait(false)), ["USD"]);
|
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Cambi BCE EUR/USD: {rates.Count} giorni, dal {rates[0].Date:yyyy-MM-dd} al {rates[^1].Date:yyyy-MM-dd}."))
|
|
.ConfigureAwait(false);
|
|
return rates;
|
|
}
|
|
|
|
private static List<string> DataNotes(ProtocolOutcome outcome, IReadOnlyList<FxRate> rates)
|
|
{
|
|
var broad = outcome.Runs[0].Report.Instruments;
|
|
var it = CultureInfo.GetCultureInfo("it-IT");
|
|
var missing = CryptoTrendProtocol.Archives.Select(EuroHistory.SymbolOf).Where(s => broad.All(i => i.Symbol != s)).ToList();
|
|
var notes = new List<string>
|
|
{
|
|
"Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.",
|
|
string.Create(it, $"Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno ({rates.Count} giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1)."),
|
|
string.Create(it, $"{broad.Count} coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni."),
|
|
"Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.",
|
|
};
|
|
if (missing.Count > 0)
|
|
{
|
|
notes.Add("Senza archivi nel periodo, quindi non usate: " + string.Join(", ", missing) + ".");
|
|
}
|
|
|
|
return notes;
|
|
}
|
|
|
|
private static string? Option(List<string> args, string name)
|
|
{
|
|
var index = args.IndexOf(name);
|
|
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
|
|
}
|
|
}
|