Add sub-day research bars, ECB crosses and FX minute import
Phase 12 needs intraday bars and the 28 currency pairs for the basket research, without touching the daily backtest engine. - Timeframes gain 15m, 30m, 1h, 4h, 8h with Length and IsIntraday; the CSV import checks any intraday timeframe minute-style at its length instead of sending it to the daily check. - BarAggregator builds longer bars in decimal on UTC epoch buckets, never fills a gap and leaves out a bucket that has not closed. - Bar calendars (24x7, 24x5 FX from Sunday to Friday 17:00 New York, exchange sessions) and BarDataset: a common clock in double columns, NaN where a series has no bar, optional ask columns, Through that only shows closed bars, and a fingerprint of the data. - EcbCrosses derives the 28 pairs (from the shared Baskets list) from the seven ECB rates; "anubis data ecb" writes them under research/ecb from the same cached zip as "backtest base", whose loader moves into the library with its output unchanged. - CsvImporter.Parse is split out of ImportAsync and mappings accept a fixed offset such as UTC-05:00. - "anubis data fx" reads Dukascopy and HistData one-minute files, refuses anything else in Italian, drops bars outside the FX week and writes the 1m and 15m series. The formats come from general knowledge: the fixtures are constructed samples, as API-NOTES says. refs #120 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aec848b4a2
commit
2a96e08d5a
17 files changed
+1632
-42
No files matched your search
@@ -166,6 +166,9 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio
|
||||
| Codici di una chiave rifiutata | Alpaca e OKX rispondono 401 o 403; su OKX i codici 50102 e 50112 parlano dell'orologio e non della chiave. Scritto dalla documentazione, non provato dal vivo: se un codice mancasse, l'avviso direbbe "non risponde" invece di "non accetta la chiave" (ADR 0020). | 9 |
|
||||
| Archivi della SEC (settori) | `company_tickers.json` e `submissions` letti come da documentazione, non provati dal vivo perché serve un contatto dell'utente. Senza, nessuna richiesta parte; un settore sconosciuto non limita niente. | 9 |
|
||||
| Minuti senza scambi su OKX | Il buco si riscarica una volta, poi resta segnato come non recuperabile e non blocca nulla. | 2 |
|
||||
| Formato dei file a un minuto di Dukascopy | Scritto da conoscenze generali, non da un file visto: intestazione `Gmt time,Open,High,Low,Close,Volume`, ora `dd.MM.yyyy HH:mm:ss.fff` in UTC, un file per lato con `_BID_` o `_ASK_` nel nome, unità del volume non documentata (si tiene com'è). I campioni nei test (`Fixtures/fx`) sono costruiti a mano. Un file in ora locale o di formato diverso viene rifiutato con la spiegazione; le barre fuori dalla settimana 24×5 vengono lasciate fuori e contate. Da confrontare con il primo file vero dell'utente. | 12 |
|
||||
| Formato dei file a un minuto di HistData | Scritto da conoscenze generali: ASCII generico senza intestazione, `;`, ora `yyyyMMdd HHmmss` di New York senza ora legale (UTC−5 tutto l'anno), solo denaro, coppia nel nome `DAT_ASCII_EURUSD_M1_2024.csv`. Il formato MetaTrader (`DAT_MT_…`) viene rifiutato. Campioni costruiti a mano; da confrontare con il primo file vero. | 12 |
|
||||
| Le sette valute nello storico della BCE dal 1999 | Lo zip `eurofxref-hist.zip` ha le colonne USD, JPY, GBP, CHF, AUD, CAD e NZD (controllato sul file registrato di due giorni); non è stato controllato su tutto lo storico che ogni giorno le abbia tutte. Un giorno senza un cambio toglie solo le coppie che lo usano, e `anubis data ecb` dice quante barre mancano. | 12 |
|
||||
|
||||
## Verifiche della Fase 2 (dati di mercato)
|
||||
|
||||
|
||||
+11
-1
@@ -290,7 +290,7 @@ Chi aggiorna da una versione precedente trova nel Diario una riga sola: da quest
|
||||
}
|
||||
```
|
||||
|
||||
Le colonne si indicano con il nome dell'intestazione o con il numero, contando da 0. `timeframe` è `1m` (al minuto) o `1d` (giornaliero). `time_format` è `auto`, `unix_s`, `unix_ms`, `unix_us` o un formato di data. `continuous` è `true` per i mercati che non chiudono mai (crypto), `false` per le azioni. Poi:
|
||||
Le colonne si indicano con il nome dell'intestazione o con il numero, contando da 0. `timeframe` è `1m` (al minuto), `15m`, `30m`, `1h`, `4h`, `8h` o `1d` (giornaliero). `time_format` è `auto`, `unix_s`, `unix_ms`, `unix_us` o un formato di data. `time_zone` è un fuso come `Europe/Rome` oppure uno spostamento fisso tutto l'anno come `UTC-05:00`. `continuous` è `true` per i mercati che non chiudono mai (crypto), `false` per le azioni. Poi:
|
||||
|
||||
```sh
|
||||
docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data csv /data/import/file.csv
|
||||
@@ -298,6 +298,16 @@ docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data csv
|
||||
|
||||
Se hai impostato `PUID` e `PGID`, metti quei numeri al posto di `99:100`. Il comando scrive quante barre ha letto e i problemi trovati.
|
||||
|
||||
**Valute per la ricerca.** Due comandi preparano le 28 coppie delle otto valute (EUR, GBP, AUD, NZD, USD, CAD, CHF, JPY) nello storico di ricerca; il bot non le usa per decidere.
|
||||
|
||||
- `data ecb` ricava ogni giorno dal 1999 le 28 coppie dai cambi di riferimento della BCE (per esempio USDJPY è il cambio dello yen diviso quello del dollaro). Scarica lo stesso file di `backtest base`; con `--offline` usa quello già scaricato.
|
||||
- `data fx <file>` legge un file a un minuto che scarichi tu da Dukascopy (un file per il prezzo denaro, `_BID_` nel nome, e uno per la lettera, `_ASK_`, in ora GMT) o da HistData (formato ASCII generico, `DAT_ASCII_EURUSD_M1_2024.csv`, solo denaro). Scrive le barre da un minuto e quelle da 15 minuti costruite da quelle. Se il nome del file non dice la coppia, aggiungi `--symbol EURUSD`. Le barre del fine settimana vengono lasciate fuori e il comando dice quante. Un formato diverso viene rifiutato con la spiegazione.
|
||||
|
||||
```sh
|
||||
docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data ecb
|
||||
docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data fx /data/import/DAT_ASCII_EURUSD_M1_2024.csv
|
||||
```
|
||||
|
||||
Attenzione: il Laboratorio legge dallo storico di ricerca solo le serie giornaliere di Binance. I dati importati con `"venue": "import"` restano in archivio e il Laboratorio **non li usa**. Per usarli servono `"venue": "binance"`, `"timeframe": "1d"` e un simbolo di Binance come `BTCUSDT`: in quel caso le tue barre **sostituiscono** quelle già scaricate per gli stessi giorni, anche per la revisione trimestrale. Fallo solo se sei sicuro dei dati.
|
||||
|
||||
---
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 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);
|
||||
@@ -72,6 +95,33 @@ internal static class DataCommand
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,32 @@ 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);
|
||||
Directory.CreateDirectory(researchRoot);
|
||||
await File.WriteAllBytesAsync(path, zip, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return ParseHistoryCsv(ExtractHistoryCsv(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)), currencies);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The weekly economic calendar of Forex Factory (faireconomy.media). It has no actual values.</summary>
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
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)
|
||||
{
|
||||
throw new FormatException($"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, []),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,39 @@ 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);
|
||||
return new CsvParse(bars, notes, errors, lineNumber);
|
||||
}
|
||||
|
||||
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);
|
||||
/// <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 offset = new TimeSpan(int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture), 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))
|
||||
|
||||
@@ -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,13 +174,22 @@ 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)
|
||||
{
|
||||
for (var t = from; t < to; t += step)
|
||||
{
|
||||
yield return t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<DateOnly> EveryDay(DateOnly from, DateOnly to)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
20240102 030000;1.094500;1.094800;1.094400;1.094700;0
|
||||
20240102 030100;1.094700;1.095200;1.094600;1.095100;0
|
||||
20240102 030700;1.095100;1.095300;1.094900;1.095000;0
|
||||
20240102 031400;1.095000;1.095000;1.094100;1.094300;0
|
||||
20240102 031500;1.094300;1.094600;1.094200;1.094500;0
|
||||
|
@@ -0,0 +1,6 @@
|
||||
Gmt time,Open,High,Low,Close,Volume
|
||||
02.01.2024 08:00:00.000,1.09462,1.09492,1.09452,1.09482,10.5
|
||||
02.01.2024 08:01:00.000,1.09482,1.09532,1.09472,1.09522,20.25
|
||||
02.01.2024 08:07:00.000,1.09522,1.09542,1.09502,1.09512,3
|
||||
02.01.2024 08:14:00.000,1.09512,1.09512,1.09422,1.09442,1.5
|
||||
02.01.2024 08:15:00.000,1.09442,1.09472,1.09432,1.09462,7
|
||||
|
@@ -0,0 +1,7 @@
|
||||
Gmt time,Open,High,Low,Close,Volume
|
||||
02.01.2024 08:00:00.000,1.09450,1.09480,1.09440,1.09470,10.5
|
||||
02.01.2024 08:01:00.000,1.09470,1.09520,1.09460,1.09510,20.25
|
||||
02.01.2024 08:07:00.000,1.09510,1.09530,1.09490,1.09500,3
|
||||
02.01.2024 08:14:00.000,1.09500,1.09500,1.09410,1.09430,1.5
|
||||
02.01.2024 08:15:00.000,1.09430,1.09460,1.09420,1.09450,7
|
||||
06.01.2024 12:00:00.000,1.09450,1.09450,1.09450,1.09450,0
|
||||
|
@@ -0,0 +1,622 @@
|
||||
using System.IO.Compression;
|
||||
using Anubis.Baskets;
|
||||
using Anubis.Brokers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Bars shorter than a day for research, the 28 currency pairs from the ECB rates and the import of one-minute FX files
|
||||
/// (Phase 12, issue #120).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ResearchBarsTests
|
||||
{
|
||||
private static readonly DateTimeOffset _jan2 = new(2024, 1, 2, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static ResearchBar Minute(DateTimeOffset at, decimal open, decimal high, decimal low, decimal close, decimal volume = 1m) =>
|
||||
new(at, open, high, low, close, volume);
|
||||
|
||||
// ---- Timeframes ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TimeframesKnowTheirLengthAndWhichAreIntraday()
|
||||
{
|
||||
CollectionAssert.AreEqual(new[] { "1m", "15m", "30m", "1h", "4h", "8h", "1d" }, Timeframes.All.ToArray());
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(1), Timeframes.Length(Timeframes.Minute));
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(15), Timeframes.Length(Timeframes.Minutes15));
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(30), Timeframes.Length(Timeframes.Minutes30));
|
||||
Assert.AreEqual(TimeSpan.FromHours(1), Timeframes.Length(Timeframes.Hour));
|
||||
Assert.AreEqual(TimeSpan.FromHours(4), Timeframes.Length(Timeframes.Hours4));
|
||||
Assert.AreEqual(TimeSpan.FromHours(8), Timeframes.Length(Timeframes.Hours8));
|
||||
Assert.AreEqual(TimeSpan.FromDays(1), Timeframes.Length(Timeframes.Day));
|
||||
Assert.IsTrue(Timeframes.IsIntraday("15m"));
|
||||
Assert.IsTrue(Timeframes.IsIntraday("1m"));
|
||||
Assert.IsFalse(Timeframes.IsIntraday("1d"));
|
||||
Assert.IsFalse(Timeframes.IsIntraday("1w"), "an unknown timeframe is not intraday");
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Timeframes.Length("1w"));
|
||||
}
|
||||
|
||||
// ---- Aggregator ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorNeverFillsAGapAndEmitsPartialBuckets()
|
||||
{
|
||||
var minutes = new[]
|
||||
{
|
||||
Minute(_jan2.AddMinutes(31), 10m, 12m, 9m, 11m, 2m),
|
||||
Minute(_jan2, 5m, 6m, 4m, 5.5m, 1m),
|
||||
};
|
||||
|
||||
var bars = BarAggregator.Aggregate(minutes, Timeframes.Minutes15);
|
||||
|
||||
Assert.AreEqual(2, bars.Count, "the empty bucket of 00:15 gives no bar");
|
||||
Assert.AreEqual(new ResearchBar(_jan2, 5m, 6m, 4m, 5.5m, 1m), bars[0], "a bucket with one minute out of fifteen is still a bar");
|
||||
Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(30), 10m, 12m, 9m, 11m, 2m), bars[1]);
|
||||
Assert.AreEqual(0, BarAggregator.Aggregate([], Timeframes.Hour).Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorLeavesOutTheBucketThatHasNotClosed()
|
||||
{
|
||||
var minutes = Enumerable.Range(0, 21).Select(i => Minute(_jan2.AddMinutes(i), 1m + i, 2m + i, 0.5m + i, 1.5m + i)).ToList();
|
||||
|
||||
var early = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(25));
|
||||
Assert.AreEqual(1, early.Count, "00:15–00:30 ends after 00:25: not emitted");
|
||||
Assert.AreEqual(_jan2, early[0].OpensAt);
|
||||
|
||||
var closed = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(30));
|
||||
Assert.AreEqual(2, closed.Count, "a bucket that ends exactly at the cut is complete");
|
||||
Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(15), 16m, 22m, 15.5m, 21.5m, 6m), closed[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void FourHourBucketsOfBinanceMinutesStartOnUtcMultiples()
|
||||
{
|
||||
// Binance archives: 4h klines open at 00, 04, 08 … UTC; minutes carry quote volume and trades.
|
||||
var start = new DateTimeOffset(2024, 3, 10, 3, 58, 0, TimeSpan.Zero);
|
||||
var minutes = Enumerable.Range(0, 4)
|
||||
.Select(i => Minute(start.AddMinutes(i), 100m + i, 101m + i, 99m + i, 100.5m + i, 0.25m) with { QuoteVolume = 10.1m, Trades = 3 + i })
|
||||
.ToList();
|
||||
|
||||
var bars = BarAggregator.Aggregate(minutes, Timeframes.Hours4);
|
||||
|
||||
Assert.AreEqual(2, bars.Count);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 0, 0, 0, TimeSpan.Zero), bars[0].OpensAt);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 4, 0, 0, TimeSpan.Zero), bars[1].OpensAt);
|
||||
Assert.AreEqual(new ResearchBar(bars[0].OpensAt, 100m, 102m, 99m, 101.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 7 }, bars[0]);
|
||||
Assert.AreEqual(new ResearchBar(bars[1].OpensAt, 102m, 104m, 101m, 103.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 11 }, bars[1]);
|
||||
|
||||
// One minute without quote volume or trades: the sums would be wrong, so they stay empty.
|
||||
minutes[3] = minutes[3] with { QuoteVolume = null, Trades = null };
|
||||
var partial = BarAggregator.Aggregate(minutes, Timeframes.Hours4);
|
||||
Assert.AreEqual(20.2m, partial[0].QuoteVolume);
|
||||
Assert.IsNull(partial[1].QuoteVolume);
|
||||
Assert.IsNull(partial[1].Trades);
|
||||
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 8, 0, 0, TimeSpan.Zero),
|
||||
BarAggregator.BucketOf(new DateTimeOffset(2024, 3, 10, 12, 59, 0, TimeSpan.FromHours(1)), TimeSpan.FromHours(4)), "UTC, whatever the offset given");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AggregatorKeepsDecimalsExactAndRefusesUnalignedOrDuplicateMinutes()
|
||||
{
|
||||
var minutes = new[]
|
||||
{
|
||||
Minute(_jan2, 1.123456789012345678m, 1.2m, 1.1m, 1.15m, 0.1m),
|
||||
Minute(_jan2.AddMinutes(1), 1.15m, 1.3m, 1.000000000000000001m, 1.25m, 0.2m),
|
||||
};
|
||||
var bar = BarAggregator.Aggregate(minutes, Timeframes.Minutes30).Single();
|
||||
Assert.AreEqual(0.3m, bar.Volume, "0.1 + 0.2 is 0.3 in decimal");
|
||||
Assert.AreEqual(1.123456789012345678m, bar.Open);
|
||||
Assert.AreEqual(1.000000000000000001m, bar.Low);
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate([Minute(_jan2.AddSeconds(30), 1m, 1m, 1m, 1m)], Timeframes.Minutes15));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate([minutes[0], minutes[0]], Timeframes.Minutes15));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => BarAggregator.Aggregate(minutes, Timeframes.Day + "x"));
|
||||
}
|
||||
|
||||
// ---- Calendars ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFxWeekOpensSundayAndClosesFridayAtFivePmNewYorkAcrossDaylightSaving()
|
||||
{
|
||||
var fx = BarCalendars.Fx;
|
||||
var quarter = TimeSpan.FromMinutes(15);
|
||||
static DateTimeOffset Utc(int month, int day, int hour, int minute) => new(2024, month, day, hour, minute, 0, TimeSpan.Zero);
|
||||
|
||||
// Friday 8 March 2024 closes at 17:00 EST (22:00 UTC); the US clocks move on Sunday 10 March, so it reopens
|
||||
// at 17:00 EDT (21:00 UTC). Europe moves on 31 March: the two are different weeks.
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 8, 21, 45), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 8, 22, 0), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 9, 12, 0), quarter), "Saturday");
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 20, 45), quarter));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 10, 21, 0), quarter));
|
||||
|
||||
// November: Friday 1 closes at 17:00 EDT (21:00 UTC), Sunday 3 reopens at 17:00 EST (22:00 UTC).
|
||||
Assert.IsTrue(fx.IsOpen(Utc(11, 1, 20, 45), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(11, 1, 21, 0), quarter));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(11, 3, 21, 45), quarter));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(11, 3, 22, 0), quarter));
|
||||
|
||||
var march = fx.Moments(Utc(3, 8, 0, 0), Utc(3, 11, 0, 0), quarter).ToList();
|
||||
Assert.AreEqual(Utc(3, 8, 21, 45), march.Last(t => t < Utc(3, 9, 0, 0)));
|
||||
Assert.AreEqual(Utc(3, 10, 21, 0), march.First(t => t > Utc(3, 9, 0, 0)));
|
||||
Assert.AreEqual(88 + 12, march.Count, "Friday until 22:00 UTC, then Sunday from 21:00 UTC");
|
||||
|
||||
// A bar that straddles the opening is open: it holds traded minutes.
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 10, 20, 0), TimeSpan.FromHours(4)));
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 16, 0), TimeSpan.FromHours(4)));
|
||||
|
||||
// Daily bars: Monday to Friday, the days the ECB publishes.
|
||||
Assert.IsFalse(fx.IsOpen(Utc(3, 10, 0, 0), TimeSpan.FromDays(1)));
|
||||
Assert.IsTrue(fx.IsOpen(Utc(3, 11, 0, 0), TimeSpan.FromDays(1)));
|
||||
Assert.IsTrue(BarCalendars.Always.IsOpen(Utc(3, 9, 12, 0), quarter));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CalendarsCountTheirPeriodsPerYearAndExchangesKeepOnlyTheirSessions()
|
||||
{
|
||||
Assert.AreEqual(35040, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromMinutes(15)));
|
||||
Assert.AreEqual(365, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
Assert.AreEqual(24960, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromMinutes(15)), "52 weeks × 5 days × 96");
|
||||
Assert.AreEqual(260, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
|
||||
var day = new DateOnly(2024, 7, 2);
|
||||
var session = new MarketSession(day, Zones.At(day, new TimeOnly(9, 30), Zones.NewYork), Zones.At(day, new TimeOnly(16, 0), Zones.NewYork));
|
||||
var exchange = BarCalendars.Exchange([session]);
|
||||
Assert.AreEqual("exchange", exchange.Name);
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 15, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)));
|
||||
Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 30, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "09:30 EDT");
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 20, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "16:00 EDT is the close");
|
||||
Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1)));
|
||||
Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 3, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1)), "no session that day");
|
||||
Assert.AreEqual(26, exchange.Moments(session.OpenUtc.AddHours(-2), session.CloseUtc.AddHours(2), TimeSpan.FromMinutes(15)).Count());
|
||||
Assert.AreEqual(252 * 26, exchange.PeriodsPerYear(TimeSpan.FromMinutes(15)));
|
||||
Assert.AreEqual(252, exchange.PeriodsPerYear(TimeSpan.FromDays(1)));
|
||||
}
|
||||
|
||||
// ---- BarDataset ----
|
||||
|
||||
private static Dictionary<string, IReadOnlyList<ResearchBar>> TwoSymbols() => new(StringComparer.Ordinal)
|
||||
{
|
||||
["BBB"] = [Minute(_jan2, 1m, 2m, 0.5m, 1.5m), Minute(_jan2.AddMinutes(30), 3m, 4m, 2.5m, 3.5m), Minute(_jan2.AddMinutes(45), 5m, 6m, 4.5m, 5.5m)],
|
||||
["AAA"] = [Minute(_jan2, 10m, 20m, 5m, 15m), Minute(_jan2.AddMinutes(15), 11m, 21m, 6m, 16m), Minute(_jan2.AddMinutes(30), 12m, 22m, 7m, 17m)],
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetSharesOneClockAndLeavesMissingBarsEmpty()
|
||||
{
|
||||
var bars = TwoSymbols();
|
||||
bars["AAA"] = [.. bars["AAA"], Minute(_jan2.AddDays(4).AddHours(12), 1m, 1m, 1m, 1m)]; // Saturday: outside the FX week.
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), bars);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "AAA", "BBB" }, data.Symbols.ToArray(), "ordinal order");
|
||||
CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15), _jan2.AddMinutes(30), _jan2.AddMinutes(45) }, data.Clock.ToArray());
|
||||
Assert.AreEqual(TimeSpan.FromMinutes(15), data.Length);
|
||||
Assert.AreEqual(24960, data.PeriodsPerYear);
|
||||
Assert.IsTrue(data.Has("BBB", 0));
|
||||
Assert.IsFalse(data.Has("BBB", 1));
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("BBB").Close[1]), "a missing bar is NaN, never the previous close");
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("BBB").Open[1]));
|
||||
Assert.AreEqual(3.5, data.Bars("BBB").Close[2]);
|
||||
Assert.IsTrue(double.IsNaN(data.Bars("AAA").Close[3]));
|
||||
Assert.AreEqual(16.0, data.Bars("AAA").Close[data.IndexOf(_jan2.AddMinutes(15))]);
|
||||
Assert.AreEqual(-1, data.IndexOf(_jan2.AddMinutes(7)));
|
||||
Assert.AreEqual(0, data.Dropped, "the Saturday bar is outside [from, to): not counted");
|
||||
Assert.IsNull(data.Ask("AAA"));
|
||||
|
||||
var week = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddDays(7), bars);
|
||||
Assert.AreEqual(1, week.Dropped, "a bar on Saturday is outside the FX week");
|
||||
Assert.AreEqual(5 * 96, week.Clock.Count, "Tuesday 00:00 UTC to the next Tuesday, without Friday 22:00 to Sunday 22:00 UTC");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetThroughNeverShowsABarThatHasNotClosed()
|
||||
{
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols());
|
||||
|
||||
var cut = data.Through(_jan2.AddMinutes(37));
|
||||
CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15) }, cut.Clock.ToArray(), "the bar of 00:30 closes at 00:45");
|
||||
Assert.AreEqual(2, cut.Bars("AAA").Close.Count);
|
||||
Assert.AreEqual(_jan2.AddMinutes(30), cut.ClosesAt(1));
|
||||
Assert.AreEqual(3, data.Through(_jan2.AddMinutes(45)).Clock.Count, "a bar that closes exactly at the cut is known");
|
||||
Assert.AreEqual(0, data.Through(_jan2.AddMinutes(14)).Clock.Count);
|
||||
|
||||
var middle = data.Between(_jan2.AddMinutes(15), _jan2.AddMinutes(45));
|
||||
CollectionAssert.AreEqual(new[] { _jan2.AddMinutes(15), _jan2.AddMinutes(30) }, middle.Clock.ToArray());
|
||||
Assert.AreEqual(17.0, middle.Bars("AAA").Close[1]);
|
||||
Assert.IsTrue(double.IsNaN(middle.Bars("BBB").Close[0]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BarDatasetFingerprintChangesWhenOnePriceChanges()
|
||||
{
|
||||
var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols());
|
||||
Assert.AreEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint());
|
||||
Assert.AreEqual(64, data.Fingerprint().Length);
|
||||
|
||||
var changed = TwoSymbols();
|
||||
changed["BBB"] = [changed["BBB"][0], changed["BBB"][1] with { Close = 3.5000001m }, changed["BBB"][2]];
|
||||
Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), changed).Fingerprint());
|
||||
Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint(), "the calendar is part of the data");
|
||||
Assert.AreNotEqual(data.Fingerprint(), data.Through(_jan2.AddMinutes(45)).Fingerprint());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BarDatasetReadsBidAndAskSeriesFromTheResearchStore()
|
||||
{
|
||||
var folder = TempFolder.Create("bardataset");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(folder);
|
||||
await store.WriteAsync("dukascopy", "EURUSD-BID", Timeframes.Minutes15, [Minute(_jan2, 1.1m, 1.2m, 1.0m, 1.15m)], CancellationToken.None).ConfigureAwait(false);
|
||||
await store.WriteAsync("dukascopy", "EURUSD-ASK", Timeframes.Minutes15, [Minute(_jan2, 1.1001m, 1.2001m, 1.0001m, 1.1501m)], CancellationToken.None).ConfigureAwait(false);
|
||||
await store.WriteAsync("dukascopy", "USDJPY-BID", Timeframes.Minutes15, [Minute(_jan2.AddMinutes(15), 150m, 151m, 149m, 150.5m)], CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
var data = await BarDataset.LoadQuotesAsync(store, "dukascopy", ["USDJPY", "EURUSD"], Timeframes.Minutes15, _jan2, _jan2.AddMinutes(30), CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { "EURUSD", "USDJPY" }, data.Symbols.ToArray());
|
||||
Assert.AreEqual("24x5", data.Calendar.Name);
|
||||
Assert.AreEqual(1.15, data.Bars("EURUSD").Close[0]);
|
||||
Assert.AreEqual(1.1501, data.Ask("EURUSD")!.Close[0]);
|
||||
Assert.IsNull(data.Ask("USDJPY"), "no ask file for the pair: no ask columns");
|
||||
Assert.AreEqual(150.5, data.Bars("USDJPY").Close[1]);
|
||||
|
||||
var plain = await BarDataset.LoadAsync(store, "dukascopy", ["EURUSD-BID"], Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddMinutes(30), CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
Assert.AreEqual(1.15, plain.Bars("EURUSD-BID").Close[0]);
|
||||
Assert.IsTrue(double.IsNaN(plain.Bars("EURUSD-BID").Close[1]));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ECB crosses ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheTwentyEightPairsComeFromTheSevenEcbRates()
|
||||
{
|
||||
CollectionAssert.AreEquivalent(new[] { "GBP", "AUD", "NZD", "USD", "CAD", "CHF", "JPY" }, EcbCrosses.Rates.ToArray());
|
||||
var rates = Ecb.ParseHistoryCsv(Fixture.Text("free/ecb-hist.csv"), EcbCrosses.Rates);
|
||||
var crosses = EcbCrosses.Build(rates);
|
||||
|
||||
CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), crosses.Keys.ToArray(), "the pairs and their order come from the shared list");
|
||||
Assert.AreEqual(56, crosses.Values.Sum(b => b.Count), "28 pairs × 2 days");
|
||||
|
||||
var day = new DateTimeOffset(2026, 11, 9, 0, 0, 0, TimeSpan.Zero);
|
||||
decimal On(string pair, DateTimeOffset at) => crosses[pair].Single(b => b.OpensAt == at).Close;
|
||||
var usdjpy = crosses["USDJPY"].Single(b => b.OpensAt == day);
|
||||
Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy.Close);
|
||||
Assert.AreEqual(new ResearchBar(day, usdjpy.Close, usdjpy.Close, usdjpy.Close, usdjpy.Close, 0m), usdjpy, "O = H = L = C at 00:00 UTC, volume 0");
|
||||
Assert.AreEqual(176.79m, On("EURJPY", day), "a EUR pair is the rate itself");
|
||||
Assert.AreEqual(0.8343m, On("EURGBP", day));
|
||||
var expected = new Dictionary<string, decimal>
|
||||
{
|
||||
["USDJPY"] = 157.94693112m,
|
||||
["GBPUSD"] = 1.34160374m,
|
||||
["GBPJPY"] = 211.90219346m,
|
||||
["AUDUSD"] = 0.68939394m,
|
||||
["AUDCAD"] = 0.97222222m,
|
||||
["AUDNZD"] = 1.22819660m,
|
||||
["NZDUSD"] = 0.56130585m,
|
||||
["USDCAD"] = 1.41025641m,
|
||||
["USDCHF"] = 0.81872599m,
|
||||
["CADCHF"] = 0.58055116m,
|
||||
["CADJPY"] = 111.99873297m,
|
||||
["CHFJPY"] = 192.91793976m,
|
||||
};
|
||||
foreach (var (pair, value) in expected)
|
||||
{
|
||||
Assert.AreEqual(value, Math.Round(On(pair, day), 8), pair);
|
||||
}
|
||||
|
||||
var friday = day.AddDays(-3);
|
||||
Assert.AreEqual(158.32512315m, Math.Round(On("USDJPY", friday), 8));
|
||||
Assert.AreEqual(1.33848828m, Math.Round(On("GBPUSD", friday), 8));
|
||||
|
||||
// A day without the franc: only the seven pairs with CHF lose that day.
|
||||
var withoutFranc = rates.Where(r => !(r.Quote == "CHF" && r.Date == new DateOnly(2026, 11, 6))).ToList();
|
||||
var partial = EcbCrosses.Build(withoutFranc);
|
||||
Assert.AreEqual(49, partial.Values.Sum(b => b.Count));
|
||||
foreach (var pair in FxPairs.All)
|
||||
{
|
||||
Assert.AreEqual(pair.Base == "CHF" || pair.Quote == "CHF" ? 1 : 2, partial[pair.Name].Count, pair.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] EcbZip()
|
||||
{
|
||||
using var zip = new MemoryStream();
|
||||
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
|
||||
using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open()))
|
||||
{
|
||||
writer.Write(Fixture.Text("free/ecb-hist.csv"));
|
||||
}
|
||||
|
||||
return zip.ToArray();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataEcbWritesTheTwentyEightPairsAndOfflineReusesTheCachedHistory()
|
||||
{
|
||||
var data = TempFolder.Create("data-ecb");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip());
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], output, env, http).ConfigureAwait(false), output.ToString());
|
||||
Assert.AreEqual(1, http.Requests.Count);
|
||||
StringAssert.Contains(output.ToString(), "Coppie di valute dai cambi BCE: 28 coppie, 2 giorni, dal 2026-11-06 al 2026-11-09.");
|
||||
|
||||
var research = Path.Combine(data, "research");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(research, Ecb.HistoryFile)), "the same cached zip as backtest base");
|
||||
var store = new ResearchStore(research);
|
||||
var series = store.Series();
|
||||
Assert.AreEqual(28, series.Count);
|
||||
Assert.IsTrue(series.All(s => s.Venue == "ecb" && s.Timeframe == Timeframes.Day), string.Join(", ", series));
|
||||
CollectionAssert.AreEquivalent(FxPairs.All.Select(p => p.Name).ToArray(), series.Select(s => s.Symbol).ToArray());
|
||||
var usdjpy = await store.ReadAsync("ecb", "USDJPY", Timeframes.Day, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false);
|
||||
Assert.AreEqual(2, usdjpy.Count);
|
||||
Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy[1].Close, "the file keeps every decimal");
|
||||
|
||||
var offline = new FakeHttp();
|
||||
using var again = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--offline", "--platform", "docker", "--data-dir", data], again, env, offline).ConfigureAwait(false), again.ToString());
|
||||
Assert.AreEqual(0, offline.Requests.Count, "offline with the cached zip: no request");
|
||||
StringAssert.Contains(again.ToString(), "28 coppie");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task BacktestBaseStillPrintsTheSameEcbLineFromTheSharedLoader()
|
||||
{
|
||||
var research = TempFolder.Create("ecb-loader");
|
||||
try
|
||||
{
|
||||
var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 8, 0, 0, TimeSpan.Zero));
|
||||
var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip());
|
||||
using var output = new StringWriter();
|
||||
var rates = await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, output).ConfigureAwait(false);
|
||||
Assert.AreEqual("Cambi BCE EUR/USD: 2 giorni, dal 2026-11-06 al 2026-11-09." + Environment.NewLine, output.ToString());
|
||||
Assert.AreEqual(2, rates.Count);
|
||||
Assert.IsTrue(rates.All(r => r.Quote == "USD"), "only the dollar, as before");
|
||||
Assert.AreEqual(1, http.Requests.Count, "offline but without the cached zip: downloaded once");
|
||||
Assert.AreEqual(Path.Combine(research, "ecb-eurofxref-hist.zip"), Ecb.HistoryPath(research));
|
||||
|
||||
await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, TextWriter.Null).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, http.Requests.Count, "offline with the cached zip: no request");
|
||||
await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: false, TextWriter.Null).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, http.Requests.Count, "online: downloaded again");
|
||||
|
||||
var missing = new FakeHttp().On("eurofxref-hist.zip", "", System.Net.HttpStatusCode.NotFound);
|
||||
var error = await Assert.ThrowsExactlyAsync<MarketDataException>(() =>
|
||||
Ecb.LoadHistoryAsync(new ApiHttp(missing.Client(), clock, "ecb"), Path.Combine(research, "empty"), offline: true, ["USD"], CancellationToken.None)).ConfigureAwait(false);
|
||||
Assert.AreEqual("BCE: lo storico dei cambi non è disponibile.", error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(research);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- FX minute files ----
|
||||
|
||||
private const string HistDataFile = "fx/DAT_ASCII_EURUSD_M1_2024.csv";
|
||||
private const string DukascopyBid = "fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv";
|
||||
private const string DukascopyAsk = "fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv";
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task FifteenMinuteBarsFromMinutesMatchTheHandComputedOnesInBothFormats()
|
||||
{
|
||||
// Constructed samples (no real file yet): the same bid prices in both formats, HistData at fixed UTC−5.
|
||||
var folder = TempFolder.Create("fx-15m");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(folder);
|
||||
var importer = new FxMinuteImporter(store);
|
||||
var eight = new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero);
|
||||
async Task<List<ResearchBar>> Read(string venue, string series, string timeframe) =>
|
||||
await store.ReadAsync(venue, series, timeframe, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false);
|
||||
|
||||
var histdata = await importer.ImportAsync(Fixture.Path(HistDataFile), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, histdata.Count);
|
||||
Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "1m", 5, eight, eight.AddMinutes(15), histdata[0].Notes), histdata[0]);
|
||||
Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "15m", 2, eight, eight.AddMinutes(15), histdata[1].Notes), histdata[1]);
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 0m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 0m),
|
||||
}, await Read("histdata", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
Assert.AreEqual(eight, (await Read("histdata", "EURUSD-BID", "1m").ConfigureAwait(false))[0].OpensAt, "03:00 at UTC−5 is 08:00 UTC");
|
||||
Assert.IsTrue(histdata[0].Notes.Any(n => n.StartsWith(IssueKinds.Gap, StringComparison.Ordinal)), "the missing minutes are reported against the FX week");
|
||||
|
||||
var bid = await importer.ImportAsync(Fixture.Path(DukascopyBid), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual("dukascopy", bid[0].Venue);
|
||||
Assert.AreEqual("EURUSD-BID", bid[0].Symbol);
|
||||
Assert.AreEqual(5, bid[0].Bars, "the flat Saturday bar is left out");
|
||||
Assert.IsTrue(bid[0].Notes.Any(n => n.Contains("1 barre fuori dall'orario del mercato", StringComparison.Ordinal)), string.Join(" | ", bid[0].Notes));
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 35.25m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 7m),
|
||||
}, await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
|
||||
var ask = await importer.ImportAsync(Fixture.Path(DukascopyAsk), null, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual("EURUSD-ASK", ask[1].Symbol);
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
new ResearchBar(eight, 1.09462m, 1.09542m, 1.09422m, 1.09442m, 35.25m),
|
||||
new ResearchBar(eight.AddMinutes(15), 1.09442m, 1.09472m, 1.09432m, 1.09462m, 7m),
|
||||
}, await Read("dukascopy", "EURUSD-ASK", "15m").ConfigureAwait(false));
|
||||
|
||||
// The same minutes through the pure aggregator give the same bars.
|
||||
var minutes = await Read("dukascopy", "EURUSD-BID", "1m").ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(BarAggregator.Aggregate(minutes, Timeframes.Minutes15).ToList(), await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataFxWritesMinuteAndFifteenMinuteSeriesForBothFormats()
|
||||
{
|
||||
var data = TempFolder.Create("data-fx");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
using var output = new StringWriter();
|
||||
foreach (var file in new[] { HistDataFile, DukascopyBid, DukascopyAsk })
|
||||
{
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["fx", Fixture.Path(file), "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString());
|
||||
}
|
||||
|
||||
var text = output.ToString();
|
||||
StringAssert.Contains(text, "histdata EURUSD-BID 1m: 5 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC).");
|
||||
StringAssert.Contains(text, "histdata EURUSD-BID 15m: 2 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC).");
|
||||
StringAssert.Contains(text, "dukascopy EURUSD-ASK 15m: 2 barre");
|
||||
var series = new ResearchStore(Path.Combine(data, "research")).Series();
|
||||
CollectionAssert.AreEquivalent(new[]
|
||||
{
|
||||
("dukascopy", "EURUSD-ASK", "15m"), ("dukascopy", "EURUSD-ASK", "1m"), ("dukascopy", "EURUSD-BID", "15m"), ("dukascopy", "EURUSD-BID", "1m"),
|
||||
("histdata", "EURUSD-BID", "15m"), ("histdata", "EURUSD-BID", "1m"),
|
||||
}, series.ToArray());
|
||||
|
||||
// A HistData file renamed: the pair comes from --symbol.
|
||||
var renamed = Path.Combine(data, "import", "minuti.csv");
|
||||
File.Copy(Fixture.Path(HistDataFile), renamed);
|
||||
using var named = new StringWriter();
|
||||
Assert.AreEqual(0, await DataCommand.RunAsync(["fx", renamed, "--symbol", "gbpusd", "--platform", "docker", "--data-dir", data], named, env).ConfigureAwait(false), named.ToString());
|
||||
StringAssert.Contains(named.ToString(), "histdata GBPUSD-BID 15m: 2 barre");
|
||||
using var nameless = new StringWriter();
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["fx", renamed, "--platform", "docker", "--data-dir", data], nameless, env).ConfigureAwait(false));
|
||||
StringAssert.Contains(nameless.ToString(), "--symbol");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task DataFxRefusesAnUnknownFormatInItalian()
|
||||
{
|
||||
var data = TempFolder.Create("data-fx-unknown");
|
||||
try
|
||||
{
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
var metatrader = Path.Combine(data, "DAT_MT_EURUSD_M1_2024.csv");
|
||||
await File.WriteAllTextAsync(metatrader, "2024.01.01,17:00,1.104270,1.104290,1.104270,1.104290,0\n").ConfigureAwait(false);
|
||||
var local = Path.Combine(data, "EURUSD_Candlestick_1_M_BID_01.01.2024-31.12.2024.csv");
|
||||
await File.WriteAllTextAsync(local, "Local time,Open,High,Low,Close,Volume\n02.01.2024 09:00:00.000 GMT+0100,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false);
|
||||
var sideless = Path.Combine(data, "EURUSD_Candlestick_1_M_01.01.2024-31.12.2024.csv");
|
||||
await File.WriteAllTextAsync(sideless, "Gmt time,Open,High,Low,Close,Volume\n02.01.2024 08:00:00.000,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false);
|
||||
|
||||
foreach (var (file, words) in new[]
|
||||
{
|
||||
(metatrader, "Formato non riconosciuto"), (local, "ora locale"), (sideless, "_BID_"),
|
||||
})
|
||||
{
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(1, await DataCommand.RunAsync(["fx", file, "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString());
|
||||
StringAssert.StartsWith(output.ToString(), "Non riuscito: ");
|
||||
StringAssert.Contains(output.ToString(), words);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, new ResearchStore(Path.Combine(data, "research")).Series().Count, "nothing written");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task DataUsageListsTheNewCommandsAndTimeframes()
|
||||
{
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(2, await DataCommand.RunAsync(["nothing"], output, ServerHarness.DockerSqlite()).ConfigureAwait(false));
|
||||
var usage = output.ToString();
|
||||
StringAssert.Contains(usage, "<1d|1m|15m|30m|1h|4h|8h>");
|
||||
StringAssert.Contains(usage, "anubis data ecb [--offline]");
|
||||
StringAssert.Contains(usage, "anubis data fx <file.csv> [--symbol EURUSD]");
|
||||
}
|
||||
|
||||
// ---- CSV importer ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CsvParseIsPureAndReadsAFixedOffsetAllYear()
|
||||
{
|
||||
var mapping = new CsvMapping { Delimiter = ";", HasHeader = false, TimeFormat = "yyyyMMdd HHmmss", TimeZone = "UTC-05:00" };
|
||||
var parsed = CsvImporter.Parse(["20240102 030000;1;2;0.5;1.5;0", "", "20240702 030000;1;2;0.5;1.5;0", "20240703 0300;1;2;0.5;1.5;0"], mapping);
|
||||
|
||||
Assert.AreEqual(4, parsed.Lines);
|
||||
Assert.AreEqual(1, parsed.Errors);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[0].OpensAt);
|
||||
Assert.AreEqual(new DateTimeOffset(2024, 7, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[1].OpensAt, "no daylight saving: still 08:00 UTC in July");
|
||||
StringAssert.StartsWith(parsed.Notes[0], "riga 4: ");
|
||||
Assert.AreEqual("1 righe non lette su 4", parsed.Notes[^1]);
|
||||
Assert.AreEqual(TimeSpan.FromHours(5.5), CsvImporter.ZoneOf("UTC+05:30").BaseUtcOffset);
|
||||
Assert.AreEqual(TimeSpan.Zero, CsvImporter.ZoneOf("UTC").BaseUtcOffset);
|
||||
Assert.ThrowsExactly<TimeZoneNotFoundException>(() => CsvImporter.ZoneOf("Nowhere/Atlantis"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task CsvImporterChecksIntradayBarsAtTheirOwnLength()
|
||||
{
|
||||
var folder = TempFolder.Create("csv-15m");
|
||||
try
|
||||
{
|
||||
var csv = Path.Combine(folder, "btcusdt-15m.csv");
|
||||
await File.WriteAllTextAsync(csv,
|
||||
"time,open,high,low,close,volume\n" +
|
||||
"2024-01-02 00:00:00,100,101,99,100.5,1\n" +
|
||||
"2024-01-02 00:15:00,100.5,102,100,101,1\n" +
|
||||
"2024-01-02 00:45:00,101,103,100,102,1\n").ConfigureAwait(false);
|
||||
var mapping = new CsvMapping { Timeframe = Timeframes.Minutes15, TimeFormat = "yyyy-MM-dd HH:mm:ss" };
|
||||
var store = new ResearchStore(Path.Combine(folder, "research"));
|
||||
|
||||
var result = await new CsvImporter(store).ImportAsync(csv, mapping, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
Assert.AreEqual(3, result.Bars);
|
||||
Assert.IsFalse(result.Notes.Any(n => n.StartsWith(IssueKinds.Duplicate, StringComparison.Ordinal)), "three bars of one day are not duplicates: " + string.Join(" | ", result.Notes));
|
||||
Assert.AreEqual("gap 2024-01-02 00:30: Manca una barra da 15m", result.Notes.Single());
|
||||
Assert.AreEqual(3, (await store.ReadAsync("import", "BTCUSDT", "15m", DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false)).Count);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user