Add market data schema, catalogue, bar storage and quality checks (refs #18 #20 #21 #23)

Migration 0002 adds the market data tables on both engines: daily and
one-minute bars, corporate actions, FX rates, the exchange calendar,
calendar events, mood indicators, spread samples, data issues, source
state and universe members, plus the trading rules on instruments.

The data layer is format-independent so the venue clients can build on
it: the instrument catalogue (rules from the venue, delisted kept), bar
upserts with ON CONFLICT, the SPEC 6.4 checks with an issue register
that blocks entries until a second reading, freshness by age of the last
datum (trap 10), research history in .csv.gz with exact decimals, and
adjusted series anchored at the decision day with level and quantity
conversion across splits and dividends.

Recorded API responses from OKX, the Alpaca docs and the free sources
are kept byte for byte as test fixtures; the secret scan now ignores
pagination cursors such as Alpaca's next_page_token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 14:58:44 +01:00
1 parent 67350f091e
commit 3b13a4258d
54 files changed
+3067 -3

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
using System.Globalization;
namespace Anubis.Data;
/// <summary>
/// Adjusted series and the effect of corporate actions (SPEC 6.10, trap 9).
/// <list type="bullet">
/// <item>Signals use the adjusted series anchored at the decision day: its last price equals the real one, so
/// averages, highs and stop levels are already in today's prices.</item>
/// <item>A backtest that sees day t uses the final adjusted series rescaled so that day t matches the real price.</item>
/// <item>When an action hits a followed instrument, saved levels are converted with its factor; quantities change
/// only with splits and stock dividends.</item>
/// </list>
/// </summary>
public static class Adjustments
{
/// <summary>
/// The factor that brings prices before the ex-date in line with prices from the ex-date on: 1/ratio for a
/// split, (close − dividend) / close for a cash dividend, using the last real close before the ex-date.
/// </summary>
public static double PriceFactor(CorporateAction action, double? closeBeforeEx)
{
ArgumentNullException.ThrowIfNull(action);
if (action.ChangesShares)
{
return 1.0 / (double)action.Ratio!.Value;
}
if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is { } cash && closeBeforeEx is { } close && close > (double)cash && cash > 0)
{
return (close - (double)cash) / close;
}
return 1.0;
}
/// <summary>
/// The series as known on <paramref name="anchor"/>: bars up to that day, with <see cref="DailyBar.Adjusted"/>
/// computed from the real prices and the actions whose ex-date is not later than the anchor. The anchor bar's
/// adjusted prices equal its real ones. Actions after the anchor are ignored: on that day nobody knew them.
/// </summary>
public static IReadOnlyList<DailyBar> Anchored(IReadOnlyList<DailyBar> raw, IEnumerable<CorporateAction> actions, DateOnly anchor)
{
ArgumentNullException.ThrowIfNull(raw);
ArgumentNullException.ThrowIfNull(actions);
var bars = raw.Where(b => b.Day <= anchor).OrderBy(b => b.Day).ToList();
var known = actions.Where(a => a.ExDate <= anchor && a.ExDate > (bars.Count > 0 ? bars[0].Day : anchor)).OrderBy(a => a.ExDate).ToList();
var factors = known.Select(a =>
{
var before = bars.LastOrDefault(b => b.Day < a.ExDate);
return (a.ExDate, Price: PriceFactor(a, before?.Close), Shares: a.ChangesShares ? (double)a.Ratio!.Value : 1.0);
}).ToList();
var result = new List<DailyBar>(bars.Count);
foreach (var bar in bars)
{
double price = 1, shares = 1;
foreach (var f in factors.Where(f => f.ExDate > bar.Day))
{
price *= f.Price;
shares *= f.Shares;
}
result.Add(bar with { Adjusted = bar.Prices.Scale(price), Volume = bar.Volume * shares });
}
return result;
}
/// <summary>
/// The backtest view at day <paramref name="day"/>: the source's final adjusted series up to that day, rescaled
/// so that its price on that day equals the real one. Needs <see cref="DailyBar.Adjusted"/> on every bar.
/// </summary>
public static IReadOnlyList<Ohlc> RescaledAt(IReadOnlyList<DailyBar> bars, DateOnly day)
{
ArgumentNullException.ThrowIfNull(bars);
var upTo = bars.Where(b => b.Day <= day).OrderBy(b => b.Day).ToList();
if (upTo.Count == 0)
{
return [];
}
var last = upTo[^1];
var adjusted = last.Adjusted ?? throw new InvalidOperationException("Bar without adjusted prices: " + last.Day);
var factor = last.Close / adjusted.Close;
return upTo.Select(b => (b.Adjusted ?? throw new InvalidOperationException("Bar without adjusted prices: " + b.Day)).Scale(factor)).ToList();
}
/// <summary>
/// Converts a saved level (entry price, highest close, stop) across an action: a stop at 100 before a 2-for-1
/// split becomes 50. <paramref name="closeBeforeEx"/> is needed for cash dividends.
/// </summary>
public static decimal ConvertLevel(decimal level, CorporateAction action, decimal? closeBeforeEx)
{
ArgumentNullException.ThrowIfNull(action);
if (action.ChangesShares)
{
return level / action.Ratio!.Value;
}
if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is { } cash && closeBeforeEx is { } close && close > cash && cash > 0)
{
return level * (close - cash) / close;
}
return level;
}
/// <summary>Quantity held after the action: only splits and stock dividends change it (SPEC 6.10).</summary>
public static decimal ConvertQuantity(decimal quantity, CorporateAction action)
{
ArgumentNullException.ThrowIfNull(action);
return action.ChangesShares ? quantity * action.Ratio!.Value : quantity;
}
/// <summary>
/// Recognises actions from the jump in the ratio between the real and the adjusted series, for when the
/// corporate actions endpoint is not available (SPEC 4.1). A jump close to a simple ratio (2, 3, 1/10…) is a
/// split; a small one is a cash dividend.
/// </summary>
public static IReadOnlyList<CorporateAction> Detect(string symbol, IReadOnlyList<DailyBar> bars, double tolerance = 0.002)
{
ArgumentNullException.ThrowIfNull(bars);
var found = new List<CorporateAction>();
var series = bars.Where(b => b.Adjusted is { Close: > 0 } && b.Close > 0).OrderBy(b => b.Day).ToList();
for (var i = 1; i < series.Count; i++)
{
var before = series[i - 1].Adjusted!.Value.Close / series[i - 1].Close;
var after = series[i].Adjusted!.Value.Close / series[i].Close;
// The adjusted/real ratio is constant between actions; from the ex-date on it is multiplied by the inverse factor.
var change = after / before;
if (Math.Abs(change - 1) <= tolerance)
{
continue;
}
var day = series[i].Day;
var key = $"detected:{symbol}:{day:yyyy-MM-dd}";
var ratio = SimpleRatio(change, tolerance);
if (ratio is { } r)
{
found.Add(new CorporateAction(symbol, CorporateActionKinds.Split, day, "detected", key) { Ratio = r });
}
else if (change > 1 && change < 1.25)
{
// Prices before the ex-date were multiplied by f = 1/change: dividend = close before × (1 − f).
var dividend = series[i - 1].Close * (1 - (1 / change));
found.Add(new CorporateAction(symbol, CorporateActionKinds.CashDividend, day, "detected", key)
{
CashAmount = Math.Round((decimal)dividend, 4),
});
}
}
return found;
}
/// <summary>A split ratio n or 1/n (n from 2 to 50), or 3/2, 5/4, 4/3, 2/3…, matching <paramref name="value"/>.</summary>
private static decimal? SimpleRatio(double value, double tolerance)
{
for (var n = 2; n <= 50; n++)
{
if (Math.Abs(value - n) <= tolerance * n)
{
return n;
}
if (Math.Abs(value - (1.0 / n)) <= tolerance / n)
{
return decimal.Parse((1.0m / n).ToString("0.##########", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
}
foreach (var (num, den) in new[] { (3, 2), (5, 4), (4, 3), (5, 2), (2, 3), (4, 5), (3, 4), (2, 5) })
{
if (Math.Abs(value - ((double)num / den)) <= tolerance * num / den)
{
return (decimal)num / den;
}
}
return null;
}
}
+136
View File
@@ -0,0 +1,136 @@
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Data;
/// <summary>
/// Daily and one-minute bars in the database (SPEC 5.4, 6.2). Writes are upserts on (instrument, day) and
/// (instrument, minute) with <c>ON CONFLICT</c>, which both engines understand. The research history lives in
/// files instead (<see cref="ResearchStore"/>).
/// </summary>
public sealed class BarStore(Database db, IClock clock)
{
/// <summary>One-minute bars are kept this long (SPEC 5.4).</summary>
public static readonly TimeSpan MinuteRetention = TimeSpan.FromDays(400);
public const string DayFormat = "yyyy-MM-dd";
public static string DayText(DateOnly day) => day.ToString(DayFormat, CultureInfo.InvariantCulture);
public static DateOnly ParseDay(string text) => DateOnly.ParseExact(text, DayFormat, CultureInfo.InvariantCulture);
public async Task<int> UpsertDailyAsync(Guid instrumentId, IEnumerable<DailyBar> bars, string source, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(bars);
var list = bars.ToList();
if (list.Count == 0)
{
return 0;
}
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
foreach (var bar in list)
{
await s.ExecuteAsync(
"INSERT INTO bars_1d (id, instrument_id, day, open, high, low, close, volume, quote_volume, adj_open, adj_high, adj_low, adj_close, " +
"source, quality, created_at, updated_at) VALUES (@id, @i, @d, @o, @h, @l, @c, @v, @qv, @ao, @ah, @al, @ac, @src, @q, @now, @now) " +
"ON CONFLICT (instrument_id, day) DO UPDATE SET open = excluded.open, high = excluded.high, low = excluded.low, close = excluded.close, " +
"volume = excluded.volume, quote_volume = excluded.quote_volume, adj_open = excluded.adj_open, adj_high = excluded.adj_high, " +
"adj_low = excluded.adj_low, adj_close = excluded.adj_close, source = excluded.source, quality = excluded.quality, updated_at = excluded.updated_at",
cancellationToken,
("id", Ids.NewId(clock)), ("i", instrumentId), ("d", DayText(bar.Day)), ("o", bar.Open), ("h", bar.High), ("l", bar.Low), ("c", bar.Close),
("v", bar.Volume), ("qv", bar.QuoteVolume), ("ao", bar.Adjusted?.Open), ("ah", bar.Adjusted?.High), ("al", bar.Adjusted?.Low),
("ac", bar.Adjusted?.Close), ("src", source), ("q", bar.Quality), ("now", now)).ConfigureAwait(false);
}
return list.Count;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Daily bars from <paramref name="from"/> to <paramref name="to"/>, both included, oldest first.</summary>
public async Task<IReadOnlyList<DailyBar>> DailyAsync(Guid instrumentId, DateOnly from, DateOnly to, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT day, open, high, low, close, volume, quote_volume, adj_open, adj_high, adj_low, adj_close, quality FROM bars_1d " +
"WHERE instrument_id = @i AND day >= @f AND day <= @t ORDER BY day",
ReadDaily, ("i", instrumentId), ("f", DayText(from)), ("t", DayText(to))), cancellationToken).ConfigureAwait(false);
public async Task<DateOnly?> LastDayAsync(Guid instrumentId, CancellationToken cancellationToken)
{
var text = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MAX(day) AS d FROM bars_1d WHERE instrument_id = @i",
r => r.TextOrNull("d"), ("i", instrumentId)), cancellationToken).ConfigureAwait(false);
return text is null ? null : ParseDay(text);
}
public async Task<DateOnly?> FirstDayAsync(Guid instrumentId, CancellationToken cancellationToken)
{
var text = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(day) AS d FROM bars_1d WHERE instrument_id = @i",
r => r.TextOrNull("d"), ("i", instrumentId)), cancellationToken).ConfigureAwait(false);
return text is null ? null : ParseDay(text);
}
public Task<long> CountDailyAsync(Guid instrumentId, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM bars_1d WHERE instrument_id = @i", ("i", instrumentId)), cancellationToken);
public Task SetDailyQualityAsync(Guid instrumentId, DateOnly day, string quality, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE bars_1d SET quality = @q, updated_at = @now WHERE instrument_id = @i AND day = @d", cancellationToken,
("q", quality), ("now", clock.UtcNow), ("i", instrumentId), ("d", DayText(day))), cancellationToken);
public Task DeleteDailyAsync(Guid instrumentId, DateOnly day, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("DELETE FROM bars_1d WHERE instrument_id = @i AND day = @d", cancellationToken,
("i", instrumentId), ("d", DayText(day))), cancellationToken);
public async Task<int> UpsertMinuteAsync(Guid instrumentId, IEnumerable<Bar> bars, string source, string quality, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(bars);
var list = bars.ToList();
if (list.Count == 0)
{
return 0;
}
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
foreach (var bar in list)
{
await s.ExecuteAsync(
"INSERT INTO bars_1m (id, instrument_id, opens_at, open, high, low, close, volume, source, quality, created_at) " +
"VALUES (@id, @i, @t, @o, @h, @l, @c, @v, @src, @q, @now) " +
"ON CONFLICT (instrument_id, opens_at) DO UPDATE SET open = excluded.open, high = excluded.high, low = excluded.low, " +
"close = excluded.close, volume = excluded.volume, source = excluded.source, quality = excluded.quality",
cancellationToken,
("id", Ids.NewId(clock)), ("i", instrumentId), ("t", bar.OpensAt), ("o", bar.Open), ("h", bar.High), ("l", bar.Low), ("c", bar.Close),
("v", bar.Volume), ("src", source), ("q", quality), ("now", now)).ConfigureAwait(false);
}
return list.Count;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>One-minute bars opening from <paramref name="from"/> (included) to <paramref name="to"/> (excluded), oldest first.</summary>
public async Task<IReadOnlyList<Bar>> MinuteAsync(Guid instrumentId, DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync(
"SELECT opens_at, open, high, low, close, volume FROM bars_1m WHERE instrument_id = @i AND opens_at >= @f AND opens_at < @t ORDER BY opens_at",
r => new Bar(r.Moment("opens_at"), r.Measure("open"), r.Measure("high"), r.Measure("low"), r.Measure("close"), r.Measure("volume")),
("i", instrumentId), ("f", from), ("t", to)), cancellationToken).ConfigureAwait(false);
public Task<DateTimeOffset?> LastMinuteAsync(Guid instrumentId, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT opens_at FROM bars_1m WHERE instrument_id = @i ORDER BY opens_at DESC",
r => (DateTimeOffset?)r.Moment("opens_at"), ("i", instrumentId)), cancellationToken);
/// <summary>Deletes one-minute bars older than the retention (SPEC 5.4). Returns how many went.</summary>
public Task<int> PruneMinutesAsync(CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("DELETE FROM bars_1m WHERE opens_at < @t", cancellationToken, ("t", clock.UtcNow - MinuteRetention)),
cancellationToken);
private static DailyBar ReadDaily(DbRow r) =>
new(ParseDay(r.Text("day")), r.Measure("open"), r.Measure("high"), r.Measure("low"), r.Measure("close"), r.Measure("volume"))
{
QuoteVolume = r.IsNull("quote_volume") ? null : r.Measure("quote_volume"),
Adjusted = r.IsNull("adj_close") ? null : new Ohlc(r.Measure("adj_open"), r.Measure("adj_high"), r.Measure("adj_low"), r.Measure("adj_close")),
Quality = r.Text("quality"),
};
}
+80
View File
@@ -0,0 +1,80 @@
using System.Collections.Concurrent;
using Anubis.Core;
namespace Anubis.Data;
/// <summary>Published when an instrument's live data become stale or fresh again (SPEC 6.5).</summary>
public sealed record FreshnessChanged(Guid InstrumentId, string Symbol, bool Fresh, DateTimeOffset? LastDataAt, DateTimeOffset At);
/// <summary>
/// Watches the age of the last live datum of each followed instrument, not the state of the connection (trap 10):
/// a feed that stays connected but stops sending is stale after <see cref="MaxAge"/>, and risk blocks new entries
/// on that instrument (SPEC 6.5, 9.2). Exits and stops are never blocked by this.
/// </summary>
public sealed class FreshnessMonitor(IClock clock, EventBus bus, TimeSpan? maxAge = null)
{
/// <summary>Maximum age of live prices (SPEC 6.5).</summary>
public static readonly TimeSpan DefaultMaxAge = TimeSpan.FromSeconds(60);
private readonly ConcurrentDictionary<Guid, Entry> _entries = new();
public TimeSpan MaxAge { get; } = maxAge ?? DefaultMaxAge;
public sealed record Status(Guid InstrumentId, string Symbol, DateTimeOffset? LastDataAt, bool Fresh, TimeSpan? Age);
private sealed record Entry(string Symbol, DateTimeOffset FollowedSince, DateTimeOffset? LastDataAt, bool Fresh);
/// <summary>Starts watching an instrument. Until its first datum it counts as stale.</summary>
public void Follow(Guid instrumentId, string symbol) =>
_entries.TryAdd(instrumentId, new Entry(symbol, clock.UtcNow, null, false));
public void Unfollow(Guid instrumentId) => _entries.TryRemove(instrumentId, out _);
public IReadOnlyCollection<Guid> Followed => _entries.Keys.ToList();
/// <summary>A datum arrived. <paramref name="dataAt"/> is the venue's time; the age counts from when it arrived here if that is earlier.</summary>
public void Touch(Guid instrumentId, DateTimeOffset dataAt)
{
var now = clock.UtcNow;
var seen = dataAt > now ? now : dataAt;
if (!_entries.TryGetValue(instrumentId, out var entry))
{
return;
}
var updated = entry with { LastDataAt = entry.LastDataAt is { } last && last > seen ? last : seen };
var fresh = IsFresh(updated, now);
_entries[instrumentId] = updated with { Fresh = fresh };
if (fresh && !entry.Fresh)
{
bus.Publish(new FreshnessChanged(instrumentId, entry.Symbol, true, updated.LastDataAt, now));
}
}
/// <summary>Re-evaluates every instrument and publishes the changes. Called every few seconds by the collector.</summary>
public void Check()
{
var now = clock.UtcNow;
foreach (var (id, entry) in _entries)
{
var fresh = IsFresh(entry, now);
if (fresh != entry.Fresh)
{
_entries[id] = entry with { Fresh = fresh };
bus.Publish(new FreshnessChanged(id, entry.Symbol, fresh, entry.LastDataAt, now));
}
}
}
/// <summary>Whether new entries may use this instrument's live prices now.</summary>
public bool IsFresh(Guid instrumentId) => _entries.TryGetValue(instrumentId, out var entry) && IsFresh(entry, clock.UtcNow);
public IReadOnlyList<Status> Snapshot()
{
var now = clock.UtcNow;
return _entries.Select(e => new Status(e.Key, e.Value.Symbol, e.Value.LastDataAt, IsFresh(e.Value, now), now - e.Value.LastDataAt))
.OrderBy(s => s.Symbol, StringComparer.Ordinal).ToList();
}
private bool IsFresh(Entry entry, DateTimeOffset now) => entry.LastDataAt is { } last && now - last <= MaxAge;
}
+126
View File
@@ -0,0 +1,126 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Data;
/// <summary>
/// The single instrument catalogue (SPEC 6.1): internal id, venue, venue symbol, class, currency, tick, lot, minimum
/// and status, refreshed every day from the venues. An instrument the venue stops listing is kept, marked
/// <c>delisted</c>: its history and the orders that used it still point to it.
/// </summary>
public sealed class InstrumentCatalog(Database db, IClock clock)
{
public const string Delisted = "delisted";
private const string Columns =
"id, venue, symbol, name, asset_class, quote_currency, base_currency, exchange, tick_size, lot_size, min_size, min_notional, " +
"status, fractionable, is_fund, listed_at, updated_at";
public sealed record SyncResult(int Added, int Updated, int Delisted);
/// <summary>
/// Writes what the venue listed today. With <paramref name="complete"/> the list is the venue's whole catalogue
/// and instruments missing from it become delisted.
/// </summary>
public async Task<SyncResult> SyncAsync(string venue, IReadOnlyCollection<InstrumentSpec> specs, bool complete, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(specs);
if (specs.Any(s => s.Venue != venue))
{
throw new ArgumentException("Every instrument must belong to " + venue, nameof(specs));
}
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
var existing = (await s.QueryAsync($"SELECT {Columns} FROM instruments WHERE venue = @v", Read, ("v", venue)).ConfigureAwait(false))
.ToDictionary(i => i.Symbol, StringComparer.Ordinal);
int added = 0, updated = 0, delisted = 0;
foreach (var spec in specs.DistinctBy(x => x.Symbol))
{
if (existing.Remove(spec.Symbol, out var known))
{
if (known.Spec != spec)
{
await s.ExecuteAsync(
"UPDATE instruments SET name = @name, asset_class = @class, quote_currency = @quote, base_currency = @base, exchange = @exchange, " +
"tick_size = @tick, lot_size = @lot, min_size = @min, min_notional = @notional, status = @status, fractionable = @fractionable, " +
"is_fund = @fund, listed_at = @listed, updated_at = @now WHERE id = @id",
cancellationToken, [.. Parameters(spec), ("now", now), ("id", known.Id)]).ConfigureAwait(false);
updated++;
}
}
else
{
await s.ExecuteAsync(
$"INSERT INTO instruments ({Columns}, created_at) VALUES (@id, @venue, @symbol, @name, @class, @quote, @base, @exchange, @tick, @lot, @min, @notional, " +
"@status, @fractionable, @fund, @listed, @now, @now)",
cancellationToken, [.. Parameters(spec), ("id", Ids.NewId(clock)), ("venue", venue), ("symbol", spec.Symbol), ("now", now)]).ConfigureAwait(false);
added++;
}
}
if (complete)
{
foreach (var missing in existing.Values.Where(i => i.Spec.Status != Delisted))
{
await s.ExecuteAsync("UPDATE instruments SET status = @status, updated_at = @now WHERE id = @id", cancellationToken,
("status", Delisted), ("now", now), ("id", missing.Id)).ConfigureAwait(false);
delisted++;
}
}
return new SyncResult(added, updated, delisted);
}, cancellationToken).ConfigureAwait(false);
}
public Task<Instrument?> FindAsync(string venue, string symbol, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM instruments WHERE venue = @v AND symbol = @s", Read, ("v", venue), ("s", symbol)),
cancellationToken);
public Task<Instrument?> GetAsync(Guid id, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.FirstOrDefaultAsync($"SELECT {Columns} FROM instruments WHERE id = @id", Read, ("id", id)), cancellationToken);
public async Task<IReadOnlyList<Instrument>> ListAsync(string? venue, CancellationToken cancellationToken) =>
await db.ReadAsync(s => venue is null
? s.QueryAsync($"SELECT {Columns} FROM instruments ORDER BY venue, symbol", Read)
: s.QueryAsync($"SELECT {Columns} FROM instruments WHERE venue = @v ORDER BY symbol", Read, ("v", venue)),
cancellationToken).ConfigureAwait(false);
/// <summary>Finds or creates an instrument known only by name, for the research importers and tests.</summary>
public async Task<Instrument> EnsureAsync(InstrumentSpec spec, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(spec);
if (await FindAsync(spec.Venue, spec.Symbol, cancellationToken).ConfigureAwait(false) is { } known)
{
return known;
}
await SyncAsync(spec.Venue, [spec], complete: false, cancellationToken).ConfigureAwait(false);
return (await FindAsync(spec.Venue, spec.Symbol, cancellationToken).ConfigureAwait(false))!;
}
private static (string, object?)[] Parameters(InstrumentSpec spec) =>
[
("name", spec.Name), ("class", spec.AssetClass), ("quote", spec.QuoteCurrency), ("base", spec.BaseCurrency), ("exchange", spec.Exchange),
("tick", spec.TickSize), ("lot", spec.LotSize), ("min", spec.MinSize), ("notional", spec.MinNotional), ("status", spec.Status),
("fractionable", spec.Fractionable), ("fund", spec.IsFund), ("listed", spec.ListedAt),
];
private static Instrument Read(DbRow r) => new(
r.Id("id"),
new InstrumentSpec(r.Text("venue"), r.Text("symbol"), r.Text("name"), r.Text("asset_class"), r.Text("quote_currency"))
{
BaseCurrency = r.TextOrNull("base_currency"),
Exchange = r.TextOrNull("exchange"),
TickSize = r.MoneyOrNull("tick_size"),
LotSize = r.MoneyOrNull("lot_size"),
MinSize = r.MoneyOrNull("min_size"),
MinNotional = r.MoneyOrNull("min_notional"),
Status = r.TextOrNull("status"),
Fractionable = r.IsNull("fractionable") ? null : r.Bool("fractionable"),
IsFund = r.IsNull("is_fund") ? null : r.Bool("is_fund"),
ListedAt = r.MomentOrNull("listed_at"),
},
r.MomentOrNull("updated_at"));
}
+163
View File
@@ -0,0 +1,163 @@
namespace Anubis.Data;
/// <summary>Where data and orders come from. The value is stored in <c>instruments.venue</c>.</summary>
public static class Venues
{
public const string Okx = "okx";
public const string Alpaca = "alpaca";
/// <summary>Research archives only (data.binance.vision): never a venue for orders (SPEC 4.2).</summary>
public const string Binance = "binance";
}
public static class AssetClasses
{
public const string Crypto = "crypto";
public const string Equity = "equity";
}
/// <summary>Quality of a stored bar (SPEC 6.4).</summary>
public static class BarQuality
{
/// <summary>Passed every check.</summary>
public const string Ok = "ok";
/// <summary>Failed a check and waits for a second reading: no entries on the instrument meanwhile.</summary>
public const string Suspect = "suspect";
/// <summary>Failed a check, but a second reading gave the same values: a real move, usable.</summary>
public const string Confirmed = "confirmed";
}
/// <summary>
/// An instrument as the venue describes it (SPEC 6.1): trading rules come from the API every day, never from code.
/// <paramref name="Symbol"/> is the venue's own identifier: <c>BTC-EUR</c> on OKX, <c>AAPL</c> on Alpaca.
/// </summary>
public sealed record InstrumentSpec(
string Venue,
string Symbol,
string Name,
string AssetClass,
string QuoteCurrency)
{
public string? BaseCurrency { get; init; }
/// <summary>Listing exchange for stocks (NYSE, NASDAQ, ARCA…); null for crypto.</summary>
public string? Exchange { get; init; }
public decimal? TickSize { get; init; }
public decimal? LotSize { get; init; }
public decimal? MinSize { get; init; }
public decimal? MinNotional { get; init; }
/// <summary>The venue's own word: <c>live</c>, <c>suspend</c>, <c>active</c>, <c>inactive</c>…</summary>
public string? Status { get; init; }
public bool? Fractionable { get; init; }
/// <summary>ETF, ETN or fund: never bought, at most used as an indicator (SPEC 4.6).</summary>
public bool? IsFund { get; init; }
public DateTimeOffset? ListedAt { get; init; }
}
/// <summary>An instrument of the catalogue: the internal id and what the venue said the last time it was read.</summary>
public sealed record Instrument(Guid Id, InstrumentSpec Spec, DateTimeOffset? UpdatedAt)
{
public string Venue => Spec.Venue;
public string Symbol => Spec.Symbol;
public string AssetClass => Spec.AssetClass;
public bool IsCrypto => Spec.AssetClass == AssetClasses.Crypto;
/// <summary>The instrument is tradable today, as far as the venue says.</summary>
public bool IsLive => Spec.Status is null or "live" or "active";
}
/// <summary>
/// A bar of a given length that opens at <paramref name="OpensAt"/> (UTC). Bars are analysis data and stay
/// floating point (SPEC 5.4).
/// </summary>
public sealed record Bar(DateTimeOffset OpensAt, double Open, double High, double Low, double Close, double Volume)
{
/// <summary>Traded value in the quote currency, when the source gives it (OKX <c>volCcyQuote</c>).</summary>
public double? QuoteVolume { get; init; }
}
/// <summary>
/// A daily bar. <paramref name="Day"/> is the exchange date for stocks and the UTC date for crypto: a crypto day
/// opens at 00:00 UTC and closes at the next 00:00 UTC (trap 23).
/// </summary>
public sealed record DailyBar(DateOnly Day, double Open, double High, double Low, double Close, double Volume)
{
public double? QuoteVolume { get; init; }
/// <summary>Prices adjusted for splits and dividends as the source gave them (stocks only).</summary>
public Ohlc? Adjusted { get; init; }
public string Quality { get; init; } = BarQuality.Ok;
public Ohlc Prices => new(Open, High, Low, Close);
}
public readonly record struct Ohlc(double Open, double High, double Low, double Close)
{
public Ohlc Scale(double factor) => new(Open * factor, High * factor, Low * factor, Close * factor);
}
/// <summary>Best bid and ask: prices orders may use, so they are exact.</summary>
public sealed record Quote(string Symbol, decimal Bid, decimal Ask, DateTimeOffset At)
{
public decimal? BidSize { get; init; }
public decimal? AskSize { get; init; }
public decimal Mid => (Bid + Ask) / 2m;
/// <summary>Spread in basis points of the mid price; null when the book is empty or crossed.</summary>
public double? SpreadBp => Bid > 0 && Ask >= Bid ? (double)((Ask - Bid) / Mid * 10_000m) : null;
}
/// <summary>Something a live feed delivered. <see cref="At"/> is the moment the venue gives, in UTC.</summary>
public abstract record MarketEvent(string Symbol, DateTimeOffset At);
public sealed record TradeEvent(string Symbol, DateTimeOffset At, decimal Price, decimal Size) : MarketEvent(Symbol, At);
public sealed record QuoteEvent(Quote Quote) : MarketEvent(Quote.Symbol, Quote.At);
/// <summary>A one-minute bar. <see cref="Closed"/> is false while the minute is still running.</summary>
public sealed record BarEvent(string Symbol, Bar Bar, bool Closed) : MarketEvent(Symbol, Bar.OpensAt);
/// <summary>Kinds of corporate action (SPEC 6.10).</summary>
public static class CorporateActionKinds
{
/// <summary>Forward or reverse split: <c>ratio</c> new shares for each old one (2 = 2-for-1, 0.1 = 1-for-10).</summary>
public const string Split = "split";
public const string CashDividend = "cash_dividend";
/// <summary>Dividend paid in shares: treated like a split with its ratio.</summary>
public const string StockDividend = "stock_dividend";
public const string SymbolChange = "symbol_change";
}
/// <summary>A corporate action. <paramref name="SourceKey"/> identifies it at the source, so a second reading does not add it twice.</summary>
public sealed record CorporateAction(string Symbol, string Kind, DateOnly ExDate, string Source, string SourceKey)
{
public decimal? Ratio { get; init; }
public decimal? CashAmount { get; init; }
public string? Currency { get; init; }
public string? NewSymbol { get; init; }
/// <summary>A split, reverse split or stock dividend: quantities and per-share levels change.</summary>
public bool ChangesShares => Kind is CorporateActionKinds.Split or CorporateActionKinds.StockDividend && Ratio is > 0m;
}
+301
View File
@@ -0,0 +1,301 @@
using System.Globalization;
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Data;
/// <summary>What the data checks look for (SPEC 6.3, 6.4).</summary>
public static class IssueKinds
{
public const string Duplicate = "duplicate";
public const string Gap = "gap";
public const string NonPositive = "non_positive";
public const string HighBelowLow = "high_below_low";
public const string Jump = "jump";
public const string Stale = "stale";
/// <summary>Kinds that make a bar suspect: no entries until a second reading (SPEC 6.4).</summary>
public static bool MakesSuspect(string kind) => kind is NonPositive or HighBelowLow or Jump or Duplicate;
}
public static class IssueStatus
{
public const string Open = "open";
/// <summary>A gap filled by a later download.</summary>
public const string Recovered = "recovered";
/// <summary>A gap the source cannot fill, or an impossible bar confirmed by the source: recorded and left out.</summary>
public const string Unrecoverable = "unrecoverable";
/// <summary>A second reading gave the same values: a real move.</summary>
public const string Confirmed = "confirmed";
/// <summary>A second reading gave different values, which replaced the first ones.</summary>
public const string Corrected = "corrected";
}
public static class Timeframes
{
public const string Day = "1d";
public const string Minute = "1m";
}
/// <summary>A problem found in a series. Moments are UTC; for daily bars they are the day at 00:00 UTC.</summary>
public sealed record QualityFinding(string Kind, DateTimeOffset StartsAt, DateTimeOffset EndsAt, string Detail);
/// <summary>
/// The automatic checks of SPEC 6.4, as pure functions over a series: duplicates, gaps against the expected
/// moments, null or negative prices, high below low, and jumps over 8 standard deviations of the previous returns.
/// </summary>
public static class QualityChecks
{
public const double JumpSigmas = 8;
/// <summary>Returns before the bar that give the standard deviation of the jump check.</summary>
public const int JumpWindow = 60;
/// <summary>Fewer returns than this and the jump check is skipped: the deviation would mean little.</summary>
public const int JumpMinimum = 20;
public static IReadOnlyList<QualityFinding> CheckDaily(IReadOnlyList<DailyBar> bars, IEnumerable<DateOnly>? expectedDays = null)
{
ArgumentNullException.ThrowIfNull(bars);
var findings = new List<QualityFinding>();
foreach (var group in bars.GroupBy(b => b.Day).Where(g => g.Count() > 1))
{
var at = Midnight(group.Key);
var distinct = group.Select(b => b.Prices).Distinct().Count();
findings.Add(new QualityFinding(IssueKinds.Duplicate, at, at,
$"{group.Count()} barre per lo stesso giorno" + (distinct > 1 ? ", con valori diversi" : ", identiche")));
}
var unique = bars.DistinctBy(b => b.Day).OrderBy(b => b.Day).ToList();
foreach (var bar in unique)
{
CheckPrices(Midnight(bar.Day), bar.Open, bar.High, bar.Low, bar.Close, findings);
}
// Splits and dividends would look like jumps on real prices: stocks are checked on their adjusted closes.
var closes = unique.Select(b => b.Adjusted?.Close ?? b.Close).ToList();
foreach (var (index, detail) in Jumps(closes))
{
var at = Midnight(unique[index].Day);
findings.Add(new QualityFinding(IssueKinds.Jump, at, at, detail));
}
if (expectedDays is not null && unique.Count > 0)
{
var have = unique.Select(b => Midnight(b.Day)).ToHashSet();
foreach (var run in MissingRuns(expectedDays.Select(Midnight), have, Midnight(unique[0].Day), Midnight(unique[^1].Day)))
{
findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last,
run.Count == 1 ? "Manca la barra di un giorno" : $"Mancano le barre di {run.Count} giorni"));
}
}
return findings;
}
/// <summary>
/// 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)
{
ArgumentNullException.ThrowIfNull(bars);
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"));
}
var unique = bars.DistinctBy(b => b.OpensAt).OrderBy(b => b.OpensAt).ToList();
foreach (var bar in unique)
{
CheckPrices(bar.OpensAt, bar.Open, bar.High, bar.Low, bar.Close, findings);
}
foreach (var (index, detail) in Jumps(unique.Select(b => b.Close).ToList()))
{
findings.Add(new QualityFinding(IssueKinds.Jump, unique[index].OpensAt, unique[index].OpensAt, detail));
}
if (expected is not null && unique.Count > 0)
{
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"));
}
}
return findings;
}
/// <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)
{
for (var t = from; t < to; t = t.AddMinutes(1))
{
yield return t;
}
}
public static IEnumerable<DateOnly> EveryDay(DateOnly from, DateOnly to)
{
for (var d = from; d <= to; d = d.AddDays(1))
{
yield return d;
}
}
public static DateTimeOffset Midnight(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
private static void CheckPrices(DateTimeOffset at, double open, double high, double low, double close, List<QualityFinding> findings)
{
if (open <= 0 || high <= 0 || low <= 0 || close <= 0 || !double.IsFinite(open + high + low + close))
{
findings.Add(new QualityFinding(IssueKinds.NonPositive, at, at, "Prezzo nullo, negativo o non valido"));
}
else if (high < low || high < Math.Max(open, close) || low > Math.Min(open, close))
{
findings.Add(new QualityFinding(IssueKinds.HighBelowLow, at, at,
string.Create(CultureInfo.InvariantCulture, $"Massimo {high} e minimo {low} incoerenti con apertura {open} e chiusura {close}")));
}
}
/// <summary>Log returns further than 8 deviations from the mean of the previous 60.</summary>
private static IEnumerable<(int Index, string Detail)> Jumps(List<double> closes)
{
var returns = new double[closes.Count];
for (var i = 1; i < closes.Count; i++)
{
returns[i] = closes[i] > 0 && closes[i - 1] > 0 ? Math.Log(closes[i] / closes[i - 1]) : double.NaN;
}
for (var i = JumpMinimum + 1; i < closes.Count; i++)
{
var window = returns.Skip(Math.Max(1, i - JumpWindow)).Take(i - Math.Max(1, i - JumpWindow)).Where(double.IsFinite).ToList();
if (window.Count < JumpMinimum || !double.IsFinite(returns[i]))
{
continue;
}
var mean = window.Average();
var sigma = Math.Sqrt(window.Sum(r => (r - mean) * (r - mean)) / (window.Count - 1));
if (sigma > 0 && Math.Abs(returns[i] - mean) > JumpSigmas * sigma)
{
yield return (i, string.Create(CultureInfo.InvariantCulture,
$"Variazione del {(Math.Exp(returns[i]) - 1) * 100:0.##}% pari a {Math.Abs(returns[i] - mean) / sigma:0.#} deviazioni standard"));
}
}
}
/// <summary>
/// Expected moments between <paramref name="first"/> and <paramref name="last"/> with no bar, grouped in runs of
/// consecutive expected moments: a weekend between two missing sessions does not split the gap.
/// </summary>
private static List<(DateTimeOffset First, DateTimeOffset Last, int Count)> MissingRuns(
IEnumerable<DateTimeOffset> expected, HashSet<DateTimeOffset> have, DateTimeOffset first, DateTimeOffset last)
{
var runs = new List<(DateTimeOffset, DateTimeOffset, int)>();
(DateTimeOffset First, DateTimeOffset Last, int Count)? current = null;
foreach (var moment in expected.Where(t => t >= first && t <= last).Distinct().Order())
{
if (have.Contains(moment))
{
if (current is { } done)
{
runs.Add(done);
current = null;
}
}
else
{
current = current is { } run ? (run.First, moment, run.Count + 1) : (moment, moment, 1);
}
}
if (current is { } tail)
{
runs.Add(tail);
}
return runs;
}
}
/// <summary>A row of <c>data_issues</c>.</summary>
public sealed record DataIssue(
Guid Id, Guid? InstrumentId, string Timeframe, string Kind, DateTimeOffset StartsAt, DateTimeOffset EndsAt,
string Status, int Attempts, string Detail, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt);
/// <summary>
/// The register of what the checks found (SPEC 6.3, 6.4). Nothing is corrected in silence: every gap, suspect
/// bar and second reading leaves a row here, and the quality report reads it.
/// </summary>
public sealed class DataIssueStore(Database db, IClock clock)
{
private const string Columns = "id, instrument_id, timeframe, kind, starts_at, ends_at, status, attempts, detail, created_at, updated_at";
/// <summary>Records a finding unless the same one (instrument, timeframe, kind, start) is already open. Returns its id.</summary>
public async Task<Guid> RecordAsync(Guid? instrumentId, string timeframe, QualityFinding finding, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(finding);
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
(string, object?)[] args = [("tf", timeframe), ("k", finding.Kind), ("s", finding.StartsAt), ("open", IssueStatus.Open)];
var existing = await s.FirstOrDefaultAsync(
"SELECT id FROM data_issues WHERE " + (instrumentId is null ? "instrument_id IS NULL" : "instrument_id = @i") +
" AND timeframe = @tf AND kind = @k AND starts_at = @s AND status = @open",
r => (Guid?)r.Id("id"), instrumentId is null ? args : [.. args, ("i", instrumentId)]).ConfigureAwait(false);
if (existing is { } id)
{
return id;
}
id = Ids.NewId(clock);
await s.ExecuteAsync(
$"INSERT INTO data_issues ({Columns}) VALUES (@id, @i, @tf, @k, @s, @e, @open, 0, @d, @now, @now)", cancellationToken,
("id", id), ("i", instrumentId), ("tf", timeframe), ("k", finding.Kind), ("s", finding.StartsAt), ("e", finding.EndsAt),
("open", IssueStatus.Open), ("d", finding.Detail), ("now", now)).ConfigureAwait(false);
return id;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Counts one more attempt at fixing an open issue (a download, a second reading).</summary>
public Task AttemptAsync(Guid id, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE data_issues SET attempts = attempts + 1, updated_at = @now WHERE id = @id", cancellationToken,
("now", clock.UtcNow), ("id", id)), cancellationToken);
public Task ResolveAsync(Guid id, string status, string? detail, CancellationToken cancellationToken) =>
db.WriteAsync(s => detail is null
? s.ExecuteAsync("UPDATE data_issues SET status = @st, updated_at = @now WHERE id = @id", cancellationToken,
("st", status), ("now", clock.UtcNow), ("id", id))
: s.ExecuteAsync("UPDATE data_issues SET status = @st, detail = @d, updated_at = @now WHERE id = @id", cancellationToken,
("st", status), ("d", detail), ("now", clock.UtcNow), ("id", id)), cancellationToken);
public async Task<IReadOnlyList<DataIssue>> OpenAsync(Guid? instrumentId, CancellationToken cancellationToken) =>
await db.ReadAsync(s => instrumentId is null
? s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE status = @open ORDER BY starts_at", Read, ("open", IssueStatus.Open))
: s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE status = @open AND instrument_id = @i ORDER BY starts_at", Read,
("open", IssueStatus.Open), ("i", instrumentId)), cancellationToken).ConfigureAwait(false);
public async Task<IReadOnlyList<DataIssue>> SinceAsync(DateTimeOffset since, CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync($"SELECT {Columns} FROM data_issues WHERE updated_at >= @t ORDER BY created_at", Read, ("t", since)),
cancellationToken).ConfigureAwait(false);
/// <summary>Instruments with a suspect bar still waiting for its second reading: no entries on them (SPEC 6.4).</summary>
public async Task<IReadOnlySet<Guid>> BlockedInstrumentsAsync(CancellationToken cancellationToken)
{
var open = await OpenAsync(null, cancellationToken).ConfigureAwait(false);
return open.Where(i => i.InstrumentId is not null && IssueKinds.MakesSuspect(i.Kind)).Select(i => i.InstrumentId!.Value).ToHashSet();
}
private static DataIssue Read(DbRow r) => new(
r.Id("id"), r.IdOrNull("instrument_id"), r.Text("timeframe"), r.Text("kind"), r.Moment("starts_at"), r.Moment("ends_at"),
r.Text("status"), (int)r.Number("attempts"), r.Text("detail"), r.Moment("created_at"), r.Moment("updated_at"));
}
+189
View File
@@ -0,0 +1,189 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
namespace Anubis.Data;
/// <summary>
/// A bar of the research history. Values keep the decimal text the source wrote, so a round trip through the file
/// loses no digit (issue #21); backtests convert to <see cref="double"/> when they read.
/// </summary>
public sealed record ResearchBar(DateTimeOffset OpensAt, decimal Open, decimal High, decimal Low, decimal Close, decimal Volume)
{
public decimal? QuoteVolume { get; init; }
public long? Trades { get; init; }
public Bar ToBar() => new(OpensAt, (double)Open, (double)High, (double)Low, (double)Close, (double)Volume)
{
QuoteVolume = QuoteVolume is { } q ? (double)q : null,
};
}
/// <summary>
/// The research history (SPEC 6.6, ADR 0003): one gzip-compressed CSV per instrument, timeframe and year under
/// <c>research/{venue}/{symbol}/{timeframe}/{year}.csv.gz</c>. Backtests read it from here, never from the database.
/// Writing a year merges with what is there: a bar with the same opening time is replaced. Files are written to a
/// temporary name and moved into place, so a crash never leaves half a file.
/// </summary>
public sealed class ResearchStore(string root)
{
public const string Header = "opens_at,open,high,low,close,volume,quote_volume,trades";
private const string MomentFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public string Root { get; } = root;
public string PathFor(string venue, string symbol, string timeframe, int year) =>
Path.Combine(Root, Safe(venue), Safe(symbol), Safe(timeframe), year.ToString(CultureInfo.InvariantCulture) + ".csv.gz");
/// <summary>Writes bars, merging each year with its existing file. Returns the number of bars now in the touched files.</summary>
public async Task<int> WriteAsync(string venue, string symbol, string timeframe, IEnumerable<ResearchBar> bars, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(bars);
var total = 0;
foreach (var year in bars.GroupBy(b => b.OpensAt.UtcDateTime.Year))
{
var path = PathFor(venue, symbol, timeframe, year.Key);
var merged = new SortedDictionary<DateTimeOffset, ResearchBar>();
if (File.Exists(path))
{
await foreach (var bar in ReadFileAsync(path, cancellationToken).ConfigureAwait(false))
{
merged[bar.OpensAt] = bar;
}
}
foreach (var bar in year)
{
merged[bar.OpensAt.ToUniversalTime()] = bar with { OpensAt = bar.OpensAt.ToUniversalTime() };
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var temp = path + ".tmp";
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true))
await using (var gzip = new GZipStream(file, CompressionLevel.Optimal))
await using (var writer = new StreamWriter(gzip, new UTF8Encoding(false)) { NewLine = "\n" })
{
await writer.WriteLineAsync(Header).ConfigureAwait(false);
foreach (var bar in merged.Values)
{
cancellationToken.ThrowIfCancellationRequested();
await writer.WriteLineAsync(Format(bar)).ConfigureAwait(false);
}
}
File.Move(temp, path, overwrite: true);
total += merged.Count;
}
return total;
}
/// <summary>Bars opening from <paramref name="from"/> (included) to <paramref name="to"/> (excluded), oldest first.</summary>
public async IAsyncEnumerable<ResearchBar> ReadAsync(string venue, string symbol, string timeframe, DateTimeOffset from, DateTimeOffset to,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
foreach (var year in Years(venue, symbol, timeframe).Where(y => y >= from.UtcDateTime.Year && y <= to.UtcDateTime.Year))
{
await foreach (var bar in ReadFileAsync(PathFor(venue, symbol, timeframe, year), cancellationToken).ConfigureAwait(false))
{
if (bar.OpensAt >= from && bar.OpensAt < to)
{
yield return bar;
}
}
}
}
public IReadOnlyList<int> Years(string venue, string symbol, string timeframe)
{
var folder = Path.Combine(Root, Safe(venue), Safe(symbol), Safe(timeframe));
if (!Directory.Exists(folder))
{
return [];
}
return Directory.EnumerateFiles(folder, "*.csv.gz")
.Select(f => Path.GetFileName(f)[..^".csv.gz".Length])
.Select(n => int.TryParse(n, NumberStyles.None, CultureInfo.InvariantCulture, out var y) ? y : 0)
.Where(y => y > 0)
.Order()
.ToList();
}
/// <summary>Every (venue, symbol, timeframe) with at least one file.</summary>
public IReadOnlyList<(string Venue, string Symbol, string Timeframe)> Series()
{
if (!Directory.Exists(Root))
{
return [];
}
return Directory.EnumerateFiles(Root, "*.csv.gz", SearchOption.AllDirectories)
.Select(f => Path.GetRelativePath(Root, f).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
.Where(p => p.Length == 4)
.Select(p => (p[0], p[1], p[2]))
.Distinct()
.Order()
.ToList();
}
private static async IAsyncEnumerable<ResearchBar> ReadFileAsync(string path,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, useAsync: true);
await using var gzip = new GZipStream(file, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
var header = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
if (header != Header)
{
throw new InvalidDataException($"Unexpected header in {path}: {header}");
}
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
{
if (line.Length > 0)
{
yield return Parse(line, path);
}
}
}
private static string Format(ResearchBar bar) => string.Join(',',
bar.OpensAt.UtcDateTime.ToString(MomentFormat, CultureInfo.InvariantCulture),
Text(bar.Open), Text(bar.High), Text(bar.Low), Text(bar.Close), Text(bar.Volume),
bar.QuoteVolume is { } q ? Text(q) : "",
bar.Trades?.ToString(CultureInfo.InvariantCulture) ?? "");
private static ResearchBar Parse(string line, string path)
{
var f = line.Split(',');
if (f.Length != 8)
{
throw new InvalidDataException($"Bad line in {path}: {line}");
}
return new ResearchBar(
DateTimeOffset.ParseExact(f[0], MomentFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal),
Number(f[1]), Number(f[2]), Number(f[3]), Number(f[4]), Number(f[5]))
{
QuoteVolume = f[6].Length == 0 ? null : Number(f[6]),
Trades = f[7].Length == 0 ? null : long.Parse(f[7], NumberStyles.None, CultureInfo.InvariantCulture),
};
}
/// <summary>Canonical decimal text: no exponent, no trailing zeros.</summary>
private static string Text(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture);
private static decimal Number(string text) => decimal.Parse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
/// <summary>File-name-safe form of a symbol: letters, digits, dash and underscore; anything else becomes underscore.</summary>
public static string Safe(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var chars = name.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' ? c : '_').ToArray();
var safe = new string(chars);
return safe is "." or ".." ? "_" : safe;
}
}
+32
View File
@@ -0,0 +1,32 @@
namespace Anubis.Data;
/// <summary>
/// The data part of a broker adapter (SPEC 5.3): instruments, bars, quotes and the live feed. The order part
/// arrives in Phase 3 on the same adapters.
/// </summary>
public interface IMarketDataSource
{
string Venue { get; }
Task<IReadOnlyList<InstrumentSpec>> ListInstrumentsAsync(CancellationToken cancellationToken);
/// <summary>Daily bars for the days from <paramref name="first"/> to <paramref name="last"/>, both included, oldest first.</summary>
Task<IReadOnlyList<DailyBar>> FetchDailyBarsAsync(string symbol, DateOnly first, DateOnly last, CancellationToken cancellationToken);
/// <summary>Closed one-minute bars opening from <paramref name="start"/> (included) to <paramref name="until"/> (excluded), oldest first.</summary>
Task<IReadOnlyList<Bar>> FetchMinuteBarsAsync(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken cancellationToken);
Task<Quote> FetchQuoteAsync(string symbol, CancellationToken cancellationToken);
/// <summary>
/// Opens a live feed for <paramref name="symbols"/>. The sequence ends when the connection drops: the caller
/// reconnects and recovers the gap (trap 10).
/// </summary>
IAsyncEnumerable<MarketEvent> StreamAsync(IReadOnlyCollection<string> symbols, CancellationToken cancellationToken);
}
/// <summary>A source refused or failed. <see cref="Retryable"/> says whether trying again later can help.</summary>
public sealed class MarketDataException(string message, bool retryable = true, Exception? inner = null) : Exception(message, inner)
{
public bool Retryable { get; } = retryable;
}
@@ -0,0 +1,185 @@
-- Phase 2: market data (SPEC 5.4, 6, 10.4; ADR 0008). Same text on PostgreSQL and SQLite, as in 0001.
-- Days are TEXT 'yyyy-MM-dd': the exchange date for stocks, the UTC date for crypto. Bars are analysis data and
-- stay floating point (SPEC 5.4); prices that orders use come from quotes and instrument rules, which are exact.
-- The instrument catalogue (SPEC 6.1): rules read from the venue every day, never written in code.
ALTER TABLE instruments ADD COLUMN base_currency TEXT;
ALTER TABLE instruments ADD COLUMN exchange TEXT;
ALTER TABLE instruments ADD COLUMN tick_size {money};
ALTER TABLE instruments ADD COLUMN lot_size {money};
ALTER TABLE instruments ADD COLUMN min_size {money};
ALTER TABLE instruments ADD COLUMN min_notional {money};
ALTER TABLE instruments ADD COLUMN status TEXT;
ALTER TABLE instruments ADD COLUMN fractionable {bool};
ALTER TABLE instruments ADD COLUMN is_fund {bool};
ALTER TABLE instruments ADD COLUMN listed_at {timestamp};
ALTER TABLE instruments ADD COLUMN updated_at {timestamp};
-- Daily bars for every strategy. Stocks keep both the real prices (orders, universe filters) and the adjusted ones
-- as the source gave them on the last download (signals, anchored to the decision day: SPEC 6.10).
-- quality: ok, suspect (failed a check, waiting for a second reading) or confirmed (a second reading agreed).
CREATE TABLE bars_1d (
id {uuid} PRIMARY KEY,
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
day TEXT NOT NULL,
open {float} NOT NULL,
high {float} NOT NULL,
low {float} NOT NULL,
close {float} NOT NULL,
volume {float} NOT NULL,
quote_volume {float},
adj_open {float},
adj_high {float},
adj_low {float},
adj_close {float},
source TEXT NOT NULL,
quality TEXT NOT NULL,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL,
UNIQUE (instrument_id, day)
){strict};
-- One-minute bars, only for instruments in the portfolio and order simulation; kept 400 days (SPEC 5.4, 6.2).
CREATE TABLE bars_1m (
id {uuid} PRIMARY KEY,
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
opens_at {timestamp} NOT NULL,
open {float} NOT NULL,
high {float} NOT NULL,
low {float} NOT NULL,
close {float} NOT NULL,
volume {float} NOT NULL,
source TEXT NOT NULL,
quality TEXT NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (instrument_id, opens_at)
){strict};
-- Splits, reverse splits, dividends, symbol changes (SPEC 6.10). ratio = new shares per old share.
CREATE TABLE corporate_actions (
id {uuid} PRIMARY KEY,
instrument_id {uuid} REFERENCES instruments (id),
symbol TEXT NOT NULL,
kind TEXT NOT NULL,
ex_date TEXT NOT NULL,
ratio {money},
cash_amount {money},
currency TEXT,
new_symbol TEXT,
source TEXT NOT NULL,
source_key TEXT NOT NULL UNIQUE,
applied_at {timestamp},
created_at {timestamp} NOT NULL
){strict};
CREATE INDEX corporate_actions_symbol ON corporate_actions (symbol, ex_date);
-- Reference exchange rates, one per day as published (SPEC 6.8): rate = units of quote for one base.
CREATE TABLE fx_rates (
id {uuid} PRIMARY KEY,
base TEXT NOT NULL,
quote TEXT NOT NULL,
rate_date TEXT NOT NULL,
rate {money} NOT NULL,
source TEXT NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (base, quote, rate_date)
){strict};
-- The exchange calendar as the broker gives it, one row per day of the downloaded range, closed days included.
CREATE TABLE market_calendar (
id {uuid} PRIMARY KEY,
market TEXT NOT NULL,
session_date TEXT NOT NULL,
is_open {bool} NOT NULL,
open_at {timestamp},
close_at {timestamp},
created_at {timestamp} NOT NULL,
UNIQUE (market, session_date)
){strict};
-- Economic events, central bank meetings and earnings dates (SPEC 10.4).
CREATE TABLE calendar_events (
id {uuid} PRIMARY KEY,
kind TEXT NOT NULL,
title TEXT NOT NULL,
currency TEXT,
symbol TEXT,
occurs_at {timestamp} NOT NULL,
time_known {bool} NOT NULL,
time_hint TEXT,
impact TEXT,
forecast TEXT,
previous TEXT,
source TEXT NOT NULL,
source_key TEXT NOT NULL UNIQUE,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
CREATE INDEX calendar_events_time ON calendar_events (occurs_at);
-- Mood indicators (SPEC 10.4): fear and greed, VIX, Bitcoin funding and open interest.
CREATE TABLE market_mood (
id {uuid} PRIMARY KEY,
indicator TEXT NOT NULL,
as_of {timestamp} NOT NULL,
value {float} NOT NULL,
label TEXT,
source TEXT NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (indicator, as_of)
){strict};
-- Hourly spread samples of the crypto pairs, for the universe filter of SPEC 8.1.
CREATE TABLE spread_samples (
id {uuid} PRIMARY KEY,
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
sampled_at {timestamp} NOT NULL,
spread_bp {float} NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (instrument_id, sampled_at)
){strict};
-- What the data checks found (SPEC 6.3, 6.4): gaps, duplicates, impossible or suspicious prices, stale feeds.
-- status: open, recovered, unrecoverable, confirmed (a second reading agreed), corrected (it did not).
CREATE TABLE data_issues (
id {uuid} PRIMARY KEY,
instrument_id {uuid} REFERENCES instruments (id),
timeframe TEXT NOT NULL,
kind TEXT NOT NULL,
starts_at {timestamp} NOT NULL,
ends_at {timestamp} NOT NULL,
status TEXT NOT NULL,
attempts INTEGER NOT NULL,
detail TEXT NOT NULL,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
CREATE INDEX data_issues_instrument ON data_issues (instrument_id, status);
-- State of each external source: last request (to respect limits across restarts), last success, last error,
-- and whether it is off because a key is missing (SPEC 4.4: the interface says so).
CREATE TABLE source_state (
id {uuid} PRIMARY KEY,
source TEXT NOT NULL UNIQUE,
enabled {bool} NOT NULL,
last_request_at {timestamp},
last_success_at {timestamp},
last_error TEXT,
note TEXT,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
-- Universes as they were chosen (SPEC 6.7, 8.1, 8.2): the crypto one is recomputed on the first day of each month.
CREATE TABLE universe_members (
id {uuid} PRIMARY KEY,
universe TEXT NOT NULL,
as_of TEXT NOT NULL,
instrument_id {uuid} NOT NULL REFERENCES instruments (id),
rank INTEGER NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (universe, as_of, instrument_id)
){strict};