Fase 12 — Dati e matematica dei panieri (#187)
ci / test (postgres) (push) Successful in 9m14s
ci / test (sqlite) (push) Successful in 6m40s
ci / image (push) Successful in 2m18s

Research-only data and maths for basket mean reversion (ADR 0028): a seam between the trial judge and the engines, the basket maths in src/Anubis/Baskets, sub-day research bars, ECB crosses and FX minute import.

refs #118, refs #119, refs #120, refs #121

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #187.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-12-04 11:29:00 +01:00
1 parent 93cdf7850d
commit e0a438a0b2
40 files changed
+4464 -110

No files matched your search

+2 -10
View File
@@ -106,17 +106,9 @@ internal static class BacktestCommand
}
/// <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)
internal 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"]);
var rates = await Ecb.LoadHistoryAsync(http, researchRoot, offline, ["USD"], CancellationToken.None).ConfigureAwait(false);
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;
+55 -4
View File
@@ -15,15 +15,18 @@ internal static class DataCommand
{
private const string Usage =
"Uso: anubis data report [--days N] [--out file.md]\n" +
" anubis data binance <SIMBOLO> <1d|1m> <AAAA-MM> (per esempio BTCUSDT 1d 2017-08)\n" +
" anubis data csv <file.csv> (colonne descritte in file.mapping.json o mapping.json)\n" +
" anubis data binance <SIMBOLO> <1d|1m|15m|30m|1h|4h|8h> <AAAA-MM> (per esempio BTCUSDT 1d 2017-08)\n" +
" anubis data csv <file.csv> (colonne descritte in file.mapping.json o mapping.json)\n" +
" anubis data ecb [--offline] (le 28 coppie delle otto valute dai cambi giornalieri della BCE, dal 1999;\n" +
" con --offline usa lo storico già scaricato, anche da backtest base)\n" +
" anubis data fx <file.csv> [--symbol EURUSD] (file a un minuto di Dukascopy o HistData: scrive le barre da 1 e da 15 minuti)\n" +
"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 ("report" or "binance" or "csv"))
if (args.Length < 1 || args[0] is not ("report" or "binance" or "csv" or "ecb" or "fx"))
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
@@ -58,6 +61,26 @@ internal static class DataCommand
var result = await new CsvImporter(new ResearchStore(config.Data.Research)).ImportAsync(file, CsvImporter.MappingFor(file), CancellationToken.None)
.ConfigureAwait(false);
await WriteAsync(output, result).ConfigureAwait(false);
return 0;
case "ecb" when positional.Count == 0:
config.Data.Ensure();
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}");
await EcbAsync(new ApiHttp(http, clock, Ecb.Source), new ResearchStore(config.Data.Research), rest.Contains("--offline"), output)
.ConfigureAwait(false);
}
return 0;
case "fx" when positional.Count == 1:
config.Data.Ensure();
foreach (var imported in await new FxMinuteImporter(new ResearchStore(config.Data.Research))
.ImportAsync(Path.GetFullPath(positional[0]), Option(rest, "--symbol"), CancellationToken.None).ConfigureAwait(false))
{
await WriteAsync(output, imported).ConfigureAwait(false);
}
return 0;
default:
await output.WriteLineAsync(Usage).ConfigureAwait(false);
@@ -65,13 +88,41 @@ internal static class DataCommand
}
}
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or System.Text.Json.JsonException
or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException)
or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException
or System.IO.InvalidDataException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
/// <summary>The 28 pairs from the ECB history (the zip shared with backtest base), one series each under research/ecb.</summary>
private static async Task EcbAsync(ApiHttp http, ResearchStore store, bool offline, TextWriter output)
{
var rates = await Ecb.LoadHistoryAsync(http, store.Root, offline, EcbCrosses.Rates, CancellationToken.None).ConfigureAwait(false);
var crosses = EcbCrosses.Build(rates);
var written = crosses.Where(c => c.Value.Count > 0).ToList();
if (written.Count == 0)
{
throw new MarketDataException("BCE: lo storico non contiene i cambi delle sette valute.", retryable: false);
}
foreach (var (pair, bars) in written)
{
await store.WriteAsync(EcbCrosses.Venue, pair, Timeframes.Day, bars, CancellationToken.None).ConfigureAwait(false);
}
var days = written.SelectMany(c => c.Value.Select(b => b.OpensAt)).Distinct().Order().ToList();
var missing = days.Count * crosses.Count - crosses.Values.Sum(b => b.Count);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Coppie di valute dai cambi BCE: {written.Count} coppie, {days.Count} giorni, dal {days[0]:yyyy-MM-dd} al {days[^1]:yyyy-MM-dd}.")).ConfigureAwait(false);
if (missing > 0)
{
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"- {missing} barre giornaliere mancano perché quel giorno la BCE non ha pubblicato uno dei due cambi.")).ConfigureAwait(false);
}
}
private static async Task<int> ReportAsync(Platform.StartupConfig config, IClock clock, IReadOnlyList<string> rest, TextWriter output)
{
if (!config.IsComplete)
+1 -1
View File
@@ -26,7 +26,7 @@ static async Task<int> RunAsync(string[] args)
return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis data report|binance|csv": the data quality report and the research imports (Phase 2).
// "anubis data report|binance|csv|ecb|fx": the data quality report and the research imports (Phases 2 and 12).
if (args.Length >= 1 && args[0] == "data")
{
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
+10
View File
@@ -53,6 +53,13 @@ public sealed record BacktestTrade(string Symbol, DateOnly Opened, DateOnly? Clo
public bool IsClosed => Closed is not null;
}
/// <summary>
/// A basket from its first level to its exit: the relation it trades (a pair of symbols or one), the units of each order,
/// how many levels it reached, its legs, why it closed (null while open) and its result net of every cost, in the dataset
/// currency. Only the basket engine writes them.
/// </summary>
public sealed record BacktestBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList<string> Legs, string? ExitReason, decimal Result);
/// <summary>What the strategy proposed on a day, and what was left after correctives and risk.</summary>
public sealed record DecisionRecord(DateOnly Day, IReadOnlyList<Intent> Proposed, IReadOnlyList<Intent> Final);
@@ -80,6 +87,9 @@ public sealed record BacktestRun(
/// <summary>Value of the leftovers below the minimum written off after an exit (SPEC 7.2).</summary>
public decimal WrittenOff { get; init; }
/// <summary>The baskets of an engine that trades them, in the order they opened; empty for the daily engine.</summary>
public IReadOnlyList<BacktestBasket> Baskets { get; init; } = [];
/// <summary>Daily returns of the equity, one per session after the first.</summary>
public double[] DailyReturns()
{
+46 -37
View File
@@ -10,6 +10,9 @@ namespace Anubis.Backtest;
/// <summary>An instrument of the report: where its bars come from and what period they cover.</summary>
public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? First, DateOnly? Last, int Bars, int Actions, string Source);
/// <summary>A basket of the judged variant (<see cref="BacktestBasket"/>), as the report shows it.</summary>
public sealed record ReportBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList<string> Legs, string? ExitReason, decimal Result);
/// <summary>A point of the equity curve of the chosen variant and of buy and hold, on the same day.</summary>
public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark);
@@ -95,6 +98,9 @@ public sealed record BacktestReport(
/// <summary>The variant in use, when the figures, the checks and the curve are its own (<see cref="TrialPlan.Judged"/>); null when they are those of the chosen one.</summary>
public string? Judged { get; init; }
/// <summary>The last baskets of the judged variant, at most <see cref="TrialRunner.MaxTrades"/>; null (left out) for an engine without baskets.</summary>
public IReadOnlyList<ReportBasket>? Baskets { get; init; }
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize<BacktestReport>(text, TrialPlan.Json) ?? throw new JsonException("Empty report");
@@ -105,7 +111,8 @@ public sealed record BacktestReport(
/// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily
/// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan
/// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice,
/// the overfitting and the number of tries.
/// the overfitting and the number of tries. The engine that runs the variants is an <see cref="ITrialEngine"/>: the daily one
/// (<see cref="DailyTrialEngine"/>) unless the caller gives another.
/// </summary>
public static class TrialRunner
{
@@ -113,6 +120,7 @@ public static class TrialRunner
public const int MaxTrades = 300;
/// <summary>A trial of a daily family on daily data: the judge with the <see cref="DailyTrialEngine"/>.</summary>
public static (BacktestReport Report, TrialSummary Summary) Run(
Guid trialId, TrialPlan plan, string planHash, IStrategyFamily family, BacktestDataset data, PriorTrials prior, DateTimeOffset now,
Action<string>? progress = null, CancellationToken cancellationToken = default)
@@ -121,8 +129,20 @@ public static class TrialRunner
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(prior);
return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken);
}
/// <summary>A trial of any family on any engine: the same validations, checks and report whatever the engine.</summary>
public static (BacktestReport Report, TrialSummary Summary) Run(
Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now,
Action<string>? progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(prior);
var watch = Stopwatch.StartNew();
var sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To);
var sessions = engine.Sessions;
if (sessions < 30)
{
throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30.");
@@ -134,15 +154,12 @@ public static class TrialRunner
throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri.");
}
// The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does.
var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } };
var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare);
var runs = new BacktestRun[variants.Count];
for (var i = 0; i < variants.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke($"variante {i + 1} di {variants.Count}");
runs[i] = BacktestEngine.Run(family.Create(variants[i].Parameters), data, options);
runs[i] = engine.Run(variants[i].Parameters);
}
var returns = runs.Select(r => r.DailyReturns()).ToArray();
@@ -157,21 +174,22 @@ public static class TrialRunner
progress?.Invoke("variante in uso");
}
var run = judgedIndex < 0 ? BacktestEngine.Run(family.Create(judged), data, options) : runs[judgedIndex];
var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex];
var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex];
var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear);
var year = engine.PeriodsPerYear;
var metrics = BacktestMetrics.Of(run, year);
progress?.Invoke("costi doppi e tripli, comprare e tenere");
var costs = new List<ReportCosts>();
foreach (var multiplier in plan.CostMultipliers.Distinct().Order())
{
var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(judged), data, options with { Costs = options.Costs with { Multiplier = multiplier } });
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear);
var costed = multiplier == 1m ? run : engine.Run(judged, multiplier);
var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year);
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
}
var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, plain);
var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear);
var benchmarkRun = engine.Benchmark();
var benchmark = BacktestMetrics.Of(benchmarkRun, year);
cancellationToken.ThrowIfCancellationRequested();
progress?.Invoke("convalide");
@@ -195,7 +213,7 @@ public static class TrialRunner
var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread);
progress?.Invoke("test anti sguardo in avanti");
var look = LookAheadCheck.Run(_ => family.Create(judged), data, options, v.LookAheadCuts);
var look = engine.LookAhead(judged, v.LookAheadCuts);
var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count,
[.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]);
@@ -226,18 +244,17 @@ public static class TrialRunner
family.Name,
family.Version,
planHash,
data.Fingerprint(),
data.Currency,
data.PeriodsPerYear,
engine.Fingerprint(),
engine.Currency,
year,
sessions,
[.. data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null,
i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))],
engine.Instruments(),
chosen.ToString(),
metrics,
benchmark,
costs,
[.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult,
Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)),
.. judgedIndex >= 0 ? Array.Empty<ReportVariant>()
: [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]],
walkForward,
@@ -248,36 +265,28 @@ public static class TrialRunner
lookAhead,
checks,
passed,
judgedIndex >= 0 ? Limitations(plan, family, data)
: [.. Limitations(plan, family, data), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."],
judgedIndex >= 0 ? engine.Limitations()
: [.. engine.Limitations(), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."],
curve,
[.. run.Trades.TakeLast(MaxTrades)],
run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
now,
watch.Elapsed.TotalSeconds)
{ Judged = plan.Judged is null ? null : judged.ToString() };
if (StrategyPipeline.ResearchShare(family.Id) is not null)
{
var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var table = plan.Slippage ?? SlippageTable.Standard;
var traded = run.Trades.Sum(x => x.Invested);
report = report with
{
ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null),
ExpectedPathP5 = [.. PathBootstrap.Percentile(judgedReturns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
.Select(x => Math.Round(x, 4))],
};
}
Judged = plan.Judged is null ? null : judged.ToString(),
Baskets = run.Baskets.Count == 0 ? null
: [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))],
};
var expected = engine.Expected(run, judgedReturns);
report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 };
var summary = new TrialSummary(data.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades,
dsr.Value, pbo?.Probability, sharpes);
return (report, summary);
}
private static BacktestMetrics Metrics(BacktestRun run, BacktestDataset data) => BacktestMetrics.Of(run, data.PeriodsPerYear);
/// <summary>What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it).</summary>
public static IReadOnlyList<string> Limitations(TrialPlan plan, IStrategyFamily family, BacktestDataset data)
public static IReadOnlyList<string> Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
+118
View File
@@ -0,0 +1,118 @@
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Backtest;
/// <summary>
/// What an engine expects of the judged variant once it trades for real: the mean slippage in basis points and the 5th
/// percentile of the expected path (SPEC 12.3). Null where the engine has nothing to expect (the examples).
/// </summary>
public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList<double>? PathP5)
{
public static TrialExpectations None { get; } = new(null, null);
}
/// <summary>
/// What the trial judge (<see cref="TrialRunner"/>) asks of an engine, so the same judge, with the same validations and the
/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in
/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check.
/// </summary>
public interface ITrialEngine
{
/// <summary>The currency of the money in the runs and in the report.</summary>
string Currency { get; }
/// <summary>Periods in a year, to annualise the returns of the runs.</summary>
int PeriodsPerYear { get; }
/// <summary>The sessions of the plan's window, both ends included: fewer than 30 and there is no trial.</summary>
int Sessions { get; }
/// <summary>A hash of the data the runs read, for the report.</summary>
string Fingerprint();
/// <summary>The instruments of the data, with the period they cover.</summary>
IReadOnlyList<ReportInstrument> Instruments();
/// <summary>One variant over the whole window, with costs multiplied by <paramref name="costMultiplier"/>.</summary>
BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m);
/// <summary>The term of comparison of the report: buy and hold for the daily engine, its own for an engine that is not.</summary>
BacktestRun Benchmark();
/// <summary>The check of SPEC 12.2 point 2: a decision must not change when data after it is added.</summary>
LookAheadResult LookAhead(StrategyParameters parameters, int cuts);
/// <summary>What this engine does not model, in plain Italian (SPEC 12.1).</summary>
IReadOnlyList<string> Limitations();
/// <summary>What the judged variant should give once it trades, from its run and its returns.</summary>
TrialExpectations Expected(BacktestRun run, double[] returns);
}
/// <summary>
/// The daily engine of the trial judge: <see cref="BacktestEngine"/> on daily closes, the strategy through its correctives and
/// the risk engine, buy and hold as the comparison. The options are built once, so every run shares the same risk state as it
/// always did.
/// </summary>
public sealed class DailyTrialEngine : ITrialEngine
{
private readonly TrialPlan _plan;
private readonly IStrategyFamily _family;
private readonly BacktestDataset _data;
private readonly BacktestOptions _plain;
private readonly BacktestOptions _options;
public DailyTrialEngine(TrialPlan plan, IStrategyFamily family, BacktestDataset data)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
ArgumentNullException.ThrowIfNull(data);
_plan = plan;
_family = family;
_data = data;
// The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does.
_plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } };
_options = StrategyPipeline.For(family.Id, data, _plain, plan.ReferenceShare);
Sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To);
}
public string Currency => _data.Currency;
public int PeriodsPerYear => _data.PeriodsPerYear;
public int Sessions { get; }
public string Fingerprint() => _data.Fingerprint();
public IReadOnlyList<ReportInstrument> Instruments() =>
[.. _data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null,
i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))];
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) =>
BacktestEngine.Run(_family.Create(parameters), _data, costMultiplier == 1m ? _options : _options with { Costs = _options.Costs with { Multiplier = costMultiplier } });
public BacktestRun Benchmark() => BacktestEngine.Run(new BuyAndHold(_data.Tradable.Count()), _data, _plain);
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => LookAheadCheck.Run(_ => _family.Create(parameters), _data, _options, cuts);
public IReadOnlyList<string> Limitations() => TrialRunner.Limitations(_plan, _family, _data);
public TrialExpectations Expected(BacktestRun run, double[] returns)
{
ArgumentNullException.ThrowIfNull(run);
ArgumentNullException.ThrowIfNull(returns);
if (StrategyPipeline.ResearchShare(_family.Id) is null)
{
return TrialExpectations.None;
}
var specs = _data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
var table = _plan.Slippage ?? SlippageTable.Standard;
var traded = run.Trades.Sum(x => x.Invested);
return new TrialExpectations(
traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null),
[.. PathBootstrap.Percentile(returns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed).Select(x => Math.Round(x, 4))]);
}
}
+17 -6
View File
@@ -5,6 +5,12 @@ namespace Anubis.Backtest;
/// <summary>One point of a parameter grid: its parameters and its place on each parameter's grid (for neighbours).</summary>
public sealed record Variant(int Index, StrategyParameters Parameters, IReadOnlyList<int> Position)
{
/// <summary>
/// For each axis, in the order of <see cref="Position"/>, whether it is a choice axis (<see cref="ParameterSpec.Choices"/>);
/// null when none is.
/// </summary>
public IReadOnlyList<bool>? Choices { get; init; }
public override string ToString() => Parameters.ToString();
}
@@ -15,12 +21,14 @@ public static class ParameterGrid
/// The Cartesian product of the grids (the family's own, or <paramref name="grids"/> where given), without the
/// points the family rejects. A family without parameters has one variant.
/// </summary>
public static IReadOnlyList<Variant> Of(IStrategyFamily family, IReadOnlyDictionary<string, IReadOnlyList<decimal>>? grids = null)
public static IReadOnlyList<Variant> Of(IResearchFamily family, IReadOnlyDictionary<string, IReadOnlyList<decimal>>? grids = null)
{
ArgumentNullException.ThrowIfNull(family);
var axes = family.Parameters
.Select(p => (p.Name, Values: (IReadOnlyList<decimal>)[.. (grids?.GetValueOrDefault(p.Name) ?? p.Grid).Distinct().Order()]))
.ToList();
bool[] marks = [.. family.Parameters.Select(p => p.Choices)];
var choices = marks.Any(c => c) ? marks : null;
if (axes.Any(a => a.Values.Count == 0))
{
throw new ArgumentException("Every parameter needs at least one value on its grid", nameof(grids));
@@ -33,7 +41,7 @@ public static class ParameterGrid
var parameters = new StrategyParameters(axes.Select((a, i) => KeyValuePair.Create(a.Name, a.Values[position[i]])));
if (family.Accepts(parameters))
{
result.Add(new Variant(result.Count, parameters, [.. position]));
result.Add(new Variant(result.Count, parameters, [.. position]) { Choices = choices });
}
// Next point: the last parameter moves fastest.
@@ -116,7 +124,8 @@ public sealed record OverfittingResult(int Groups, int Combinations, int Variant
public static class Validation
{
/// <summary>
/// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every axis.
/// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every numeric axis
/// with the same value on every choice axis (<see cref="Variant.Choices"/>).
/// </summary>
public static double[] PlateauScores(IReadOnlyList<Variant> variants, IReadOnlyList<double> values)
{
@@ -129,7 +138,7 @@ public static class Validation
var count = 0;
for (var j = 0; j < variants.Count; j++)
{
if (Neighbours(variants[i].Position, variants[j].Position))
if (Neighbours(variants[i].Position, variants[j].Position, variants[i].Choices))
{
sum += values[j];
count++;
@@ -436,11 +445,13 @@ public static class Validation
return sums;
}
private static bool Neighbours(IReadOnlyList<int> a, IReadOnlyList<int> b)
/// <summary>One step at most on every numeric axis; on a choice axis only the same value.</summary>
private static bool Neighbours(IReadOnlyList<int> a, IReadOnlyList<int> b, IReadOnlyList<bool>? choices)
{
for (var k = 0; k < a.Count; k++)
{
if (Math.Abs(a[k] - b[k]) > 1)
var limit = choices is not null && choices[k] ? 0 : 1;
if (Math.Abs(a[k] - b[k]) > limit)
{
return false;
}
+261
View File
@@ -0,0 +1,261 @@
namespace Anubis.Baskets;
/// <summary>
/// The index of a relation and the statistics on it (sections 4.2, 4.3, 4.7 and 11.3, appendix C): the index in pips and in
/// log basis points, the z-score, the relative volatility Rvol with its filter, the correlation of log returns and the hedge
/// ratio. Statistics are <see cref="double"/>. Every value at bar t reads bars up to t only; which price feeds the index (mid
/// when bid and ask exist, bid otherwise) is the caller's choice. A missing value (not a number) inside a window gives null.
/// </summary>
public static class BasketIndex
{
/// <summary>Bars of the z-score window: 100 bars of 15 minutes, 25 hours.</summary>
public const int DefaultWindow = 100;
/// <summary>Differences in the short volatility window: 16 bars of 15 minutes, 4 hours.</summary>
public const int DefaultShortBars = 16;
/// <summary>Market days of the volatility baseline.</summary>
public const int DefaultBaselineDays = 20;
/// <summary>Bars of the baseline for 15-minute bars on a 24×5 market: 20 days × 96 bars.</summary>
public const int DefaultBaselineBars = DefaultBaselineDays * 96;
/// <summary>Above this Rvol no new entry opens.</summary>
public const double DefaultMaxRvol = 2.0;
private const double BasisPoints = 10_000;
/// <summary>The pip index of two legs: X = A / pip(A) + s · B / pip(B).</summary>
public static double Pips(double priceA, FxPair a, double priceB, FxPair b, int sign)
{
ArgumentNullException.ThrowIfNull(b);
return Pips(priceA, a) + (sign * priceB / (double)b.Pip);
}
/// <summary>The pip index of a single symbol: X = A / pip(A).</summary>
public static double Pips(double price, FxPair pair)
{
ArgumentNullException.ThrowIfNull(pair);
return price / (double)pair.Pip;
}
/// <summary>
/// The log index in basis points (section 11.3): X = 10,000 · (ln A − β · ln B), β = 1 unless a hedge ratio is given.
/// For a relation of the 28 pairs in log form pass β = −s.
/// </summary>
public static double LogBp(double priceA, double priceB, double beta = 1) => BasisPoints * (Math.Log(priceA) - (beta * Math.Log(priceB)));
/// <summary>The log index of a single symbol: X = 10,000 · ln P.</summary>
public static double LogBp(double price) => BasisPoints * Math.Log(price);
/// <summary>
/// The z-score at closed bar <paramref name="t"/>: (X(t) − mean) / sample standard deviation (n − 1) of the last
/// <paramref name="window"/> values, bar t included. Null with fewer values than the window or a flat window.
/// </summary>
public static double? ZScore(IReadOnlyList<double> index, int t, int window = DefaultWindow)
{
ArgumentNullException.ThrowIfNull(index);
ArgumentOutOfRangeException.ThrowIfLessThan(window, 2);
if (!Within(index, t) || t + 1 < window)
{
return null;
}
// A flat window has no z-score. Its mean can miss the common value by one rounding step, which would leave a
// deviation of 1e-12 and a meaningless z of ±0.995: so a window whose values are all equal is flat by definition.
if (Flat(index, t - window + 1, t))
{
return null;
}
var deviation = Deviation(index, t - window + 1, t, out var mean);
return deviation is > 0 ? (index[t] - mean) / deviation : null;
}
/// <summary>
/// σ_short at bar <paramref name="t"/>: the sample standard deviation of the last <paramref name="shortBars"/> first
/// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter.
/// </summary>
public static double? ShortSigma(IReadOnlyList<double> index, int t, int shortBars = DefaultShortBars)
{
ArgumentNullException.ThrowIfNull(index);
ArgumentOutOfRangeException.ThrowIfLessThan(shortBars, 2);
if (!Within(index, t) || t < shortBars)
{
return null;
}
var differences = new double[shortBars];
for (var i = 0; i < shortBars; i++)
{
var at = t - shortBars + 1 + i;
differences[i] = index[at] - index[at - 1];
}
return Deviation(differences, 0, shortBars - 1, out _);
}
/// <summary>Bars of the volatility baseline for a market with <paramref name="barsPerDay"/> bars a day.</summary>
public static int BaselineBars(int barsPerDay, int days = DefaultBaselineDays) => barsPerDay * days;
/// <summary>
/// Rvol at bar <paramref name="t"/>: σ_short(t) over σ_base(t), the median of σ_short over the last
/// <paramref name="baselineBars"/> bars ending at t. Null without enough history for every σ_short of the baseline, or
/// when σ_base is zero.
/// </summary>
public static double? Rvol(IReadOnlyList<double> index, int t, int baselineBars = DefaultBaselineBars, int shortBars = DefaultShortBars)
{
ArgumentNullException.ThrowIfNull(index);
ArgumentOutOfRangeException.ThrowIfLessThan(baselineBars, 1);
if (!Within(index, t) || t - baselineBars + 1 < shortBars)
{
return null;
}
var sigmas = new double[baselineBars];
for (var i = 0; i < baselineBars; i++)
{
if (ShortSigma(index, t - baselineBars + 1 + i, shortBars) is not { } sigma)
{
return null;
}
sigmas[i] = sigma;
}
var current = sigmas[^1];
Array.Sort(sigmas);
var middle = baselineBars / 2;
var baseline = baselineBars % 2 == 1 ? sigmas[middle] : (sigmas[middle - 1] + sigmas[middle]) / 2;
return baseline > 0 ? current / baseline : null;
}
/// <summary>The volatility filter: a new entry only with a known Rvol no higher than <paramref name="max"/>.</summary>
public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max;
/// <summary>
/// Pearson correlation of the log returns of two price series over the last <paramref name="window"/> returns ending at
/// bar <paramref name="t"/> (window + 1 prices). Null without enough prices, with a missing price or a flat leg.
/// </summary>
public static double? Correlation(IReadOnlyList<double> pricesA, IReadOnlyList<double> pricesB, int t, int window = DefaultWindow)
{
ArgumentNullException.ThrowIfNull(pricesA);
ArgumentNullException.ThrowIfNull(pricesB);
ArgumentOutOfRangeException.ThrowIfLessThan(window, 2);
if (!Within(pricesA, t) || !Within(pricesB, t) || t < window)
{
return null;
}
var x = new double[window];
var y = new double[window];
for (var i = 0; i < window; i++)
{
var at = t - window + 1 + i;
x[i] = Math.Log(pricesA[at] / pricesA[at - 1]);
y[i] = Math.Log(pricesB[at] / pricesB[at - 1]);
}
return Pearson(x, y);
}
/// <summary>
/// The hedge ratio β of a statistical relation: the slope of the least-squares regression of ln A on ln B over the
/// formation window given. It stays fixed until the next reselection. Null with fewer than two points or a flat B.
/// </summary>
public static double? HedgeRatio(IReadOnlyList<double> pricesA, IReadOnlyList<double> pricesB)
{
ArgumentNullException.ThrowIfNull(pricesA);
ArgumentNullException.ThrowIfNull(pricesB);
if (pricesA.Count != pricesB.Count)
{
throw new ArgumentException("Le due serie del rapporto di copertura devono avere la stessa lunghezza.", nameof(pricesB));
}
if (pricesA.Count < 2)
{
return null;
}
var y = pricesA.Select(p => Math.Log(p)).ToArray();
var x = pricesB.Select(p => Math.Log(p)).ToArray();
if (!y.All(double.IsFinite) || !x.All(double.IsFinite))
{
return null;
}
var meanX = x.Average();
var meanY = y.Average();
var covariance = 0d;
var variance = 0d;
for (var i = 0; i < x.Length; i++)
{
covariance += (x[i] - meanX) * (y[i] - meanY);
variance += (x[i] - meanX) * (x[i] - meanX);
}
return variance > 0 ? covariance / variance : null;
}
private static bool Within(IReadOnlyList<double> values, int t) => t >= 0 && t < values.Count;
private static bool Flat(IReadOnlyList<double> values, int from, int to)
{
for (var i = from + 1; i <= to; i++)
{
if (values[i] != values[from])
{
return false;
}
}
return true;
}
/// <summary>Sample standard deviation of values[from..to]; null when a value is missing.</summary>
private static double? Deviation(IReadOnlyList<double> values, int from, int to, out double mean)
{
var count = to - from + 1;
var sum = 0d;
for (var i = from; i <= to; i++)
{
sum += values[i];
}
mean = sum / count;
if (!double.IsFinite(mean))
{
return null;
}
var squares = 0d;
for (var i = from; i <= to; i++)
{
squares += (values[i] - mean) * (values[i] - mean);
}
return Math.Sqrt(squares / (count - 1));
}
private static double? Pearson(double[] x, double[] y)
{
var meanX = x.Average();
var meanY = y.Average();
if (!double.IsFinite(meanX) || !double.IsFinite(meanY))
{
return null;
}
var sxy = 0d;
var sxx = 0d;
var syy = 0d;
for (var i = 0; i < x.Length; i++)
{
sxy += (x[i] - meanX) * (y[i] - meanY);
sxx += (x[i] - meanX) * (x[i] - meanX);
syy += (y[i] - meanY) * (y[i] - meanY);
}
return sxx > 0 && syy > 0 ? Math.Clamp(sxy / Math.Sqrt(sxx * syy), -1, 1) : null;
}
}
+237
View File
@@ -0,0 +1,237 @@
namespace Anubis.Baskets;
/// <summary>Buying or selling (section 4.4): a bought (long) order gains when the price rises, a sold (short) one when it falls.</summary>
public enum Direction
{
Buy,
Sell,
}
/// <summary>The two prices of a quote (section 4.5): a bought order closes at the bid, a sold one at the ask.</summary>
public readonly record struct BidAsk(decimal Bid, decimal Ask);
/// <summary>One open order of a basket (section 4.5): pair, direction and entry price.</summary>
public sealed record BasketOrder(FxPair Pair, Direction Side, decimal Entry)
{
/// <summary>Pips of the order at a quote: long (bid − entry) / pip, short (entry − ask) / pip.</summary>
public decimal Pips(BidAsk quote) => BasketMath.OrderPips(Side, Entry, quote, Pair.Pip);
}
/// <summary>A leg for the exposure per currency (section 4.4, appendix C): units of the base at a price.</summary>
public sealed record ExposureLeg(FxPair Pair, Direction Side, decimal Units, decimal Price);
/// <summary>Units on each leg of a unit (section 6.4); <see cref="Raised"/> when the venue minimum lifted them.</summary>
public sealed record LegUnits(decimal Units, bool Raised)
{
/// <summary>The effective lot the ledger records: units / 100,000.</summary>
public decimal Lot() => Units / BasketMath.LotUnits;
}
/// <summary>
/// The money arithmetic of a basket, all in <see cref="decimal"/> (sections 4.5, 4.6, 4.12, 6.4, 6.9 and 11.3, appendices A
/// and C): pip sum, common exit price, distance scale, stop excursion, pip value, equal units raised to the venue minimum,
/// exposure per currency and the three-costs rule.
/// </summary>
public static class BasketMath
{
/// <summary>Units in one lot.</summary>
public const decimal LotUnits = 100_000m;
/// <summary>The venue's minimum exposure per position, in USD (section 6.4).</summary>
public const decimal VenueMinimumUsd = 1_000m;
/// <summary>A unit opens only when its target is at least this many times its cost (section 11.3).</summary>
public const decimal CostMultiple = 3m;
/// <summary>Pips of one order: long (bid − entry) / pip, short (entry − ask) / pip.</summary>
public static decimal OrderPips(Direction side, decimal entry, BidAsk quote, decimal pip) =>
side == Direction.Buy ? (quote.Bid - entry) / pip : (entry - quote.Ask) / pip;
/// <summary>The pip sum of a basket: the pips of every open order, added.</summary>
public static decimal PipSum(IEnumerable<BasketOrder> orders, Func<FxPair, BidAsk> quotes)
{
ArgumentNullException.ThrowIfNull(orders);
ArgumentNullException.ThrowIfNull(quotes);
return orders.Sum(o => o.Pips(quotes(o.Pair)));
}
/// <summary>
/// The common exit price of n equal orders on one symbol (section 4.5, appendix C): mean(entries) + target / n · pip for
/// longs (the bid reaches it), − target / n · pip for shorts (the ask reaches it). At that price the pip sum is the target.
/// </summary>
public static decimal CommonExit(IReadOnlyList<decimal> entries, Direction side, decimal targetPips, decimal pip)
{
ArgumentNullException.ThrowIfNull(entries);
ArgumentOutOfRangeException.ThrowIfZero(entries.Count);
var move = MovePerOrder(targetPips, entries.Count) * pip;
var mean = entries.Sum() / entries.Count;
return side == Direction.Buy ? mean + move : mean - move;
}
/// <summary>Table 4.5: the move beyond the mean entry each of n equal orders needs for the target, in pips (target / n).</summary>
public static decimal MovePerOrder(decimal targetPips, int orders)
{
ArgumentOutOfRangeException.ThrowIfLessThan(orders, 1);
return targetPips / orders;
}
/// <summary>The distance factor of Rvol: max(1, min(Rvol, 3)).</summary>
public static decimal DistanceFactor(double rvol) => (decimal)Math.Max(1, Math.Min(Finite(rvol), 3));
/// <summary>The dynamic target factor of Rvol: max(0.7, min(Rvol, 3)).</summary>
public static decimal TargetFactor(double rvol) => (decimal)Math.Max(0.7, Math.Min(Finite(rvol), 3));
/// <summary>
/// The distance of the k-th re-entry (section 4.6, appendix C): Dmin × max(1, min(Rvol, 3)) × g^(k − 1), measured from
/// the last level, k = 1 … MaxReentries.
/// </summary>
public static decimal Distance(decimal minDistance, double rvol, decimal growth, int k)
{
ArgumentOutOfRangeException.ThrowIfLessThan(k, 1);
var distance = minDistance * DistanceFactor(rvol);
for (var i = 1; i < k; i++)
{
distance *= growth;
}
return distance;
}
/// <summary>The distances of every re-entry, k = 1 … <paramref name="maxReentries"/>.</summary>
public static IReadOnlyList<decimal> Distances(decimal minDistance, double rvol, decimal growth, int maxReentries)
{
ArgumentOutOfRangeException.ThrowIfNegative(maxReentries);
return [.. Enumerable.Range(1, maxReentries).Select(k => Distance(minDistance, rvol, growth, k))];
}
/// <summary>Whether a basket with <paramref name="levels"/> levels open may add one: only while levels &lt; 1 + MaxReentries.</summary>
public static bool CanAdd(int levels, int maxReentries) => levels >= 1 && levels < 1 + maxReentries;
/// <summary>The distance the next level needs from the last one; null once the last level is open.</summary>
public static decimal? NextDistance(int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) =>
CanAdd(levels, maxReentries) ? Distance(minDistance, rvol, growth, levels) : null;
/// <summary>
/// Whether to add a level: a level may still be added and the last level has lost at least the distance. The lot of the
/// new level is the lot of the first; it never grows.
/// </summary>
public static bool ShouldAdd(decimal lastLevelPips, int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) =>
NextDistance(levels, maxReentries, minDistance, rvol, growth) is { } distance && lastLevelPips <= -distance;
/// <summary>The pip sum of n levels, D apart, when the first level stands at E pips (appendix C): n·E + D·n(n − 1)/2.</summary>
public static decimal PipSumAtExcursion(int levels, decimal firstLevelPips, decimal distance)
{
ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1);
return (levels * firstLevelPips) + (distance * levels * (levels - 1) / 2);
}
/// <summary>
/// The first-level excursion E ≤ 0 at which n full levels lose <paramref name="threshold"/> of the capital (table 4.12,
/// section 6.9): |n·E + D·n(n − 1)/2| × lot × pip value per lot = threshold × capital. Exact; the document's tables
/// show it rounded half to even.
/// </summary>
public static decimal StopExcursion(int levels, decimal distance, decimal lot, decimal pipValuePerLot, decimal threshold, decimal capital)
{
ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(lot);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot);
var pipSum = -(threshold * capital) / (lot * pipValuePerLot);
return (pipSum - (distance * levels * (levels - 1) / 2)) / levels;
}
/// <summary>The lot that loses <paramref name="threshold"/> of the capital at the excursion E (appendix C).</summary>
public static decimal LotForRisk(int levels, decimal excursion, decimal distance, decimal pipValuePerLot, decimal threshold, decimal capital)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot);
var pipSum = Math.Abs(PipSumAtExcursion(levels, excursion, distance));
if (pipSum == 0)
{
throw new ArgumentException("A questa escursione la somma dei pip è zero: nessun lotto la porta alla soglia.", nameof(excursion));
}
return threshold * capital / (pipValuePerLot * pipSum);
}
/// <summary>
/// The USD value of one unit of a currency (appendix C): 1 for the dollar, the price of XUSD when it is a pair, 1 / USDX
/// otherwise (usd(JPY) = 1 / USDJPY).
/// </summary>
public static decimal UsdPerUnit(string currency, Func<FxPair, decimal> price)
{
ArgumentNullException.ThrowIfNull(price);
if (currency == Currencies.Usd)
{
return 1m;
}
var pair = FxPairs.Of(currency, Currencies.Usd)
?? throw new ArgumentException($"{currency} non è una delle otto valute.", nameof(currency));
return pair.Base == Currencies.Usd ? 1m / price(pair) : price(pair);
}
/// <summary>The value of one pip in USD (appendix C): units × pip × usd(quote).</summary>
public static decimal PipValue(FxPair pair, decimal units, decimal usdPerQuote)
{
ArgumentNullException.ThrowIfNull(pair);
return units * pair.Pip * usdPerQuote;
}
/// <summary>The value of one pip in USD, the quote currency valued at the prices given.</summary>
public static decimal PipValue(FxPair pair, decimal units, Func<FxPair, decimal> price)
{
ArgumentNullException.ThrowIfNull(pair);
return PipValue(pair, units, UsdPerUnit(pair.Quote, price));
}
/// <summary>
/// Equal units on every leg (section 6.4 and the forward-test phase): LotPer10k × capital / 10,000 × 100,000, in whole
/// units. When a leg would be worth less than the venue minimum, every leg rises to the units that bring the weakest leg
/// (the lowest USD value of its base) to the minimum, rounded up to whole units.
/// </summary>
public static LegUnits EqualUnits(decimal lotPer10k, decimal capital, IReadOnlyList<decimal> usdPerBase, decimal minimumUsd = VenueMinimumUsd)
{
ArgumentNullException.ThrowIfNull(usdPerBase);
ArgumentOutOfRangeException.ThrowIfZero(usdPerBase.Count);
var weakest = usdPerBase.Min();
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weakest);
var units = Math.Floor(lotPer10k * capital / 10_000m * LotUnits);
if (units * weakest >= minimumUsd)
{
return new LegUnits(units, false);
}
return new LegUnits(Math.Ceiling(minimumUsd / weakest), true);
}
/// <summary>
/// The net position per currency in native units (section 4.4, appendix C): a long of U units of BASEQUOTE at price P is
/// +U of the base and −U·P of the quote; a short reverses both signs.
/// </summary>
public static IReadOnlyDictionary<string, decimal> Exposure(IEnumerable<ExposureLeg> legs)
{
ArgumentNullException.ThrowIfNull(legs);
var net = new Dictionary<string, decimal>(StringComparer.Ordinal);
foreach (var leg in legs)
{
var sign = leg.Side == Direction.Buy ? 1m : -1m;
net[leg.Pair.Base] = net.GetValueOrDefault(leg.Pair.Base) + (sign * leg.Units);
net[leg.Pair.Quote] = net.GetValueOrDefault(leg.Pair.Quote) - (sign * leg.Units * leg.Price);
}
return net;
}
/// <summary>The net position per currency valued in USD.</summary>
public static IReadOnlyDictionary<string, decimal> UsdExposure(IReadOnlyDictionary<string, decimal> native, Func<FxPair, decimal> price)
{
ArgumentNullException.ThrowIfNull(native);
return native.ToDictionary(e => e.Key, e => e.Value * UsdPerUnit(e.Key, price), StringComparer.Ordinal);
}
/// <summary>The three-costs rule (section 11.3): a unit opens only if its target is at least three times its cost.</summary>
public static bool PassesCostRule(decimal targetPips, decimal costPips, decimal multiple = CostMultiple) => targetPips >= multiple * costPips;
private static double Finite(double rvol) =>
double.IsFinite(rvol) ? rvol : throw new ArgumentOutOfRangeException(nameof(rvol), rvol, "Rvol deve essere un numero finito.");
}
+79
View File
@@ -0,0 +1,79 @@
namespace Anubis.Baskets;
/// <summary>
/// The eight currencies of the research document (section 4.1) in the market naming order: in a pair the currency that comes
/// first is the base. The one home of the currency and pair lists: the basket maths and the ECB crosses both read them here.
/// </summary>
public static class Currencies
{
public const string Eur = "EUR";
public const string Gbp = "GBP";
public const string Aud = "AUD";
public const string Nzd = "NZD";
public const string Usd = "USD";
public const string Cad = "CAD";
public const string Chf = "CHF";
public const string Jpy = "JPY";
private static readonly string[] All = [Eur, Gbp, Aud, Nzd, Usd, Cad, Chf, Jpy];
/// <summary>EUR, GBP, AUD, NZD, USD, CAD, CHF, JPY.</summary>
public static IReadOnlyList<string> Order { get; } = Array.AsReadOnly(All);
/// <summary>Position of a currency in <see cref="Order"/>; -1 when it is not one of the eight.</summary>
public static int IndexOf(string currency) => Array.IndexOf(All, currency);
}
/// <summary>A currency pair: the price is how many units of <see cref="Quote"/> buy one unit of <see cref="Base"/>.</summary>
public sealed record FxPair(string Base, string Quote)
{
/// <summary>The market name, base then quote: EURUSD.</summary>
public string Name => Base + Quote;
/// <summary>The pip: 0.01 when the quote is the yen, 0.0001 otherwise (document, appendix C).</summary>
public decimal Pip => Quote == Currencies.Jpy ? 0.01m : 0.0001m;
public override string ToString() => Name;
}
/// <summary>The 28 pairs of the eight currencies, in the order of the document's appendix A.</summary>
public static class FxPairs
{
/// <summary>Every pair whose base comes before its quote in <see cref="Currencies.Order"/>: 8 × 7 / 2 = 28.</summary>
public static IReadOnlyList<FxPair> All { get; } = Build();
private static readonly Dictionary<string, FxPair> ByName = All.ToDictionary(p => p.Name, StringComparer.Ordinal);
/// <summary>The pair with this market name (EURUSD), or null when it is not one of the 28.</summary>
public static FxPair? Find(string name) => ByName.GetValueOrDefault(name);
/// <summary>The pair with this market name; throws when it is not one of the 28.</summary>
public static FxPair Get(string name) => Find(name) ?? throw new ArgumentException($"{name} non è una delle 28 coppie.", nameof(name));
/// <summary>The pair of two currencies, whichever order they are given in; null when they are the same or unknown.</summary>
public static FxPair? Of(string one, string other)
{
var a = Currencies.IndexOf(one);
var b = Currencies.IndexOf(other);
if (a < 0 || b < 0 || a == b)
{
return null;
}
return a < b ? Find(one + other) : Find(other + one);
}
private static List<FxPair> Build()
{
var pairs = new List<FxPair>(28);
for (var i = 0; i < Currencies.Order.Count; i++)
{
for (var j = i + 1; j < Currencies.Order.Count; j++)
{
pairs.Add(new FxPair(Currencies.Order[i], Currencies.Order[j]));
}
}
return pairs;
}
}
+174
View File
@@ -0,0 +1,174 @@
namespace Anubis.Baskets;
/// <summary>The kinds of relation of section 4.1 (chain, ratio, disjoint) and the two of section 11 (statistical, single symbol).</summary>
public enum RelationKind
{
/// <summary>The common currency is the quote of one pair and the base of the other: the synthetic is the product.</summary>
Chain,
/// <summary>The common currency has the same role in both pairs: the synthetic is the ratio A / B.</summary>
Ratio,
/// <summary>No common currency: no synthetic, the sign comes from the correlation.</summary>
Disjoint,
/// <summary>Two instruments tied by a hedge ratio β from the regression of log prices.</summary>
Statistical,
/// <summary>One symbol on its own.</summary>
SingleSymbol,
}
/// <summary>
/// How two of the 28 pairs relate (section 4.1). <see cref="Cross"/> is the listed pair equivalent to the synthetic: for a
/// chain the product A × B, always a listed pair; for a ratio the quotient A / B, which may be the inverse of the listed pair
/// (<see cref="CrossInverted"/>). Kind, common currency and cross never depend on the order of the legs; only the
/// orientation of a ratio's quotient does.
/// </summary>
public sealed record PairRelation(FxPair A, FxPair B, RelationKind Kind, string? Common, FxPair? Cross, bool CrossInverted)
{
/// <summary>The sign s of the pip index (section 4.2); null when the couple has no sign and cannot be traded.</summary>
public int? Sign(double? correlation = null) => Relations.Sign(Kind, correlation);
}
/// <summary>A row of appendix B: leg A ends in the common currency, leg B starts with it, buying both buys the cross.</summary>
public sealed record ChainRow(int Row, FxPair A, FxPair B, FxPair Cross, bool Listed);
/// <summary>A two-leg spread as the document writes it (section 3.3), leg A first.</summary>
public sealed record DocumentedSpread(FxPair A, FxPair B);
/// <summary>
/// The relations among the 28 pairs (section 4.1, appendix B, appendix C): classification, the 378 couples, the 56 chains in
/// the document's order, the eight documented spreads (section 3.3) and the 14-pair list (section 4.9).
/// </summary>
public static class Relations
{
private static readonly int[] ListedRows = [3, 9, 17, 29, 30, 35];
/// <summary>The 378 unordered couples of the 28 pairs, each once, in appendix A order: 56 chains, 112 ratios, 210 disjoint.</summary>
public static IReadOnlyList<PairRelation> Couples { get; } = Array.AsReadOnly(BuildCouples());
/// <summary>
/// Appendix B: for each common currency c from GBP to CHF, every a before c and every b after c in the currency order,
/// A = a c, B = c b, cross = a b. Rows 3, 9, 17, 29, 30 and 35 are the ones the documented editions list.
/// </summary>
public static IReadOnlyList<ChainRow> AppendixB { get; } = Array.AsReadOnly(BuildAppendixB());
/// <summary>The eight spreads of section 3.3, in the document's leg order: six chains and two disjoint couples.</summary>
public static IReadOnlyList<DocumentedSpread> DocumentedSpreads { get; } = Array.AsReadOnly<DocumentedSpread>(
[
new(FxPairs.Get("EURUSD"), FxPairs.Get("USDCHF")),
new(FxPairs.Get("AUDUSD"), FxPairs.Get("USDCAD")),
new(FxPairs.Get("NZDUSD"), FxPairs.Get("EURNZD")),
new(FxPairs.Get("USDCAD"), FxPairs.Get("EURUSD")),
new(FxPairs.Get("EURAUD"), FxPairs.Get("AUDCAD")),
new(FxPairs.Get("GBPUSD"), FxPairs.Get("EURGBP")),
new(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF")),
new(FxPairs.Get("EURCHF"), FxPairs.Get("AUDCAD")),
]);
/// <summary>The 14-pair list (section 4.9): the twelve documented symbols plus EURCAD and AUDNZD, in appendix A order.</summary>
public static IReadOnlyList<FxPair> FourteenPairs { get; } = Array.AsReadOnly(
new[]
{
"EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD",
"AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF",
}.Select(FxPairs.Get).ToArray());
/// <summary>Classifies two different pairs; the result never depends on which one is given first, except for a ratio's orientation.</summary>
public static PairRelation Classify(FxPair a, FxPair b)
{
ArgumentNullException.ThrowIfNull(a);
ArgumentNullException.ThrowIfNull(b);
if (a == b)
{
throw new ArgumentException($"Una relazione vuole due coppie diverse, non {a.Name} due volte.", nameof(b));
}
var common = Shared(a, b);
if (common is null)
{
return new PairRelation(a, b, RelationKind.Disjoint, null, null, false);
}
// Chain: x/c × c/y = x/y. The listed pairs give x before c before y, so the cross is always listed.
if (a.Quote == common && b.Base == common)
{
return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(a.Base, b.Quote), false);
}
if (a.Base == common && b.Quote == common)
{
return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(b.Base, a.Quote), false);
}
// Ratio. Both quote c: (c per x) / (c per y) = y per x, the pair x/y. Both base c: (x per c) / (y per c) = x per y,
// the pair y/x. The listed pair may be the other way round.
var otherA = a.Base == common ? a.Quote : a.Base;
var otherB = b.Base == common ? b.Quote : b.Base;
var syntheticBase = a.Quote == common ? otherA : otherB;
var cross = FxPairs.Of(otherA, otherB)!;
return new PairRelation(a, b, RelationKind.Ratio, common, cross, cross.Base != syntheticBase);
}
/// <summary>
/// The sign s of the pip index X = A / pip(A) + s · B / pip(B) (section 4.2, appendix C): +1 for a chain, −1 for a ratio,
/// −sign(ρ) for a disjoint couple. A disjoint couple with ρ zero, unknown or not a number has no sign: null.
/// </summary>
public static int? Sign(RelationKind kind, double? correlation) => kind switch
{
RelationKind.Chain => 1,
RelationKind.Ratio => -1,
RelationKind.Disjoint => correlation is { } rho && rho != 0 && !double.IsNaN(rho) ? -Math.Sign(rho) : null,
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Il segno dell'indice in pip vale solo per catena, rapporto e disgiunta."),
};
private static string? Shared(FxPair a, FxPair b)
{
if (a.Base == b.Base || a.Base == b.Quote)
{
return a.Base;
}
return a.Quote == b.Base || a.Quote == b.Quote ? a.Quote : null;
}
private static PairRelation[] BuildCouples()
{
var pairs = FxPairs.All;
var couples = new List<PairRelation>(pairs.Count * (pairs.Count - 1) / 2);
for (var i = 0; i < pairs.Count; i++)
{
for (var j = i + 1; j < pairs.Count; j++)
{
couples.Add(Classify(pairs[i], pairs[j]));
}
}
return [.. couples];
}
private static ChainRow[] BuildAppendixB()
{
var order = Currencies.Order;
var rows = new List<ChainRow>(56);
for (var c = 1; c < order.Count - 1; c++)
{
for (var a = 0; a < c; a++)
{
for (var b = c + 1; b < order.Count; b++)
{
var row = rows.Count + 1;
rows.Add(new ChainRow(
row,
FxPairs.Get(order[a] + order[c]),
FxPairs.Get(order[c] + order[b]),
FxPairs.Get(order[a] + order[b]),
ListedRows.Contains(row)));
}
}
}
return [.. rows];
}
}
+92
View File
@@ -0,0 +1,92 @@
using Anubis.Data;
namespace Anubis.Baskets;
/// <summary>
/// A window of the day on a wall clock (section 4.7), half-open: <see cref="From"/> is inside, <see cref="To"/> is not. When
/// <see cref="To"/> comes before <see cref="From"/> the window crosses midnight.
/// </summary>
public sealed record DailyWindow(TimeOnly From, TimeOnly To)
{
public bool Contains(TimeOnly time) => From <= To ? time >= From && time < To : time >= From || time < To;
}
/// <summary>
/// The server clock of the research document (section 4.7 and appendix C): New York time plus seven hours, so it follows
/// the United States' daylight saving only (UTC+2 in winter, UTC+3 in summer). The server day changes at 17:00 New York.
/// Every window is half-open: the weekend rule (no new entries from Friday 16:00 to Monday 02:00 server time), the hourly
/// window (10:00 to 20:00 server time, when it is on) and the daily venue pause (16:55 to 18:10 New York time).
/// </summary>
public static class ServerClock
{
/// <summary>How far the server clock is ahead of New York.</summary>
public static readonly TimeSpan AheadOfNewYork = TimeSpan.FromHours(7);
/// <summary>First server time of the weekend rule, on Friday.</summary>
public static readonly TimeOnly WeekendFrom = new(16, 0);
/// <summary>First server time after the weekend rule, on Monday.</summary>
public static readonly TimeOnly WeekendTo = new(2, 0);
/// <summary>The hourly window, in server time.</summary>
public static DailyWindow Session { get; } = new(new TimeOnly(10, 0), new TimeOnly(20, 0));
/// <summary>The daily venue pause, in New York time: no entries and no averaging inside it.</summary>
public static DailyWindow DailyPauseNewYork { get; } = new(new TimeOnly(16, 55), new TimeOnly(18, 10));
/// <summary>The server wall clock at a moment.</summary>
public static DateTime ToServer(DateTimeOffset moment) => NewYork(moment) + AheadOfNewYork;
/// <summary>The moment a server wall-clock time names. In the hour New York's clock goes back, standard time wins.</summary>
public static DateTimeOffset FromServer(DateTime server)
{
var newYork = DateTime.SpecifyKind(server - AheadOfNewYork, DateTimeKind.Unspecified);
return new DateTimeOffset(newYork, Zones.NewYork.GetUtcOffset(newYork)).ToUniversalTime();
}
/// <summary>How far the server clock is ahead of UTC at a moment: two hours in winter, three in summer.</summary>
public static TimeSpan OffsetFromUtc(DateTimeOffset moment) => ToServer(moment) - moment.UtcDateTime;
/// <summary>The server day of a moment: the date of the server clock.</summary>
public static DateOnly Day(DateTimeOffset moment) => DateOnly.FromDateTime(ToServer(moment));
/// <summary>The moment of a server time on a server day.</summary>
public static DateTimeOffset At(DateOnly day, TimeOnly time) => FromServer(day.ToDateTime(time));
/// <summary>Server midnight: 17:00 New York of the day before.</summary>
public static DateTimeOffset DayStart(DateOnly day) => At(day, TimeOnly.MinValue);
/// <summary>The start of the server day after the one of <paramref name="moment"/>: when entries resume after the equity stop.</summary>
public static DateTimeOffset NextDayStart(DateTimeOffset moment) => DayStart(Day(moment).AddDays(1));
/// <summary>True from Friday 16:00 to Monday 02:00 server time (Monday 02:00 excluded).</summary>
public static bool InWeekend(DateTimeOffset moment)
{
var server = ToServer(moment);
var time = TimeOnly.FromDateTime(server);
return server.DayOfWeek switch
{
DayOfWeek.Friday => time >= WeekendFrom,
DayOfWeek.Saturday or DayOfWeek.Sunday => true,
DayOfWeek.Monday => time < WeekendTo,
_ => false,
};
}
/// <summary>True inside the hourly window, in server time; <paramref name="window"/> replaces 10:00–20:00.</summary>
public static bool InSession(DateTimeOffset moment, DailyWindow? window = null) =>
(window ?? Session).Contains(TimeOnly.FromDateTime(ToServer(moment)));
/// <summary>True inside the daily venue pause, in New York time; <paramref name="pause"/> replaces 16:55–18:10.</summary>
public static bool InDailyPause(DateTimeOffset moment, DailyWindow? pause = null) =>
(pause ?? DailyPauseNewYork).Contains(TimeOnly.FromDateTime(NewYork(moment)));
/// <summary>
/// Whether the clock allows a new entry: outside the weekend rule and the daily pause, and inside the hourly window when
/// it is on.
/// </summary>
public static bool EntriesAllowed(DateTimeOffset moment, bool sessionOn) =>
!InWeekend(moment) && !InDailyPause(moment) && (!sessionOn || InSession(moment));
private static DateTime NewYork(DateTimeOffset moment) => TimeZoneInfo.ConvertTime(moment, Zones.NewYork).DateTime;
}
+153
View File
@@ -0,0 +1,153 @@
namespace Anubis.Baskets;
/// <summary>The state of a pair on the panel (section 4.9): ferma, in osservazione, pronta, aperta.</summary>
public enum PairState
{
/// <summary>Ferma: |z| below the watch threshold.</summary>
Idle,
/// <summary>In osservazione: |z| at or above the watch threshold.</summary>
Watch,
/// <summary>Pronta: |z| at or above the entry threshold, but a gate blocks the entry.</summary>
Armed,
/// <summary>Aperta: every gate passes, or a unit is already open.</summary>
Open,
}
/// <summary>The states of a pair, the entry signal and the closing of the spread (sections 4.3 and 4.9).</summary>
public static class PairStates
{
/// <summary>|z| from which a pair is watched.</summary>
public const double DefaultWatchZ = 1.5;
/// <summary>|z| at or below which the spread counts as closed.</summary>
public const double DefaultSpreadClosedZ = 0.5;
/// <summary>
/// The state at a closed bar: <see cref="PairState.Open"/> with a unit open or with |z| ≥ entry and every gate passing;
/// <see cref="PairState.Armed"/> with |z| ≥ entry and a gate blocking; <see cref="PairState.Watch"/> with |z| ≥ watch;
/// <see cref="PairState.Idle"/> otherwise, and without a z-score.
/// </summary>
public static PairState Of(double? z, double entryZ, bool gatesPass, bool hasOpenUnit = false, double watchZ = DefaultWatchZ)
{
if (hasOpenUnit)
{
return PairState.Open;
}
if (z is not { } value || double.IsNaN(value))
{
return PairState.Idle;
}
var size = Math.Abs(value);
if (size >= entryZ)
{
return gatesPass ? PairState.Open : PairState.Armed;
}
return size >= watchZ ? PairState.Watch : PairState.Idle;
}
/// <summary>The entry signal: buy the spread at z ≤ −entry, sell it at z ≥ +entry, nothing otherwise.</summary>
public static Direction? Signal(double? z, double entryZ) => z switch
{
{ } value when value <= -entryZ => Direction.Buy,
{ } value when value >= entryZ => Direction.Sell,
_ => null,
};
/// <summary>Whether the spread has closed: |z| ≤ <paramref name="closedZ"/>.</summary>
public static bool SpreadClosed(double? z, double closedZ = DefaultSpreadClosedZ) => z is { } value && Math.Abs(value) <= closedZ;
}
/// <summary>
/// One of the four styles of section 4.7: entry threshold, spreads open at once, averagings; the growth variant (1.3) allows
/// <see cref="MaxAveragingsWithGrowth"/>.
/// </summary>
public sealed record TradingStyle(string Name, double EntryZ, int MaxOpenSpreads, int MaxAveragings, int MaxAveragingsWithGrowth);
/// <summary>The four styles of section 4.7; Moderato is the default.</summary>
public static class TradingStyles
{
public static TradingStyle HedgeFund { get; } = new("HedgeFund", 3.0, 1, 2, 2);
public static TradingStyle Conservativo { get; } = new("Conservativo", 2.5, 2, 3, 3);
public static TradingStyle Moderato { get; } = new("Moderato", 2.0, 2, 3, 3);
public static TradingStyle Aggressivo { get; } = new("Aggressivo", 1.5, 3, 3, 4);
public static TradingStyle Default => Moderato;
public static IReadOnlyList<TradingStyle> All { get; } = Array.AsReadOnly(new[] { HedgeFund, Conservativo, Moderato, Aggressivo });
/// <summary>The style with this name, or null.</summary>
public static TradingStyle? Find(string name) => All.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.Ordinal));
}
/// <summary>
/// A risk profile of the basket logic (sections 5 and 7.1, appendix D). Fractions are of the balance or of equity:
/// 0.09 is 9%. A null stop is a stop that does not exist; a null exposure cap means the cap is only logged.
/// </summary>
/// <param name="Name">Fedele or Prudente.</param>
/// <param name="StopZ">Basket stop when |z| reaches this value.</param>
/// <param name="StopLoss">Basket stop when its loss reaches this fraction of equity.</param>
/// <param name="StopOnBrokenRelation">Basket stop when the relation breaks (the correlation loses its expected sign).</param>
/// <param name="StopAfterBars">Basket stop after this many bars open.</param>
/// <param name="EquityStop">Everything closes when open loss ÷ balance reaches this fraction.</param>
/// <param name="ResumeAtNextServerDay">After the equity stop entries resume at the next server day.</param>
/// <param name="CostGate">The three-costs rule blocks entries (otherwise it is only logged).</param>
/// <param name="MaxCurrencyExposure">Net exposure per currency, in multiples of one entry's exposure.</param>
/// <param name="OffRealAccountsOnly">Allowed only in backtest, simulator and Demo.</param>
public sealed record BasketProfile(
string Name,
double? StopZ,
decimal? StopLoss,
bool StopOnBrokenRelation,
int? StopAfterBars,
decimal EquityStop,
bool ResumeAtNextServerDay,
bool CostGate,
decimal? MaxCurrencyExposure,
bool OffRealAccountsOnly)
{
/// <summary>Whether any basket stop is on.</summary>
public bool HasBasketStops() => StopZ is not null || StopLoss is not null || StopOnBrokenRelation || StopAfterBars is not null;
}
/// <summary>
/// The two profiles: Fedele, the document as written (no basket stop, equity stop at 9% with resume at the next server day,
/// only off real accounts); Prudente, the same logic with the basket stops (z 3.5, loss 1% — the document's 1.5% reduced by
/// SPEC 9.2 — broken relation, 96 bars), the cost gate and the currency exposure cap 2.0.
/// </summary>
public static class BasketProfiles
{
public static BasketProfile Fedele { get; } = new(
"Fedele",
StopZ: null,
StopLoss: null,
StopOnBrokenRelation: false,
StopAfterBars: null,
EquityStop: 0.09m,
ResumeAtNextServerDay: true,
CostGate: false,
MaxCurrencyExposure: null,
OffRealAccountsOnly: true);
public static BasketProfile Prudente { get; } = new(
"Prudente",
StopZ: 3.5,
StopLoss: 0.01m,
StopOnBrokenRelation: true,
StopAfterBars: 96,
EquityStop: 0.09m,
ResumeAtNextServerDay: true,
CostGate: true,
MaxCurrencyExposure: 2.0m,
OffRealAccountsOnly: false);
public static IReadOnlyList<BasketProfile> All { get; } = Array.AsReadOnly(new[] { Fedele, Prudente });
}
+89
View File
@@ -0,0 +1,89 @@
namespace Anubis.Data;
/// <summary>
/// Builds longer bars from shorter ones (Phase 12, ADR 0028), as a pure function in <see cref="decimal"/>: no digit is lost.
/// A bucket is aligned on a multiple of its length counted from the Unix epoch in UTC: 15 minutes, 30 minutes and one hour
/// then also fall on the New York hours and on the server clock (New York + 7 hours); 4 and 8 hours fall on 00, 04, 08 …
/// UTC like the Binance archives. Open is the first bar's, high the highest, low the lowest, close the last bar's, volume
/// the sum; quote volume and trades are summed only when every bar of the bucket has them. A bucket without bars gives no
/// bar: nothing is ever carried forward.
/// </summary>
public static class BarAggregator
{
/// <summary>The start of the bucket of <paramref name="length"/> that holds <paramref name="moment"/>, in UTC.</summary>
public static DateTimeOffset BucketOf(DateTimeOffset moment, TimeSpan length)
{
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(length, TimeSpan.Zero);
var ticks = (moment.UtcTicks - DateTimeOffset.UnixEpoch.UtcTicks) / length.Ticks * length.Ticks;
if (moment.UtcTicks < DateTimeOffset.UnixEpoch.UtcTicks && (moment.UtcTicks - DateTimeOffset.UnixEpoch.UtcTicks) % length.Ticks != 0)
{
ticks -= length.Ticks; // Before 1970 the division rounds towards zero, not down.
}
return new DateTimeOffset(DateTimeOffset.UnixEpoch.UtcTicks + ticks, TimeSpan.Zero);
}
/// <summary>
/// The bars of <paramref name="timeframe"/> built from <paramref name="bars"/> (usually one-minute bars), oldest first.
/// Every input bar must open on a whole UTC minute and appear once. With <paramref name="completeBefore"/>, a bucket that
/// ends after it is left out: it has not closed yet, and an unfinished bar must never reach the data.
/// </summary>
public static IReadOnlyList<ResearchBar> Aggregate(IEnumerable<ResearchBar> bars, string timeframe, DateTimeOffset? completeBefore = null)
{
ArgumentNullException.ThrowIfNull(bars);
var length = Timeframes.Length(timeframe);
var ordered = bars.OrderBy(b => b.OpensAt).ToList();
for (var i = 0; i < ordered.Count; i++)
{
if (ordered[i].OpensAt.UtcTicks % TimeSpan.TicksPerMinute != 0)
{
throw new ArgumentException($"La barra delle {ordered[i].OpensAt:O} non comincia a un minuto intero.", nameof(bars));
}
if (i > 0 && ordered[i].OpensAt == ordered[i - 1].OpensAt)
{
throw new ArgumentException($"Due barre per lo stesso momento: {ordered[i].OpensAt:O}.", nameof(bars));
}
}
var result = new List<ResearchBar>();
var start = 0;
while (start < ordered.Count)
{
var bucket = BucketOf(ordered[start].OpensAt, length);
var end = start;
while (end < ordered.Count && BucketOf(ordered[end].OpensAt, length) == bucket)
{
end++;
}
if (completeBefore is not { } cut || bucket + length <= cut)
{
result.Add(Merge(bucket, ordered, start, end));
}
start = end;
}
return result;
}
private static ResearchBar Merge(DateTimeOffset bucket, List<ResearchBar> bars, int start, int end)
{
var first = bars[start];
decimal high = first.High, low = first.Low, volume = 0m;
decimal? quoteVolume = 0m;
long? trades = 0;
for (var i = start; i < end; i++)
{
var bar = bars[i];
high = Math.Max(high, bar.High);
low = Math.Min(low, bar.Low);
volume += bar.Volume;
quoteVolume = quoteVolume is { } q && bar.QuoteVolume is { } bq ? q + bq : null;
trades = trades is { } t && bar.Trades is { } bt ? t + bt : null;
}
return new ResearchBar(bucket, first.Open, high, low, bars[end - 1].Close, volume) { QuoteVolume = quoteVolume, Trades = trades };
}
}
+154
View File
@@ -0,0 +1,154 @@
using Anubis.Core;
namespace Anubis.Data;
/// <summary>
/// When a market has bars (Phase 12, ADR 0028): a bar of a given length that opens at a given moment is "open" when the
/// market trades during at least part of it, so a bar that straddles the opening or the close holds traded minutes and
/// belongs to the calendar.
/// </summary>
public interface IBarCalendar
{
/// <summary>Short name, part of the data fingerprint: <c>24x7</c>, <c>24x5</c>, <c>exchange</c>.</summary>
string Name { get; }
bool IsOpen(DateTimeOffset opensAt, TimeSpan length);
/// <summary>Bars of <paramref name="length"/> in a year, to annualise.</summary>
int PeriodsPerYear(TimeSpan length);
}
/// <summary>The three calendars of the research bars: crypto every day, currencies five days a week, exchanges by session.</summary>
public static class BarCalendars
{
/// <summary>Crypto: every moment of every day.</summary>
public static IBarCalendar Always { get; } = new AlwaysOpen();
/// <summary>
/// Currencies, 24×5: open from Sunday 17:00 to Friday 17:00 New York time, following US daylight saving only (Monday
/// 00:00 to Saturday 00:00 of the server clock). Daily bars, which open at 00:00 UTC, count Monday to Friday: the days
/// the ECB publishes; Sunday evening belongs to Monday's trading.
/// </summary>
public static IBarCalendar Fx { get; } = new FxWeek();
/// <summary>An exchange: the bars that overlap one of its sessions (early closes included).</summary>
public static IBarCalendar Exchange(IEnumerable<MarketSession> sessions) => new ExchangeSessions(sessions);
/// <summary>The opening moments of the bars of <paramref name="length"/> in [from, to) when the calendar is open, aligned as <see cref="BarAggregator.BucketOf"/>.</summary>
public static IEnumerable<DateTimeOffset> Moments(this IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to, TimeSpan length)
{
ArgumentNullException.ThrowIfNull(calendar);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(length, TimeSpan.Zero);
return Walk(calendar, from, to, length);
static IEnumerable<DateTimeOffset> Walk(IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to, TimeSpan length)
{
var t = BarAggregator.BucketOf(from, length);
if (t < from)
{
t += length;
}
for (; t < to; t += length)
{
if (calendar.IsOpen(t, length))
{
yield return t;
}
}
}
}
private sealed class AlwaysOpen : IBarCalendar
{
public string Name => "24x7";
public bool IsOpen(DateTimeOffset opensAt, TimeSpan length) => true;
public int PeriodsPerYear(TimeSpan length) => (int)(TimeSpan.FromDays(365).Ticks / length.Ticks);
}
private sealed class FxWeek : IBarCalendar
{
private static readonly TimeSpan Five = TimeSpan.FromHours(17);
// A plain week of January 2024, far from any change of the clocks.
private static readonly DateTimeOffset ReferenceWeek = new(2024, 1, 7, 0, 0, 0, TimeSpan.Zero);
public string Name => "24x5";
public bool IsOpen(DateTimeOffset opensAt, TimeSpan length)
{
if (length >= TimeSpan.FromDays(1))
{
return opensAt.UtcDateTime.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday);
}
var local = TimeZoneInfo.ConvertTime(opensAt, Zones.NewYork);
var closedUntil = local.DayOfWeek switch
{
DayOfWeek.Friday when local.TimeOfDay >= Five => 2,
DayOfWeek.Saturday => 1,
DayOfWeek.Sunday when local.TimeOfDay < Five => 0,
_ => -1,
};
if (closedUntil < 0)
{
return true;
}
var reopens = Zones.At(DateOnly.FromDateTime(local.Date).AddDays(closedUntil), new TimeOnly(17, 0), Zones.NewYork);
return opensAt + length > reopens;
}
public int PeriodsPerYear(TimeSpan length) => 52 * this.Moments(ReferenceWeek, ReferenceWeek.AddDays(7), length).Count();
}
private sealed class ExchangeSessions : IBarCalendar
{
private readonly MarketSession[] _sessions;
public ExchangeSessions(IEnumerable<MarketSession> sessions)
{
ArgumentNullException.ThrowIfNull(sessions);
_sessions = [.. sessions.OrderBy(s => s.CloseUtc)];
}
public string Name => "exchange";
public bool IsOpen(DateTimeOffset opensAt, TimeSpan length)
{
// The first session that closes after the bar opens: the bar is open when that session opens before it ends.
int lo = 0, hi = _sessions.Length;
while (lo < hi)
{
var mid = (lo + hi) / 2;
if (_sessions[mid].CloseUtc <= opensAt)
{
lo = mid + 1;
}
else
{
hi = mid;
}
}
return lo < _sessions.Length && _sessions[lo].OpenUtc < opensAt + length;
}
/// <summary>About 252 sessions a year, each with the average number of bars of the sessions given (a regular one when none is).</summary>
public int PeriodsPerYear(TimeSpan length)
{
static int Bars(DateTimeOffset open, DateTimeOffset close, TimeSpan length) =>
(int)((BarAggregator.BucketOf(close.AddTicks(-1), length) - BarAggregator.BucketOf(open, length)).Ticks / length.Ticks) + 1;
if (_sessions.Length == 0)
{
var regular = new DateTimeOffset(2024, 1, 2, 14, 30, 0, TimeSpan.Zero);
return 252 * Bars(regular, regular.AddMinutes(390), length);
}
return 252 * (int)Math.Round(_sessions.Average(s => Bars(s.OpenUtc, s.CloseUtc, length)), MidpointRounding.AwayFromZero);
}
}
}
+282
View File
@@ -0,0 +1,282 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Anubis.Data;
/// <summary>The prices of one series on the common clock of a <see cref="BarDataset"/>: NaN where it has no bar.</summary>
public sealed class BarColumns
{
private readonly double[] _open, _high, _low, _close, _volume;
private BarColumns(double[] open, double[] high, double[] low, double[] close, double[] volume)
{
(_open, _high, _low, _close, _volume) = (open, high, low, close, volume);
}
public IReadOnlyList<double> Open => _open;
public IReadOnlyList<double> High => _high;
public IReadOnlyList<double> Low => _low;
public IReadOnlyList<double> Close => _close;
public IReadOnlyList<double> Volume => _volume;
/// <summary>Whether the series has a bar at the position <paramref name="t"/> of the clock.</summary>
public bool Has(int t) => !double.IsNaN(_close[t]);
internal static BarColumns Empty(int length)
{
static double[] Nan(int n)
{
var values = new double[n];
Array.Fill(values, double.NaN);
return values;
}
return new BarColumns(Nan(length), Nan(length), Nan(length), Nan(length), Nan(length));
}
internal void Set(int t, ResearchBar bar) =>
(_open[t], _high[t], _low[t], _close[t], _volume[t]) = ((double)bar.Open, (double)bar.High, (double)bar.Low, (double)bar.Close, (double)bar.Volume);
internal BarColumns Slice(int start, int count) => new(
_open[start..(start + count)], _high[start..(start + count)], _low[start..(start + count)], _close[start..(start + count)], _volume[start..(start + count)]);
internal void Write(StringBuilder text, IReadOnlyList<DateTimeOffset> clock)
{
for (var t = 0; t < clock.Count; t++)
{
if (Has(t))
{
text.Append(CultureInfo.InvariantCulture,
$"{clock[t].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'},{_open[t]:R},{_high[t]:R},{_low[t]:R},{_close[t]:R},{_volume[t]:R}\n");
}
}
}
}
/// <summary>
/// Research bars shorter than a day (or daily) of several series on one common clock (Phase 12, ADR 0028): every moment
/// of the calendar in the window, in columns of <see cref="double"/> (analysis data, SPEC 5.4). A series without a bar at
/// a moment has NaN there: nothing is ever filled. Bars outside the calendar are left out and counted in
/// <see cref="Dropped"/>. Built once and never changed, like <c>BacktestDataset</c>.
/// </summary>
public sealed class BarDataset
{
private readonly Dictionary<string, BarColumns> _bars;
private readonly Dictionary<string, BarColumns> _asks;
private readonly DateTimeOffset[] _clock;
private BarDataset(string timeframe, IBarCalendar calendar, DateTimeOffset[] clock, Dictionary<string, BarColumns> bars, Dictionary<string, BarColumns> asks, int dropped)
{
Timeframe = timeframe;
Length = Timeframes.Length(timeframe);
Calendar = calendar;
_clock = clock;
_bars = bars;
_asks = asks;
Symbols = [.. bars.Keys.Order(StringComparer.Ordinal)];
Dropped = dropped;
}
public string Timeframe { get; }
public TimeSpan Length { get; }
public IBarCalendar Calendar { get; }
/// <summary>The series, in ordinal order.</summary>
public IReadOnlyList<string> Symbols { get; }
/// <summary>The opening moments of the bars, oldest first, in UTC.</summary>
public IReadOnlyList<DateTimeOffset> Clock => _clock;
/// <summary>Bars inside the window but outside the calendar, or not on its grid: left out.</summary>
public int Dropped { get; }
public int PeriodsPerYear => Calendar.PeriodsPerYear(Length);
/// <summary>The prices of a series (the bid when the source gives both sides).</summary>
public BarColumns Bars(string symbol) =>
_bars.TryGetValue(symbol, out var columns) ? columns : throw new KeyNotFoundException($"{symbol} non è nei dati.");
/// <summary>The ask prices of a series, or null when the source gives only one side.</summary>
public BarColumns? Ask(string symbol) => _asks.GetValueOrDefault(symbol);
public bool Has(string symbol, int t) => Bars(symbol).Has(t);
/// <summary>The position of a moment on the clock, or -1.</summary>
public int IndexOf(DateTimeOffset opensAt)
{
var index = Array.BinarySearch(_clock, opensAt);
return index >= 0 ? index : -1;
}
/// <summary>When the bar at position <paramref name="t"/> closes: only from then on is it known.</summary>
public DateTimeOffset ClosesAt(int t) => _clock[t] + Length;
/// <summary>
/// The data known at <paramref name="moment"/>: only the bars that have closed by then. A bar still open is never
/// shown, not even in part.
/// </summary>
public BarDataset Through(DateTimeOffset moment)
{
var count = 0;
while (count < _clock.Length && _clock[count] + Length <= moment)
{
count++;
}
return Slice(0, count);
}
/// <summary>The bars that open in [from, to).</summary>
public BarDataset Between(DateTimeOffset from, DateTimeOffset to)
{
var start = 0;
while (start < _clock.Length && _clock[start] < from)
{
start++;
}
var end = start;
while (end < _clock.Length && _clock[end] < to)
{
end++;
}
return Slice(start, end - start);
}
/// <summary>
/// A SHA-256 of the timeframe, the calendar, the clock and every bar: two reports with the same fingerprint and the
/// same plan were computed on exactly the same data.
/// </summary>
public string Fingerprint()
{
var text = new StringBuilder();
text.Append(CultureInfo.InvariantCulture, $"{Timeframe}|{Calendar.Name}|{_clock.Length}");
if (_clock.Length > 0)
{
text.Append(CultureInfo.InvariantCulture, $"|{_clock[0].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}|{_clock[^1].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}");
}
text.Append('\n');
foreach (var symbol in Symbols)
{
text.Append(symbol).Append('\n');
_bars[symbol].Write(text, _clock);
if (_asks.TryGetValue(symbol, out var ask))
{
text.Append("ask\n");
ask.Write(text, _clock);
}
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
/// <summary>
/// The dataset of the bars given, on the moments of <paramref name="calendar"/> in [from, to). <paramref name="asks"/>
/// holds the ask side of the series that have one.
/// </summary>
public static BarDataset Build(string timeframe, IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to,
IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> bars, IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>>? asks = null)
{
ArgumentNullException.ThrowIfNull(calendar);
ArgumentNullException.ThrowIfNull(bars);
var length = Timeframes.Length(timeframe);
var clock = calendar.Moments(from, to, length).ToArray();
var index = new Dictionary<DateTimeOffset, int>(clock.Length);
for (var t = 0; t < clock.Length; t++)
{
index[clock[t]] = t;
}
var dropped = 0;
Dictionary<string, BarColumns> Columns(IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> series)
{
var columns = new Dictionary<string, BarColumns>(StringComparer.Ordinal);
foreach (var (symbol, list) in series)
{
var column = BarColumns.Empty(clock.Length);
foreach (var bar in list.Where(b => b.OpensAt >= from && b.OpensAt < to))
{
if (index.TryGetValue(bar.OpensAt, out var t))
{
column.Set(t, bar);
}
else
{
dropped++;
}
}
columns[symbol] = column;
}
return columns;
}
var bidColumns = Columns(bars);
var askColumns = asks is null ? new Dictionary<string, BarColumns>(StringComparer.Ordinal) : Columns(asks);
var stray = askColumns.Keys.FirstOrDefault(s => !bidColumns.ContainsKey(s));
if (stray is not null)
{
throw new ArgumentException($"{stray} ha i prezzi lettera ma non quelli denaro.", nameof(asks));
}
return new BarDataset(timeframe, calendar, clock, bidColumns, askColumns, dropped);
}
/// <summary>The series <paramref name="symbols"/> of a venue from the research history, as they are stored.</summary>
public static async Task<BarDataset> LoadAsync(ResearchStore store, string venue, IReadOnlyList<string> symbols, string timeframe, IBarCalendar calendar,
DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(symbols);
var bars = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
foreach (var symbol in symbols)
{
bars[symbol] = await store.ReadAsync(venue, symbol, timeframe, from, to, cancellationToken).ToListAsync(cancellationToken).ConfigureAwait(false);
}
return Build(timeframe, calendar, from, to, bars);
}
/// <summary>
/// Currency pairs of a venue on the 24×5 calendar, from the series written by <c>anubis data fx</c>: the bid of
/// <c>EURUSD-BID</c> and, when the venue has it, the ask of <c>EURUSD-ASK</c>, both under the name <c>EURUSD</c>.
/// </summary>
public static async Task<BarDataset> LoadQuotesAsync(ResearchStore store, string venue, IReadOnlyList<string> pairs, string timeframe,
DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(pairs);
var bids = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var asks = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
foreach (var pair in pairs)
{
bids[pair] = await store.ReadAsync(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Bid), timeframe, from, to, cancellationToken)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (store.Years(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Ask), timeframe).Count > 0)
{
asks[pair] = await store.ReadAsync(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Ask), timeframe, from, to, cancellationToken)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
}
return Build(timeframe, BarCalendars.Fx, from, to, bids, asks);
}
private BarDataset Slice(int start, int count) => new(
Timeframe,
Calendar,
_clock[start..(start + count)],
_bars.ToDictionary(p => p.Key, p => p.Value.Slice(start, count), StringComparer.Ordinal),
_asks.ToDictionary(p => p.Key, p => p.Value.Slice(start, count), StringComparer.Ordinal),
Dropped);
}
+60
View File
@@ -0,0 +1,60 @@
using Anubis.Baskets;
namespace Anubis.Data;
/// <summary>
/// The 28 pairs of the eight currencies, day by day since 1999, from the ECB reference rates (Phase 12, ADR 0028). The ECB
/// gives how many units of each currency buy one euro: with r(EUR) = 1, the pair BQ is r(Q) / r(B), rounded to 10
/// decimals (to even). A pair whose rate is missing on a day has no bar that day; the others are still built. Each bar
/// opens at 00:00 UTC of the day with open = high = low = close and volume 0, venue "ecb", timeframe "1d".
/// The rates of day d are fixed at about 16:00 CET of d (the same rule as <c>EuroHistory</c>): a decision at the close
/// of d may use them, and <see cref="BarDataset.Through"/> shows the bar of d only once the day is over.
/// </summary>
public static class EcbCrosses
{
public const string Venue = Ecb.Source;
public const int Decimals = 10;
/// <summary>The seven rates the ECB publishes against the euro for the other currencies: from the shared list.</summary>
public static IReadOnlyList<string> Rates { get; } = [.. Currencies.Order.Where(c => c != Currencies.Eur)];
/// <summary>The bars of the 28 pairs in the order of <see cref="FxPairs.All"/>, each oldest first (empty when no day has both rates).</summary>
public static IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> Build(IEnumerable<FxRate> rates)
{
ArgumentNullException.ThrowIfNull(rates);
var byDay = new SortedDictionary<DateOnly, Dictionary<string, decimal>>();
foreach (var rate in rates.Where(r => r.Base == Currencies.Eur && Rates.Contains(r.Quote)))
{
if (!byDay.TryGetValue(rate.Date, out var day))
{
byDay[rate.Date] = day = new Dictionary<string, decimal>(StringComparer.Ordinal) { [Currencies.Eur] = 1m };
}
if (day.TryGetValue(rate.Quote, out var known) && known != rate.Rate)
{
throw new ArgumentException($"BCE: due cambi diversi per {rate.Quote} il {rate.Date:yyyy-MM-dd}.", nameof(rates));
}
day[rate.Quote] = rate.Rate;
}
var result = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
foreach (var pair in FxPairs.All)
{
var bars = new List<ResearchBar>();
foreach (var (date, day) in byDay)
{
if (day.TryGetValue(pair.Base, out var b) && day.TryGetValue(pair.Quote, out var q) && b > 0)
{
var value = Math.Round(q / b, Decimals, MidpointRounding.ToEven);
bars.Add(new ResearchBar(QualityChecks.Midnight(date), value, value, value, value, 0m));
}
}
result[pair.Name] = bars;
}
return result;
}
}
+44
View File
@@ -4,6 +4,7 @@ using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Anubis.Brokers;
namespace Anubis.Data;
@@ -68,6 +69,49 @@ public static class Ecb
using var reader = new StreamReader(entry.Open());
return reader.ReadToEnd();
}
/// <summary>The name of the cached history zip, next to the research data.</summary>
public const string HistoryFile = "ecb-eurofxref-hist.zip";
public static string HistoryPath(string researchRoot) => Path.Combine(researchRoot, HistoryFile);
/// <summary>
/// The full ECB history of the <paramref name="currencies"/>, kept in the research folder so an offline run uses the
/// same rates: downloaded again on every run, and with <paramref name="offline"/> only when the zip is missing. Shared by
/// <c>anubis backtest base</c> and <c>anubis data ecb</c>.
/// </summary>
public static async Task<IReadOnlyList<FxRate>> LoadHistoryAsync(ApiHttp http, string researchRoot, bool offline, IReadOnlyCollection<string> currencies,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(http);
var path = HistoryPath(researchRoot);
if (!offline || !File.Exists(path))
{
var zip = await http.GetBytesAsync(History, null, null, cancellationToken).ConfigureAwait(false)
?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true);
// A body that is not the history (a maintenance page, a cut download) must not replace the good copy: it is
// checked first, then written beside the cache and moved over it in one step.
_ = HistoryCsv(zip, "scaricato");
Directory.CreateDirectory(researchRoot);
var partial = path + ".tmp";
await File.WriteAllBytesAsync(partial, zip, cancellationToken).ConfigureAwait(false);
File.Move(partial, path, overwrite: true);
}
return ParseHistoryCsv(HistoryCsv(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false), "già scaricato"), currencies);
}
private static string HistoryCsv(byte[] zip, string which)
{
try
{
return ExtractHistoryCsv(zip);
}
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException)
{
throw new MarketDataException($"BCE: il file {which} non è lo storico dei cambi (un archivio zip con un CSV).", retryable: true, ex);
}
}
}
/// <summary>The weekly economic calendar of Forex Factory (faireconomy.media). It has no actual values.</summary>
+179
View File
@@ -0,0 +1,179 @@
using System.Text.RegularExpressions;
using Anubis.Baskets;
namespace Anubis.Data;
/// <summary>A one-minute FX file recognised by <see cref="FxMinuteFiles.Detect"/>: its format, pair, side and the mapping that reads it.</summary>
public sealed record FxMinuteFile(string Format, string Pair, string Side, CsvMapping Mapping)
{
/// <summary>The venue of the research history: the format's name.</summary>
public string Venue => Format;
/// <summary>The series name: the pair and its side, such as EURUSD-BID.</summary>
public string Series => FxMinuteFiles.Series(Pair, Side);
}
/// <summary>
/// The two one-minute FX formats the research document names (Phase 12, ADR 0028). The layouts come from general
/// knowledge, not from a file seen: the test fixtures are constructed samples, to check on the first real file.
/// <list type="bullet">
/// <item>Dukascopy: header <c>Gmt time,Open,High,Low,Close,Volume</c>, times <c>dd.MM.yyyy HH:mm:ss.fff</c> in UTC, one file
/// per side with <c>_BID_</c> or <c>_ASK_</c> in its name.</item>
/// <item>HistData generic ASCII M1: no header, <c>;</c>, times <c>yyyyMMdd HHmmss</c> in New York winter time all year
/// (UTC−5), bid only; the pair is in the name <c>DAT_ASCII_EURUSD_M1_2024.csv</c>.</item>
/// </list>
/// Anything else is refused with a message in Italian.
/// </summary>
public static partial class FxMinuteFiles
{
public const string Dukascopy = "dukascopy";
public const string HistData = "histdata";
public const string Bid = "BID";
public const string Ask = "ASK";
public const string Unknown =
"Formato non riconosciuto. anubis data fx legge solo i file a un minuto di Dukascopy (intestazione «Gmt time,Open,High,Low,Close,Volume», " +
"un file per il denaro e uno per la lettera) e di HistData in formato ASCII generico (righe «AAAAMMGG HHMMSS;apertura;massimo;minimo;chiusura;volume»).";
public static string Series(string pair, string side) => pair + "-" + side;
/// <summary>
/// Recognises a file from its first non-empty line and its name; <paramref name="symbol"/> (from <c>--symbol</c>) wins
/// over the pair in the name. Throws <see cref="FormatException"/> with the reason in Italian.
/// </summary>
public static FxMinuteFile Detect(string path, string? firstLine, string? symbol)
{
ArgumentNullException.ThrowIfNull(path);
var name = Path.GetFileName(path);
var line = (firstLine ?? "").Trim().TrimStart('');
if (line.StartsWith("Local time", StringComparison.OrdinalIgnoreCase))
{
throw new FormatException("Il file di Dukascopy è in ora locale: scaricalo di nuovo in ora GMT (colonna «Gmt time»).");
}
if (line.StartsWith("Gmt time,", StringComparison.OrdinalIgnoreCase))
{
var side = name.Contains("_BID_", StringComparison.OrdinalIgnoreCase) ? Bid
: name.Contains("_ASK_", StringComparison.OrdinalIgnoreCase) ? Ask
: throw new FormatException("Dal nome del file di Dukascopy non si capisce se i prezzi sono denaro o lettera: deve contenere _BID_ o _ASK_.");
var pair = Pair(symbol ?? name.Split('_')[0]);
return new FxMinuteFile(Dukascopy, pair, side, new CsvMapping
{
Symbol = Series(pair, side),
Venue = Dukascopy,
Timeframe = Timeframes.Minute,
Delimiter = ",",
HasHeader = true,
Time = "Gmt time",
TimeFormat = "dd.MM.yyyy HH:mm:ss.fff",
TimeZone = "UTC",
Open = "Open",
High = "High",
Low = "Low",
Close = "Close",
Volume = "Volume",
Continuous = false,
});
}
if (HistDataLine().IsMatch(line))
{
var named = HistDataName().Match(name);
var pair = Pair(symbol ?? (named.Success ? named.Groups[1].Value
: throw new FormatException("Dal nome del file di HistData non si capisce la coppia: indicala con --symbol, per esempio --symbol EURUSD.")));
return new FxMinuteFile(HistData, pair, Bid, new CsvMapping
{
Symbol = Series(pair, Bid),
Venue = HistData,
Timeframe = Timeframes.Minute,
Delimiter = ";",
HasHeader = false,
Time = "0",
TimeFormat = "yyyyMMdd HHmmss",
TimeZone = "UTC-05:00",
Open = "1",
High = "2",
Low = "3",
Close = "4",
Volume = "5",
Continuous = false,
});
}
throw new FormatException(Unknown);
}
private static string Pair(string text)
{
var pair = text.Trim().ToUpperInvariant();
return FxPairs.Find(pair)?.Name
?? throw new FormatException($"«{text}» non è una delle 28 coppie delle otto valute: indica la coppia con --symbol, per esempio --symbol EURUSD.");
}
[GeneratedRegex(@"^\d{8} \d{6};", RegexOptions.CultureInvariant)]
private static partial Regex HistDataLine();
[GeneratedRegex(@"DAT_ASCII_([A-Za-z]{6})_M1", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)]
private static partial Regex HistDataName();
}
/// <summary>
/// <c>anubis data fx</c> (Phase 12): reads a one-minute file of <see cref="FxMinuteFiles"/>, leaves out the bars outside the
/// 24×5 week (saying how many), checks the rest against that calendar, writes the minutes and then the 15-minute bars
/// rebuilt from every stored minute of the buckets the file touched.
/// </summary>
public sealed class FxMinuteImporter(ResearchStore store)
{
private static readonly TimeSpan OneMinute = TimeSpan.FromMinutes(1);
/// <summary>The import of the minutes, then that of the 15-minute bars.</summary>
public async Task<IReadOnlyList<ImportResult>> ImportAsync(string path, string? symbol, CancellationToken cancellationToken)
{
var lines = await File.ReadAllLinesAsync(path, cancellationToken).ConfigureAwait(false);
var file = FxMinuteFiles.Detect(path, lines.FirstOrDefault(l => l.Trim().Length > 0), symbol);
var parsed = CsvImporter.Parse(lines, file.Mapping);
var notes = parsed.Notes.ToList();
var ordered = parsed.Bars.OrderBy(b => b.OpensAt).ToList();
if (ordered.FirstOrDefault(b => b.OpensAt.UtcTicks % TimeSpan.TicksPerMinute != 0) is { } odd)
{
throw new FormatException($"Il file non contiene barre da un minuto: una comincia alle {odd.OpensAt.UtcDateTime:yyyy-MM-dd HH:mm:ss.fff} (UTC).");
}
var open = ordered.Where(b => BarCalendars.Fx.IsOpen(b.OpensAt, OneMinute)).ToList();
if (open.Count == 0)
{
var outside = ordered.Count;
throw new FormatException(outside > 0
? $"Nessuna barra valida nel file: tutte le {outside} barre lette cadono fuori dall'orario del mercato (24×5, dalla domenica alle 17 al venerdì alle 17 di New York)."
: $"Nessuna barra valida nel file: {parsed.Errors} righe non lette su {parsed.Lines}.");
}
if (open.Count > 1 && !open.Zip(open.Skip(1)).Any(p => p.Second.OpensAt - p.First.OpensAt == OneMinute))
{
throw new FormatException("Il file non contiene barre da un minuto: nessuna barra segue la precedente di un minuto.");
}
if (open.Count < ordered.Count)
{
notes.Add($"{ordered.Count - open.Count} barre fuori dall'orario del mercato (24×5) lasciate fuori");
}
var issues = QualityChecks.CheckIntraday(open.Select(b => b.ToBar()).ToList(), Timeframes.Minute,
BarCalendars.Fx.Moments(open[0].OpensAt, open[^1].OpensAt + OneMinute, OneMinute));
notes.AddRange(issues.Take(CsvImporter.MaxReportedErrors).Select(CsvImporter.Note));
await store.WriteAsync(file.Venue, file.Series, Timeframes.Minute, open, cancellationToken).ConfigureAwait(false);
var quarter = Timeframes.Length(Timeframes.Minutes15);
var from = BarAggregator.BucketOf(open[0].OpensAt, quarter);
var to = BarAggregator.BucketOf(open[^1].OpensAt, quarter) + quarter;
var minutes = await store.ReadAsync(file.Venue, file.Series, Timeframes.Minute, from, to, cancellationToken).ToListAsync(cancellationToken).ConfigureAwait(false);
var quarters = BarAggregator.Aggregate(minutes, Timeframes.Minutes15);
await store.WriteAsync(file.Venue, file.Series, Timeframes.Minutes15, quarters, cancellationToken).ConfigureAwait(false);
return
[
new ImportResult(file.Venue, file.Series, Timeframes.Minute, open.Count, open[0].OpensAt, open[^1].OpensAt, notes),
new ImportResult(file.Venue, file.Series, Timeframes.Minutes15, quarters.Count, quarters[0].OpensAt, quarters[^1].OpensAt, []),
];
}
}
+88 -23
View File
@@ -1,6 +1,7 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Anubis.Brokers;
using Anubis.Core;
@@ -93,7 +94,9 @@ public sealed record CsvMapping
/// <summary><c>unix_ms</c>, <c>unix_s</c>, <c>unix_us</c>, <c>auto</c> (milliseconds or microseconds by size), or a .NET date format such as <c>yyyy-MM-dd HH:mm:ss</c>.</summary>
public string TimeFormat { get; init; } = "auto";
/// <summary>Time zone of text times (IANA id); unix times are always UTC.</summary>
/// <summary>
/// Time zone of text times: an IANA id, or a fixed offset all year such as <c>UTC-05:00</c>; unix times are always UTC.
/// </summary>
public string TimeZone { get; init; } = "UTC";
public string Open { get; init; } = "1";
@@ -123,11 +126,15 @@ public sealed record CsvMapping
};
}
/// <summary>What <see cref="CsvImporter.Parse"/> read: the bars in file order, the notes, the unreadable lines and all the lines.</summary>
public sealed record CsvParse(IReadOnlyList<ResearchBar> Bars, IReadOnlyList<string> Notes, int Errors, int Lines);
/// <summary>
/// The generic importer of user CSV files with one-minute or daily bars into the research history (issue #21).
/// The generic importer of user CSV files with bars of one of the <see cref="Timeframes"/> into the research history
/// (issue #21; any length shorter than a day since Phase 12).
/// Lines that cannot be read are counted and reported, never silently fixed.
/// </summary>
public sealed class CsvImporter(ResearchStore store)
public sealed partial class CsvImporter(ResearchStore store)
{
public const int MaxReportedErrors = 5;
@@ -146,7 +153,46 @@ public sealed class CsvImporter(ResearchStore store)
var symbol = string.IsNullOrWhiteSpace(mapping.Symbol)
? Path.GetFileNameWithoutExtension(csvPath).Split('-', '_')[0].ToUpperInvariant()
: mapping.Symbol;
var zone = TimeZoneInfo.FindSystemTimeZoneById(mapping.TimeZone);
var parsed = Parse(await File.ReadAllLinesAsync(csvPath, cancellationToken).ConfigureAwait(false), mapping);
var bars = parsed.Bars;
var notes = parsed.Notes.ToList();
var ordered = bars.OrderBy(b => b.OpensAt).ToList();
IReadOnlyList<QualityFinding> issues = [];
if (ordered.Count > 0 && Timeframes.IsIntraday(mapping.Timeframe))
{
var length = Timeframes.Length(mapping.Timeframe);
issues = QualityChecks.CheckIntraday(ordered.Select(b => b.ToBar()).ToList(), mapping.Timeframe,
mapping.Continuous ? QualityChecks.Every(ordered[0].OpensAt, ordered[^1].OpensAt + length, length) : null);
}
else if (ordered.Count > 0)
{
var days = ordered.Select(b => new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low,
(double)b.Close, (double)b.Volume)).ToList();
issues = QualityChecks.CheckDaily(days, mapping.Continuous ? QualityChecks.EveryDay(days[0].Day, days[^1].Day) : null);
}
notes.AddRange(issues.Take(MaxReportedErrors).Select(Note));
await store.WriteAsync(mapping.Venue, symbol, mapping.Timeframe, bars, cancellationToken).ConfigureAwait(false);
return new ImportResult(mapping.Venue, symbol, mapping.Timeframe, bars.Count, ordered.FirstOrDefault()?.OpensAt, ordered.LastOrDefault()?.OpensAt, notes);
}
/// <summary>A finding of the checks as a line of the import notes.</summary>
public static string Note(QualityFinding finding)
{
ArgumentNullException.ThrowIfNull(finding);
return $"{finding.Kind} {finding.StartsAt:yyyy-MM-dd HH:mm}: {finding.Detail}";
}
/// <summary>
/// Reads the lines of a CSV with a mapping, without touching any file: the bars in file order, the notes on the
/// lines that could not be read (at most <see cref="MaxReportedErrors"/>, then the count), and the counts.
/// </summary>
public static CsvParse Parse(IEnumerable<string> lines, CsvMapping mapping)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(mapping);
var zone = ZoneOf(mapping.TimeZone);
var numbers = new NumberFormatInfo { NumberDecimalSeparator = mapping.DecimalSeparator, NumberGroupSeparator = mapping.DecimalSeparator == "," ? "." : "," };
var style = mapping.DecimalSeparator == "," ? NumberStyles.Float | NumberStyles.AllowThousands : NumberStyles.Float;
var bars = new List<ResearchBar>();
@@ -154,7 +200,7 @@ public sealed class CsvImporter(ResearchStore store)
var errors = 0;
string[]? header = null;
var lineNumber = 0;
foreach (var line in await File.ReadAllLinesAsync(csvPath, cancellationToken).ConfigureAwait(false))
foreach (var line in lines)
{
lineNumber++;
if (line.Length == 0)
@@ -193,26 +239,45 @@ public sealed class CsvImporter(ResearchStore store)
notes.Add($"{errors} righe non lette su {lineNumber}");
}
var ordered = bars.OrderBy(b => b.OpensAt).ToList();
IReadOnlyList<QualityFinding> issues = [];
if (ordered.Count > 0 && mapping.Timeframe == Timeframes.Minute)
{
issues = QualityChecks.CheckMinutes(ordered.Select(b => b.ToBar()).ToList(),
mapping.Continuous ? QualityChecks.EveryMinute(ordered[0].OpensAt, ordered[^1].OpensAt.AddMinutes(1)) : null);
}
else if (ordered.Count > 0)
{
var days = ordered.Select(b => new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low,
(double)b.Close, (double)b.Volume)).ToList();
issues = QualityChecks.CheckDaily(days, mapping.Continuous ? QualityChecks.EveryDay(days[0].Day, days[^1].Day) : null);
}
notes.AddRange(issues.Take(MaxReportedErrors).Select(i => $"{i.Kind} {i.StartsAt:yyyy-MM-dd HH:mm}: {i.Detail}"));
await store.WriteAsync(mapping.Venue, symbol, mapping.Timeframe, bars, cancellationToken).ConfigureAwait(false);
return new ImportResult(mapping.Venue, symbol, mapping.Timeframe, bars.Count, ordered.FirstOrDefault()?.OpensAt, ordered.LastOrDefault()?.OpensAt, notes);
return new CsvParse(bars, notes, errors, lineNumber);
}
/// <summary>
/// The time zone of a mapping: <c>UTC</c>, a fixed offset all year written <c>UTC+hh:mm</c> or <c>UTC-hh:mm</c> (HistData
/// keeps New York winter time all year), or an IANA id from the system's database.
/// </summary>
public static TimeZoneInfo ZoneOf(string id)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
if (id == "UTC")
{
return TimeZoneInfo.Utc;
}
var match = FixedOffset().Match(id);
if (match.Success)
{
var minutes = int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
if (minutes >= 60)
{
throw new TimeZoneNotFoundException($"Fuso orario «{id}» non valido: i minuti vanno da 00 a 59.");
}
var offset = new TimeSpan(int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), minutes, 0);
if (offset > TimeSpan.FromHours(14))
{
throw new TimeZoneNotFoundException($"Fuso orario «{id}» fuori dai limiti (al massimo 14 ore da UTC).");
}
return TimeZoneInfo.CreateCustomTimeZone(id, match.Groups[1].Value == "-" ? -offset : offset, id, id);
}
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
[GeneratedRegex(@"^UTC([+-])(\d{2}):(\d{2})$", RegexOptions.CultureInvariant)]
private static partial Regex FixedOffset();
private static int Index(string column, string[]? header)
{
if (int.TryParse(column, NumberStyles.None, CultureInfo.InvariantCulture, out var index))
+56 -8
View File
@@ -35,10 +35,39 @@ public static class IssueStatus
public const string Corrected = "corrected";
}
/// <summary>
/// The bar lengths Anubis knows. The names are those of the Binance archives, so an archive and a series built by
/// <see cref="BarAggregator"/> end up in the same folder of the research history.
/// </summary>
public static class Timeframes
{
public const string Day = "1d";
public const string Minute = "1m";
public const string Minutes15 = "15m";
public const string Minutes30 = "30m";
public const string Hour = "1h";
public const string Hours4 = "4h";
public const string Hours8 = "8h";
public const string Day = "1d";
/// <summary>From the shortest to the longest.</summary>
public static IReadOnlyList<string> All { get; } = [Minute, Minutes15, Minutes30, Hour, Hours4, Hours8, Day];
public static bool IsKnown(string timeframe) => All.Contains(timeframe);
/// <summary>A known timeframe shorter than a day; an unknown one is not intraday.</summary>
public static bool IsIntraday(string timeframe) => timeframe != Day && IsKnown(timeframe);
public static TimeSpan Length(string timeframe) => timeframe switch
{
Minute => TimeSpan.FromMinutes(1),
Minutes15 => TimeSpan.FromMinutes(15),
Minutes30 => TimeSpan.FromMinutes(30),
Hour => TimeSpan.FromHours(1),
Hours4 => TimeSpan.FromHours(4),
Hours8 => TimeSpan.FromHours(8),
Day => TimeSpan.FromDays(1),
_ => throw new ArgumentException($"Durata delle barre sconosciuta: «{timeframe}». Valori ammessi: {string.Join(", ", All)}.", nameof(timeframe)),
};
}
/// <summary>A problem found in a series. Moments are UTC; for daily bars they are the day at 00:00 UTC.</summary>
@@ -101,13 +130,22 @@ public static class QualityChecks
/// Checks one-minute bars. <paramref name="expected"/> lists the minutes that should exist (every minute for
/// crypto, the session minutes for stocks); without it gaps are not looked for.
/// </summary>
public static IReadOnlyList<QualityFinding> CheckMinutes(IReadOnlyList<Bar> bars, IEnumerable<DateTimeOffset>? expected = null)
public static IReadOnlyList<QualityFinding> CheckMinutes(IReadOnlyList<Bar> bars, IEnumerable<DateTimeOffset>? expected = null) =>
CheckIntraday(bars, Timeframes.Minute, expected);
/// <summary>
/// Checks bars shorter than a day of any <paramref name="timeframe"/> the way <see cref="CheckMinutes"/> checks minutes;
/// <paramref name="expected"/> lists the opening moments that should exist at that length.
/// </summary>
public static IReadOnlyList<QualityFinding> CheckIntraday(IReadOnlyList<Bar> bars, string timeframe, IEnumerable<DateTimeOffset>? expected = null)
{
ArgumentNullException.ThrowIfNull(bars);
var minutes = timeframe == Timeframes.Minute;
var findings = new List<QualityFinding>();
foreach (var group in bars.GroupBy(b => b.OpensAt).Where(g => g.Count() > 1))
{
findings.Add(new QualityFinding(IssueKinds.Duplicate, group.Key, group.Key, $"{group.Count()} barre per lo stesso minuto"));
findings.Add(new QualityFinding(IssueKinds.Duplicate, group.Key, group.Key,
$"{group.Count()} barre per lo stesso " + (minutes ? "minuto" : "momento")));
}
var unique = bars.DistinctBy(b => b.OpensAt).OrderBy(b => b.OpensAt).ToList();
@@ -126,8 +164,9 @@ public static class QualityChecks
var have = unique.Select(b => b.OpensAt).ToHashSet();
foreach (var run in MissingRuns(expected, have, unique[0].OpensAt, unique[^1].OpensAt))
{
findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last,
run.Count == 1 ? "Manca la barra di un minuto" : $"Mancano {run.Count} minuti"));
findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last, minutes
? run.Count == 1 ? "Manca la barra di un minuto" : $"Mancano {run.Count} minuti"
: run.Count == 1 ? $"Manca una barra da {timeframe}" : $"Mancano {run.Count} barre da {timeframe}"));
}
}
@@ -135,11 +174,20 @@ public static class QualityChecks
}
/// <summary>Every minute in [from, to): the expected moments of a market that never closes.</summary>
public static IEnumerable<DateTimeOffset> EveryMinute(DateTimeOffset from, DateTimeOffset to)
public static IEnumerable<DateTimeOffset> EveryMinute(DateTimeOffset from, DateTimeOffset to) => Every(from, to, TimeSpan.FromMinutes(1));
/// <summary>Every <paramref name="step"/> from <paramref name="from"/> (included) to <paramref name="to"/> (excluded).</summary>
public static IEnumerable<DateTimeOffset> Every(DateTimeOffset from, DateTimeOffset to, TimeSpan step)
{
for (var t = from; t < to; t = t.AddMinutes(1))
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(step, TimeSpan.Zero);
return Steps(from, to, step);
static IEnumerable<DateTimeOffset> Steps(DateTimeOffset from, DateTimeOffset to, TimeSpan step)
{
yield return t;
for (var t = from; t < to; t += step)
{
yield return t;
}
}
}
+19 -4
View File
@@ -212,7 +212,7 @@ public sealed class StrategyParameters
public static StrategyParameters None { get; } = new([]);
/// <summary>The parameters a text such as <c>fast=20;slow=100</c> gives to a family: its defaults where the text says nothing, or nothing it accepts.</summary>
public static StrategyParameters Of(IStrategyFamily family, string? text)
public static StrategyParameters Of(IResearchFamily family, string? text)
{
ArgumentNullException.ThrowIfNull(family);
var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal);
@@ -328,10 +328,21 @@ public interface IStrategy
/// 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);
public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList<decimal> Grid, decimal Min, decimal Max, bool Whole = false)
{
/// <summary>
/// True for a choice axis: its values name different rules (a signal, a relation, a style), not points on a scale. The
/// plateau rule never averages two variants that differ on a choice axis.
/// </summary>
public bool Choices { get; init; }
}
/// <summary>A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid.</summary>
public interface IStrategyFamily
/// <summary>
/// What the laboratory needs to judge a family of rules: its name, its version and its parameters. A family judged by an
/// engine of its own (baskets) stops here; <see cref="IStrategyFamily"/> adds the strategies the daily engine and the live
/// bot run.
/// </summary>
public interface IResearchFamily
{
string Id { get; }
@@ -350,7 +361,11 @@ public interface IStrategyFamily
/// <summary>False for a point of the grid that makes no sense (a short average longer than the long one).</summary>
bool Accepts(StrategyParameters parameters) => true;
}
/// <summary>A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid.</summary>
public interface IStrategyFamily : IResearchFamily
{
IStrategy Create(StrategyParameters parameters);
}