using System.Collections;
using System.Globalization;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Learning;
namespace Anubis.Server;
///
/// "anubis learning base": the first model (SPEC 11.2, issue #63). It rebuilds the examples of crypto_trend on the
/// history that "anubis backtest base" already downloaded and converted, trains, and writes the validation report and the
/// file that travels with the program. It never uses the network. The stock strategies wait for the Alpaca history.
///
internal static class LearningCommand
{
private const string Usage =
"Uso: anubis learning base [--to AAAA-MM-GG] [--out docs/learning]\n" +
" Usa gli storici giĆ scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--data-dir , obbligatoria fuori dal container]";
public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = 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().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
var now = new SystemClock().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);
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "learning"));
try
{
Directory.CreateDirectory(outDir);
var file = await FirstModel.BuildAsync(config.Data.Research, to, null, CancellationToken.None).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.json"), FirstModel.ToJson(file)).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.md"),
FirstModel.Markdown(file, "anubis learning base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{file.Examples.Count} esempi, {file.Examples.Count(e => e.IsLabelled)} con un esito. ")
+ (file.Report is { } report ? report.Reason : "Nessun modello: esempi troppo pochi.")).ConfigureAwait(false);
await output.WriteLineAsync("Rapporto scritto in " + outDir).ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or FormatException or UnauthorizedAccessException or InvalidDataException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
private static string? Option(List args, string name)
{
var index = args.IndexOf(name);
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
}
}