Add the honest backtests of the base strategies (refs #44)
crypto_trend now has a backtest report and an outcome file, computed by "anubis backtest base" on the Binance daily archives from 2019 to October 2026. Prices are converted from USDT to euro with the ECB rate of the day, and delisted coins stay in the universe, so survivors do not flatter the result. The protocol runs the broad universe and BTC, ETH and SOL, with costs doubled and tripled and buy and hold beside. Both universes must pass. The outcome is "not passed": the broad universe falls 29.1% (limit 25%) and the narrow one has a probability of overfitting of 0.84 (limit 0.40). The strategy therefore stays in observation. The stock strategies wait for the Alpaca keys and stay in observation too. The bot reads the outcome files at every start. Trials now read 450 days of history before their start, only so the indicators and the 400-day listing age are ready on the first day. Before this, 2019 was spent warming up and BTC and ETH could not be chosen until 2020. A daily series also stops at a hole longer than a week, so the LUNA relaunched in 2022 is not mistaken for the coin that collapsed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8def84e122
commit
7041533ce2
19 files changed
+1696
-25
No files matched your search
@@ -0,0 +1,142 @@
|
||||
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.
|
||||
/// </summary>
|
||||
internal static class BacktestCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis backtest base [--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")
|
||||
{
|
||||
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 outcome = 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);
|
||||
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())
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") })
|
||||
{
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,12 @@ if (args.Length >= 1 && args[0] == "data")
|
||||
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// "anubis backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5).
|
||||
if (args.Length >= 1 && args[0] == "backtest")
|
||||
{
|
||||
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var app = ServerApp.Build(args);
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
return 0;
|
||||
Reference in new issue
Block a user