diff --git a/docs/adr/0018-scelte-fase-8.md b/docs/adr/0018-scelte-fase-8.md new file mode 100644 index 0000000..dfd4036 --- /dev/null +++ b/docs/adr/0018-scelte-fase-8.md @@ -0,0 +1,31 @@ +# 0018 — Scelte della Fase 8 (apprendimento) + +Data: 2026-12-01 · Stato: accettata · Precisa gli ADR 0003 (riga Apprendimento) e 0004 (tabella dei componenti) e SPEC 5.4, 11 e 13.6 + +## Contesto + +La Fase 8 costruisce il modulo che stima quanto è probabile che un segnale vada bene (SPEC 11). L'ADR 0003 prevedeva ML.NET con LightGBM. Il 18/11/2026 l'utente ha dato una regola più stretta per tutti i progetti: niente componenti esterni, tutto il codice in casa. + +## Decisione + +**1. I modelli sono scritti in casa.** `Microsoft.ML`, `Microsoft.ML.LightGbm` e `Microsoft.ML.FastTree` sono autorizzati ma non si usano: non entra nessun pacchetto nuovo, nessuna libreria nativa e `libgomp1` non serve. Al loro posto: +- regressione logistica regolarizzata (riferimento); +- alberi potenziati: pochi livelli, molti esempi per foglia, passo piccolo, regolarizzazione (principale, al posto di LightGBM); +- foresta casuale (sfidante, al posto del percettrone come già in ADR 0003), con lo stesso codice degli alberi; +- calibrazione di Platt e isotonica. + +Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento dura meno di un secondo. Tutto è deterministico: stessi dati, stesso modello. + +**2. Esempi.** +- Un esempio nasce dalla prima intenzione d'ingresso su uno strumento che la strategia non ha, anche se poi è rifiutata e anche in osservazione. Finché l'operazione simulata di quell'esempio è aperta, riproporre l'ingresso non ne crea un altro. +- L'esempio si scrive nella stessa transazione della decisione. Un guasto dell'apprendimento non ferma mai una decisione: la strategia prosegue come se il modello non ci fosse. +- `ml_features` contiene l'esempio con i suoi indizi, `ml_labels` l'esito (una volta sola), `ml_predictions` le stime. In più `ml_events` (la storia mostrata) e `ml_state`. + +**3. Etichetta.** È l'operazione dell'esempio simulata da sola con il motore del backtest: si compra all'apertura dopo la decisione, sempre la stessa quota, si seguono le uscite e gli stop della strategia, senza aumenti, riduzioni né nuovi acquisti, con le commissioni e lo scostamento di sempre. Il risultato è una quota di quanto investito. Un'operazione che non può partire (sotto il minimo del mercato) resta senza esito e non addestra. +- `equity_momentum` ha bisogno di tutto l'universo, perché esce anche per la posizione in classifica; le altre guardano solo il proprio strumento. + +**4. Indizi.** Tutti quelli di 11.2, calcolati con le sole barre fino alla decisione e con i valori esterni già datati **e già salvati** in quel momento. +- Si ricostruiscono dallo storico: strategia, forza, distanza dallo stop, volatilità e rapporto, volumi, regime, ampiezza, giorno della settimana. +- Restano fuori finché non ci sono 200 esempi dal vivo che li contengono: notizie, evento più grave, paura e avidità, VIX, finanziamento e open interest, giorni alla trimestrale. Paura e avidità e VIX hanno uno storico pubblico, ma non è tra i dati già scaricati: per ora seguono la stessa regola. +- L'open interest è il rapporto con la sua media di 30 giorni: il valore assoluto non vuol dire niente negli anni. Un valore esterno troppo vecchio (la fonte si è fermata) è mancante. +- La forza del segnale è della strategia e viaggia con l'intenzione (`Intent.Strength`); nessuna regola la legge. diff --git a/src/Anubis/Db/Migrations/0012_learning.sql b/src/Anubis/Db/Migrations/0012_learning.sql new file mode 100644 index 0000000..8d3a26c --- /dev/null +++ b/src/Anubis/Db/Migrations/0012_learning.sql @@ -0,0 +1,94 @@ +-- Learning (SPEC 11, ADR 0018): the archive of examples with the clues as known at the decision, their labels, the +-- models, what each model estimated, what happened to them, and the small state of the nightly check. + +-- One example: the first entry intent of a strategy on an instrument it does not hold (11.2), executed or not. source +-- is 'live' or 'history' (rebuilt by running the strategy on the past). weight is the share of the strategy's capital +-- it asked for; stop and stop_offset are the ones of the intent, kept to simulate the operation for the label; stage +-- is the strategy's stage at the decision (null for history). multiplier is the one the operation was born with. +CREATE TABLE ml_features ( + id {uuid} PRIMARY KEY, + strategy TEXT NOT NULL, + symbol TEXT NOT NULL, + source TEXT NOT NULL, + decided_day TEXT NOT NULL, + decided_at {timestamp} NOT NULL, + decision_id {uuid}, + stage TEXT, + reason TEXT NOT NULL, + weight {money} NOT NULL, + stop {money}, + stop_offset {money}, + features {json} NOT NULL, + multiplier {float} NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (strategy, symbol, decided_day, source) +){strict}; + +CREATE INDEX ml_features_decided ON ml_features (decided_at); + +-- The outcome of an example, known when its simulated operation closes; no row means still open. label is 1 when it +-- closed with a gain net of costs, 0 otherwise, null when the operation could never start (void). result is the +-- return on what was invested. +CREATE TABLE ml_labels ( + id {uuid} PRIMARY KEY, + feature_id {uuid} NOT NULL UNIQUE REFERENCES ml_features (id), + label INTEGER, + result {float}, + opened_day TEXT, + closed_day TEXT, + exit_reason TEXT NOT NULL, + created_at {timestamp} NOT NULL +){strict}; + +-- The register of every attempt (11.3): champion, challenger, retired, discarded, undone, and the ones tried while +-- choosing ('tried'). model holds the learner, its calibration and the statistics of the clues; report its validation. +CREATE TABLE ml_models ( + id {uuid} PRIMARY KEY, + version INTEGER, + learner TEXT NOT NULL, + status TEXT NOT NULL, + source TEXT NOT NULL, + trained_at {timestamp} NOT NULL, + examples INTEGER NOT NULL, + threshold_done INTEGER NOT NULL, + replaced_id {uuid}, + model {json}, + report {json} NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX ml_models_status ON ml_models (status); + +-- What a model said of an example when it was born: in_charge marks the estimate that counted (the champion's). +CREATE TABLE ml_predictions ( + id {uuid} PRIMARY KEY, + feature_id {uuid} NOT NULL REFERENCES ml_features (id), + model_id {uuid} NOT NULL REFERENCES ml_models (id), + probability {float} NOT NULL, + base_rate {float} NOT NULL, + multiplier {float} NOT NULL, + in_charge {bool} NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (feature_id, model_id) +){strict}; + +-- The history the user reads: trainings, promotions, discards, alarms. +CREATE TABLE ml_events ( + id {uuid} PRIMARY KEY, + kind TEXT NOT NULL, + version INTEGER, + text TEXT NOT NULL, + data {json}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX ml_events_created ON ml_events (created_at); + +CREATE TABLE ml_state ( + id {uuid} PRIMARY KEY, + key TEXT NOT NULL UNIQUE, + value {json} NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; diff --git a/src/Anubis/Learning/Clues.cs b/src/Anubis/Learning/Clues.cs new file mode 100644 index 0000000..0554f3b --- /dev/null +++ b/src/Anubis/Learning/Clues.cs @@ -0,0 +1,251 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Learning; + +/// +/// A clue of SPEC 11.2. is what the interface calls it: several clues may tell the same thing. +/// is false for one whose past cannot be rebuilt here: it stays out of the model until at least +/// live examples contain it. +/// +public sealed record Clue(string Key, string Group, bool FromHistory); + +/// What was known outside the bars at a decision: each value only if it was already out and already read. +public sealed record OutsideView +{ + public static OutsideView Nothing { get; } = new(); + + public double? FearGreed { get; init; } + + public double? Vix { get; init; } + + public double? BtcFunding { get; init; } + + /// Open interest over its own mean of the last 30 days: the level alone means nothing over the years. + public double? BtcOpenInterest { get; init; } + + public IReadOnlyDictionary News { get; init; } = new Dictionary(); + + /// Stories of the last 3 days by symbol. + public IReadOnlyDictionary Stories3Days { get; init; } = new Dictionary(); + + /// Next earnings day by symbol; only while the calendar is fresh. + public IReadOnlyDictionary? Earnings { get; init; } +} + +/// The clues of SPEC 11.2, all computed from what was known at the decision. +public static class Clues +{ + /// Live examples needed before a clue without history enters the model (SPEC 11.2). + public const int MinLive = 200; + + public const string StrategyPrefix = "strategy_"; + + public const string Strength = "strength"; + public const string StopDistance = "stop_distance"; + public const string Volatility = "volatility"; + public const string VolatilityRatio = "volatility_ratio"; + public const string Volume = "volume"; + public const string MarketTrend = "market_trend"; + public const string MarketVolatility = "market_volatility"; + public const string Breadth = "breadth"; + public const string WeekSin = "weekday_sin"; + public const string WeekCos = "weekday_cos"; + public const string Tone1 = "news_tone_1d"; + public const string Tone3 = "news_tone_3d"; + public const string Count1 = "news_count_1d"; + public const string Count3 = "news_count_3d"; + public const string WorstEvent = "news_worst"; + public const string FearGreed = "fear_greed"; + public const string Vix = "vix"; + public const string Funding = "btc_funding"; + public const string OpenInterest = "btc_open_interest"; + public const string EarningsDays = "earnings_days"; + + public static readonly IReadOnlyList All = + [ + new(StrategyPrefix + StrategyNames.CryptoTrend, "Strategia", true), + new(StrategyPrefix + StrategyNames.EquityMomentum, "Strategia", true), + new(StrategyPrefix + StrategyNames.EquityMeanrev, "Strategia", true), + new(Strength, "Forza della tendenza", true), + new(StopDistance, "Distanza dallo stop", true), + new(Volatility, "Agitazione recente dei prezzi", true), + new(VolatilityRatio, "Agitazione recente dei prezzi", true), + new(Volume, "Volumi scambiati", true), + new(MarketTrend, "Fase generale del mercato", true), + new(MarketVolatility, "Fase generale del mercato", true), + new(Breadth, "Quota di titoli in salita", true), + new(WeekSin, "Giorno della settimana", true), + new(WeekCos, "Giorno della settimana", true), + new(Tone1, "Tono delle notizie, 1 giorno", false), + new(Tone3, "Tono delle notizie, 3 giorni", false), + new(Count1, "Numero di notizie", false), + new(Count3, "Numero di notizie", false), + new(WorstEvent, "Notizia più grave", false), + new(FearGreed, "Paura o avidità", false), + new(Vix, "Nervosismo di Wall Street", false), + new(Funding, "Scommesse a leva sulle crypto", false), + new(OpenInterest, "Scommesse a leva sulle crypto", false), + new(EarningsDays, "Giorni alla trimestrale", false), + ]; + + /// The groups that come from the news, for the sentence under the weights of the clues. + public static readonly IReadOnlySet NewsGroups = new HashSet(StringComparer.Ordinal) + { + "Tono delle notizie, 1 giorno", "Tono delle notizie, 3 giorni", "Numero di notizie", "Notizia più grave", + }; + + public static Clue? Find(string key) => All.FirstOrDefault(c => c.Key == key); + + /// The instrument whose trend is the market's: Bitcoin for crypto, SPY for stocks. + public static string? MarketOf(string strategy, StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (strategy != StrategyNames.CryptoTrend) + { + return StrategyNames.MarketSymbol; + } + + return new[] { NoBot.BitcoinSymbol, "BTCEUR" }.FirstOrDefault(s => context.Bars(s).Count > 0) + ?? context.Universe.FirstOrDefault(s => Symbols.BaseOf(context.Spec(s), s) == "BTC"); + } + + /// The clues of one entry intent. A value that cannot be computed is simply missing. + public static IReadOnlyDictionary Of(string strategy, StrategyContext context, Intent intent, OutsideView outside) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intent); + ArgumentNullException.ThrowIfNull(outside); + var values = new SortedDictionary(StringComparer.Ordinal); + void Put(string key, double? value) + { + if (value is { } v && double.IsFinite(v)) + { + values[key] = Math.Round(v, 8); + } + } + + foreach (var (name, _, _) in StrategyNames.Base) + { + Put(StrategyPrefix + name, name == strategy ? 1 : 0); + } + + var bars = context.Bars(intent.Symbol); + var close = bars.Count > 0 ? bars.Close(bars.Count - 1) : 0; + Put(Strength, intent.Strength); + if (close > 0) + { + var distance = intent.Stop is { } stop ? close - (double)stop : intent.StopOffset is { } offset ? (double)offset : (double?)null; + Put(StopDistance, distance / close); + } + + var year = context.PeriodsPerYear; + var recent = Indicators.Volatility(bars, 20, year); + var longer = Indicators.Volatility(bars, 100, year); + Put(Volatility, recent); + Put(VolatilityRatio, recent is { } r && longer is > 0 and var l ? r / l : null); + Put(Volume, Indicators.MedianValue(bars, 60, bars.Count - 1) is > 0 and var normal ? Indicators.MedianValue(bars, 5, bars.Count - 1) / normal : null); + if (MarketOf(strategy, context) is { } market) + { + var index = context.Bars(market); + Put(MarketTrend, Indicators.Sma(index, 200) is > 0 and var average ? (index.Close(index.Count - 1) / average) - 1 : null); + Put(MarketVolatility, Indicators.Volatility(index, 30, year)); + } + + Put(Breadth, BreadthOf(context)); + var week = 2 * Math.PI * (int)context.Day.DayOfWeek / 7; + Put(WeekSin, Math.Sin(week)); + Put(WeekCos, Math.Cos(week)); + if (outside.News.TryGetValue(intent.Symbol, out var news)) + { + Put(Tone1, news.Tone1Day); + Put(Tone3, news.Tone3Days); + Put(Count1, news.Stories1Day); + Put(Count3, outside.Stories3Days.GetValueOrDefault(intent.Symbol)); + Put(WorstEvent, news.Active?.Story.RuleImportance ?? 0); + } + + Put(FearGreed, outside.FearGreed); + Put(Vix, outside.Vix); + Put(Funding, outside.BtcFunding); + Put(OpenInterest, outside.BtcOpenInterest); + if (strategy != StrategyNames.CryptoTrend && outside.Earnings is { } earnings) + { + Put(EarningsDays, earnings.TryGetValue(intent.Symbol, out var day) ? Math.Clamp(day.DayNumber - context.Day.DayNumber, 0, 31) : 31); + } + + return values; + } + + /// The share of the strategy's universe that closes above its 200-session average. + private static double? BreadthOf(StrategyContext context) + { + int above = 0, counted = 0; + foreach (var symbol in context.Universe) + { + var bars = context.Bars(symbol); + if (Indicators.Sma(bars, 200) is not { } average) + { + continue; + } + + counted++; + above += bars.Close(bars.Count - 1) > average ? 1 : 0; + } + + return counted > 0 ? (double)above / counted : null; + } +} + +/// +/// Reads what was known outside the bars at a moment (SPEC 11.2): mood values dated and saved by then, the news of each +/// instrument already read, the earnings calendar. Nothing saved after the moment is seen. +/// +public sealed class OutsideReader(Database db, IClock clock, SettingsStore? settings = null) +{ + private readonly NewsDesk _desk = new(db, clock, settings); + + public async Task ReadAsync(DateTimeOffset at, IReadOnlyDictionary specs, IReadOnlyDictionary? earnings, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(specs); + var news = new Dictionary(StringComparer.Ordinal); + var counts = new Dictionary(StringComparer.Ordinal); + var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(first_seen_at) AS first FROM news_stories", r => r.MomentOrNull("first")), cancellationToken) + .ConfigureAwait(false); + if (first is { } start && start <= at) + { + var switches = await _desk.SwitchesAsync(cancellationToken).ConfigureAwait(false); + foreach (var (symbol, spec) in specs) + { + var stories = await _desk.StoriesAsync(NewsDesk.Target(spec), at - NewsRules.NormWindow, cancellationToken).ConfigureAwait(false); + news[symbol] = NewsRules.State([.. stories], at, switches, first); + counts[symbol] = stories.Count(s => s.FirstSeenAt <= at && s.Start > at - TimeSpan.FromDays(3) && s.Start <= at); + } + } + + var interest = await MoodAsync(MoodIndicators.BtcOpenInterest, at, TimeSpan.FromDays(30), cancellationToken).ConfigureAwait(false); + return new OutsideView + { + News = news, + Stories3Days = counts, + Earnings = earnings, + FearGreed = Last(await MoodAsync(MoodIndicators.FearGreed, at, TimeSpan.FromDays(4), cancellationToken).ConfigureAwait(false)), + Vix = Last(await MoodAsync(MoodIndicators.Vix, at, TimeSpan.FromDays(6), cancellationToken).ConfigureAwait(false)), + BtcFunding = Last(await MoodAsync(MoodIndicators.BtcFunding, at, TimeSpan.FromDays(2), cancellationToken).ConfigureAwait(false)), + BtcOpenInterest = interest.Count >= 5 && interest.Average() is > 0 and var mean ? interest[^1] / mean : null, + }; + } + + private static double? Last(IReadOnlyList values) => values.Count > 0 ? values[^1] : null; + + // The values of the window already dated and saved at the moment, oldest first; a value too old is no value. + private async Task> MoodAsync(string indicator, DateTimeOffset at, TimeSpan window, CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync( + "SELECT value FROM market_mood WHERE indicator = @i AND as_of >= @f AND as_of <= @t AND created_at <= @t ORDER BY as_of", + r => r.Measure("value"), ("i", indicator), ("f", at - window), ("t", at)), cancellationToken).ConfigureAwait(false); +} diff --git a/src/Anubis/Learning/Examples.cs b/src/Anubis/Learning/Examples.cs new file mode 100644 index 0000000..cdc7ab1 --- /dev/null +++ b/src/Anubis/Learning/Examples.cs @@ -0,0 +1,218 @@ +using Anubis.Backtest; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Learning; + +/// Where an example comes from. +public static class CaseSources +{ + public const string Live = "live"; + public const string History = "history"; +} + +/// An example (SPEC 11.2; "segnale" and "caso" for the user): an entry intent and the clues known at that moment. +public sealed record Example(Guid Id, string Strategy, string Symbol, string Source, DateOnly Day, DateTimeOffset At, string Reason, decimal Weight, decimal? Stop, decimal? StopOffset, + IReadOnlyDictionary Features) +{ + /// The stage of the strategy at the decision; null for an example of the history. + public string? Stage { get; init; } + + public Guid? DecisionId { get; init; } + + /// The multiplier the operation was born with, valid to its close, increases included (SPEC 11.1). + public double Multiplier { get; init; } = 1; + + public CaseLabel? Label { get; init; } + + /// A label that can train: the operation started and closed. + public bool IsLabelled => Label is { Win: not null, ClosedDay: not null }; + + public bool IsOpenAfter(DateOnly day) => Label is null || (Label.ClosedDay is { } closed && closed > day); +} + +/// How the simulated operation of an example ended. is null when it could never start. +public sealed record CaseLabel(bool? Win, double? Result, DateOnly? OpenedDay, DateOnly? ClosedDay, string ExitReason); + +/// Why an example has no outcome. +public static class CaseOutcomes +{ + /// The operation could not start: below the minimum of the market. + public const string NeverStarted = "never_started"; +} + +/// +/// The first step of the decision: it changes nothing and notes the entry intents that make an example, with their clues. +/// One example for the first intent on an instrument not held; while the simulated operation of that example is open, a +/// repeated proposal is the same example (SPEC 11.2). +/// +public sealed class CaseCollector(string strategy, Func isNew, OutsideView? outside = null, DateOnly? only = null) : IIntentStage +{ + private readonly List _cases = []; + + public string Name => "learning_cases"; + + public IReadOnlyList Cases => _cases; + + /// Told of each new example, as soon as it is noted. + public Action? Noted { get; init; } + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + if (only is { } day && context.Day != day) + { + return intents; + } + + foreach (var intent in intents.Where(i => IsEntry(context, i) && isNew(context, i))) + { + var made = new Example(Guid.Empty, strategy, intent.Symbol, CaseSources.History, context.Day, context.Now, intent.Reason, intent.TargetWeight!.Value, intent.Stop, + intent.StopOffset, Clues.Of(strategy, context, intent, outside ?? OutsideView.Nothing)); + _cases.Add(made); + Noted?.Invoke(made); + } + + return intents; + } + + public static bool IsEntry(StrategyContext context, Intent intent) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intent); + return intent.TargetWeight is > 0m && !context.Portfolio.Holds(intent.Symbol); + } +} + +/// +/// One operation on its own: the entry of an example on its day, then the exits and the stops of its strategy and +/// nothing else. The size never changes and the instrument is never bought again, so the outcome does not depend on what +/// the bot did with the signal (SPEC 11.2). +/// +public sealed class SingleOperation(IStrategy inner, Example example) : IStrategy +{ + /// The same for every example: the result is a share of what is invested. + public const decimal Weight = 0.5m; + + public string Id => inner.Id; + + public string Version => inner.Version; + + public IReadOnlyList Schedule() => inner.Schedule(); + + /// Only equity_momentum needs the others, to know the rank; the rest look at their own instrument. + public static bool NeedsUniverse(string strategy) => strategy == StrategyNames.EquityMomentum; + + public IReadOnlyList Universe(UniverseContext context) => NeedsUniverse(inner.Id) ? inner.Universe(context) : [example.Symbol]; + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Day == example.Day) + { + return [new Intent(example.Symbol, Weight, example.Reason) { Stop = example.Stop, StopOffset = example.StopOffset }]; + } + + if (!context.Portfolio.Holds(example.Symbol)) + { + return []; + } + + var kept = new List(); + foreach (var intent in inner.Decide(context).Where(i => i.Symbol == example.Symbol)) + { + if (intent.TargetWeight == 0m) + { + kept.Add(intent); + } + else if (intent.Stop is not null) + { + kept.Add(intent with { TargetWeight = null }); + } + } + + return kept; + } +} + +/// The label of an example: its operation simulated alone, at full size, net of every cost (SPEC 11.2). +public static class CaseLabels +{ + private static readonly int[] Horizons = [40, 160, 640]; + + /// + /// The outcome with the bars of up to ; null while the operation is + /// open. The strategy is built fresh: it walks the bars again. is the first report after the + /// decision, which equity_meanrev leaves before. + /// + public static CaseLabel? Of(Example example, Func strategy, BacktestDataset data, DateOnly through, CostModel? costs = null, DateOnly? earnings = null) + { + ArgumentNullException.ThrowIfNull(example); + ArgumentNullException.ThrowIfNull(strategy); + ArgumentNullException.ThrowIfNull(data); + if (data[example.Symbol] is not { } instrument || through <= example.Day) + { + return null; + } + + var alone = SingleOperation.NeedsUniverse(example.Strategy) ? data : new BacktestDataset([instrument], data.Currency, data.Calendar); + foreach (var until in Horizons.Select(h => example.Day.AddDays(h)).Where(d => d < through).Append(through)) + { + var run = BacktestEngine.Run(new SingleOperation(strategy(), example), alone, new BacktestOptions + { + From = example.Day, + To = until, + Costs = costs ?? CostModel.Standard, + NextEarnings = earnings is { } date ? s => s == example.Symbol ? date : null : null, + }); + var trade = run.Trades.FirstOrDefault(t => t.Symbol == example.Symbol); + if (trade is null) + { + // Bars came after the decision and nothing was bought: the operation cannot exist. + if (instrument.Bars.FirstOrDefault(b => b.Day > example.Day && b.Day <= until) is { } bar) + { + return new CaseLabel(null, null, null, bar.Day, CaseOutcomes.NeverStarted); + } + } + else if (trade.Closed is { } closed) + { + var result = trade.Invested > 0m ? (double)(trade.Result / trade.Invested) : 0; + return new CaseLabel(trade.Result > 0m, Math.Round(result, 8), trade.Opened, closed, run.Fills.Last(f => f.Symbol == example.Symbol).Reason); + } + } + + return null; + } +} + +/// The examples of the past: the strategy runs on the history and every first entry becomes one (SPEC 11.2). +public static class HistoryCases +{ + public static IReadOnlyList Build(string strategy, Func create, BacktestDataset data, BacktestOptions options, Action? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(create); + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(options); + var through = options.To ?? data.Sessions[^1]; + var last = new Dictionary(StringComparer.Ordinal); + var cases = new List(); + + // The label reads the bars after the decision, but the only thing the run uses of it is whether the operation + // was already over on a later day: known on that day. + var collector = new CaseCollector(strategy, (context, intent) => !last.TryGetValue(intent.Symbol, out var previous) || !previous.IsOpenAfter(context.Day)) + { + Noted = made => + { + cancellationToken.ThrowIfCancellationRequested(); + var labelled = made with { Label = CaseLabels.Of(made, create, data, through, options.Costs) }; + last[made.Symbol] = labelled; + cases.Add(labelled); + progress?.Invoke(cases.Count); + }, + }; + BacktestEngine.Run(create(), data, options with { Correctives = [collector, .. options.Correctives] }); + return cases; + } +} diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs new file mode 100644 index 0000000..ce5b965 --- /dev/null +++ b/src/Anubis/Learning/LearningDesk.cs @@ -0,0 +1,98 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Strategies; +using Anubis.Trading; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Learning; + +/// +/// Learning as the live engine sees it (SPEC 11): for each decision it gives the step that notes the examples, then saves +/// them with the decision. A failure here never stops a decision: the strategy goes on as if there were no model. +/// +public sealed partial class LearningDesk(Database db, IClock clock, SettingsStore? settings = null, ILogger? logger = null) +{ + private readonly ILogger _logger = logger ?? NullLogger.Instance; + private readonly OutsideReader _outside = new(db, clock, settings); + + public LearningStore Store { get; } = new(db, clock); + + /// What the decision of needs from learning; null when it could not be prepared. + public async Task PrepareAsync(string strategy, string stage, DateOnly day, BacktestDataset data, Func create, IReadOnlyDictionary? earnings, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(create); + if (!StrategyPipeline.IsBase(strategy)) + { + return null; + } + + try + { + var latest = new Dictionary(await Store.LatestAsync(strategy, cancellationToken).ConfigureAwait(false), StringComparer.Ordinal); + foreach (var example in latest.Values.Where(e => e.Label is null).ToList()) + { + // The operation of the example may have closed with the bars of today, before the nightly labels. + if (!SingleOperation.NeedsUniverse(strategy) && data[example.Symbol] is { } instrument && instrument.IndexOf(example.Day) >= 0 + && CaseLabels.Of(example, create, data, day) is { } label) + { + latest[example.Symbol] = example with { Label = label }; + } + } + + var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var outside = await _outside.ReadAsync(clock.UtcNow, specs, earnings, cancellationToken).ConfigureAwait(false); + return new LearningTurn(strategy, stage, day, latest, outside, clock); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogFailed(_logger, ex, strategy); + return null; + } + } + + [LoggerMessage(Level = LogLevel.Error, Message = "Learning left out of the decision of {Strategy}")] + private static partial void LogFailed(ILogger logger, Exception exception, string strategy); +} + +/// The learning side of one decision: the steps it adds and what it saves. +public sealed class LearningTurn +{ + private readonly string _stage; + private readonly DateOnly _day; + private readonly IReadOnlyDictionary _latest; + private readonly IClock _clock; + private readonly CaseCollector _collector; + + internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyDictionary latest, OutsideView outside, IClock clock) + { + _stage = stage; + _day = day; + _latest = latest; + _clock = clock; + _collector = new CaseCollector(strategy, IsNew, outside, day); + } + + /// The correctives with the steps of learning around them: the examples are noted on what the strategy proposed. + public IReadOnlyList Around(IReadOnlyList correctives) + { + ArgumentNullException.ThrowIfNull(correctives); + return [_collector, .. correctives]; + } + + private bool IsNew(StrategyContext context, Intent intent) => !_latest.TryGetValue(intent.Symbol, out var previous) || !previous.IsOpenAfter(_day); + + /// Saves the examples in the transaction of the decision. + public async Task WriteAsync(DbSession s, Guid decisionId, CancellationToken cancellationToken) + { + foreach (var made in _collector.Cases) + { + await LearningStore.AddAsync(s, _clock, made with { Source = CaseSources.Live, At = _clock.UtcNow, Stage = _stage, DecisionId = decisionId }, cancellationToken) + .ConfigureAwait(false); + } + } +} diff --git a/src/Anubis/Learning/LearningStore.cs b/src/Anubis/Learning/LearningStore.cs new file mode 100644 index 0000000..c109e89 --- /dev/null +++ b/src/Anubis/Learning/LearningStore.cs @@ -0,0 +1,105 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Learning; + +/// The archive of the examples and of their labels (SPEC 11.2), and the small state of the learning cycle. +public sealed class LearningStore(Database db, IClock clock) +{ + private const string Columns = + "f.id, f.strategy, f.symbol, f.source, f.decided_day, f.decided_at, f.decision_id, f.stage, f.reason, f.weight, f.stop, f.stop_offset, f.features, f.multiplier, " + + "l.id AS label_id, l.label, l.result, l.opened_day, l.closed_day, l.exit_reason FROM ml_features f LEFT JOIN ml_labels l ON l.feature_id = f.id"; + + /// Saves an example as part of the decision that made it. An example already there (same day) stays as it is. + public static async Task AddAsync(DbSession s, IClock clock, Example example, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(example); + var id = example.Id == Guid.Empty ? Ids.NewId(clock) : example.Id; + await s.ExecuteAsync( + "INSERT INTO ml_features (id, strategy, symbol, source, decided_day, decided_at, decision_id, stage, reason, weight, stop, stop_offset, features, multiplier, created_at) " + + "VALUES (@id, @s, @sym, @src, @day, @at, @dec, @st, @r, @w, @stop, @off, @f, @m, @now) ON CONFLICT (strategy, symbol, decided_day, source) DO NOTHING", cancellationToken, + ("id", id), ("s", example.Strategy), ("sym", example.Symbol), ("src", example.Source), ("day", BarStore.DayText(example.Day)), ("at", example.At), + ("dec", example.DecisionId), ("st", example.Stage), ("r", example.Reason), ("w", DbValues.Money(example.Weight)), ("stop", example.Stop), ("off", example.StopOffset), + ("f", new DbJson(JsonSerializer.Serialize(example.Features))), ("m", example.Multiplier), ("now", clock.UtcNow)).ConfigureAwait(false); + if (example.Label is { } label) + { + await AddLabelAsync(s, clock, id, label, cancellationToken).ConfigureAwait(false); + } + + return id; + } + + /// The label of an example, once and for all: a label never changes. + public static Task AddLabelAsync(DbSession s, IClock clock, Guid example, CaseLabel label, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(label); + return s.ExecuteAsync( + "INSERT INTO ml_labels (id, feature_id, label, result, opened_day, closed_day, exit_reason, created_at) VALUES (@id, @f, @l, @r, @o, @c, @e, @now) ON CONFLICT (feature_id) DO NOTHING", + cancellationToken, ("id", Ids.NewId(clock)), ("f", example), ("l", label.Win is { } win ? (win ? 1 : 0) : null), ("r", label.Result), + ("o", label.OpenedDay is { } opened ? BarStore.DayText(opened) : null), ("c", label.ClosedDay is { } closed ? BarStore.DayText(closed) : null), ("e", label.ExitReason), + ("now", clock.UtcNow)); + } + + public Task AddLabelAsync(Guid example, CaseLabel label, CancellationToken cancellationToken) => + db.WriteAsync(s => AddLabelAsync(s, clock, example, label, cancellationToken), cancellationToken); + + /// The whole archive, oldest first. + public Task> AllAsync(CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " ORDER BY f.decided_at, f.strategy, f.symbol", Read), cancellationToken); + + /// The live examples whose simulated operation is still open, oldest first. + public Task> OpenAsync(CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND l.id IS NULL ORDER BY f.decided_at, f.strategy, f.symbol", Read, ("l", CaseSources.Live)), cancellationToken); + + /// The latest live example of each instrument of a strategy: the one its operation was born with. + public async Task> LatestAsync(string strategy, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " WHERE f.source = @l AND f.strategy = @s ORDER BY f.decided_at", Read, ("l", CaseSources.Live), ("s", strategy)), + cancellationToken).ConfigureAwait(false); + return rows.GroupBy(r => r.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last(), StringComparer.Ordinal); + } + + public Task CountAsync(string source, CancellationToken cancellationToken) => + db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l", ("l", source)), cancellationToken); + + // ---- State -------------------------------------------------------------------------------------------------- + + public async Task StateAsync(string key, CancellationToken cancellationToken) + where T : class + { + var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)), cancellationToken).ConfigureAwait(false); + return json is null ? null : JsonSerializer.Deserialize(json); + } + + public static async Task SaveStateAsync(DbSession s, IClock clock, string key, T value, CancellationToken cancellationToken) + where T : class + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + await s.ExecuteAsync( + "INSERT INTO ml_state (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @now, @now) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", new DbJson(JsonSerializer.Serialize(value))), ("now", clock.UtcNow)).ConfigureAwait(false); + } + + private static Example Read(DbRow r) + { + var label = r.IsNull("label_id") + ? null + : new CaseLabel(r.IsNull("label") ? null : r.Number("label") == 1, r.IsNull("result") ? null : r.Measure("result"), Day(r, "opened_day"), Day(r, "closed_day"), r.Text("exit_reason")); + return new Example(r.Id("id"), r.Text("strategy"), r.Text("symbol"), r.Text("source"), BarStore.ParseDay(r.Text("decided_day")), r.Moment("decided_at"), r.Text("reason"), + r.Money("weight"), r.MoneyOrNull("stop"), r.MoneyOrNull("stop_offset"), JsonSerializer.Deserialize>(r.Json("features").Text) ?? []) + { + Stage = r.TextOrNull("stage"), + DecisionId = r.IdOrNull("decision_id"), + Multiplier = r.Measure("multiplier"), + Label = label, + }; + } + + private static DateOnly? Day(DbRow r, string column) => r.TextOrNull(column) is { } text ? BarStore.ParseDay(text) : null; +} diff --git a/src/Anubis/Strategies/CryptoTrend.cs b/src/Anubis/Strategies/CryptoTrend.cs index c1b459a..6ea7165 100644 --- a/src/Anubis/Strategies/CryptoTrend.cs +++ b/src/Anubis/Strategies/CryptoTrend.cs @@ -203,7 +203,7 @@ public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrateg { if (target > _settings.RebalanceMinimum) { - intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop }); + intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop, Strength = r.Tracker.Ensemble }); } } else if (held) diff --git a/src/Anubis/Strategies/EquityStrategies.cs b/src/Anubis/Strategies/EquityStrategies.cs index b8e4cb0..d33ad53 100644 --- a/src/Anubis/Strategies/EquityStrategies.cs +++ b/src/Anubis/Strategies/EquityStrategies.cs @@ -144,7 +144,8 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS } } - var ranking = scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal).Select(s => s.Symbol).ToList(); + scores = [.. scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal)]; + var ranking = scores.Select(s => s.Symbol).ToList(); var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal); bool AboveTrend(string symbol) { @@ -195,7 +196,11 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS { if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr) { - intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8) }; + intents[symbol] = new Intent(symbol, weight, Reasons.Entry) + { + StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8), + Strength = scores[rank[symbol]].Score, + }; } } @@ -452,7 +457,11 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr continue; // Not enough free capital for this candidate: it is dropped. } - intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = distance }); + intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) + { + StopOffset = distance, + Strength = (_settings.EntryRsi - c.Rsi) / _settings.EntryRsi, + }); freeCash -= value; slots--; } diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index a547498..fad72e4 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -40,6 +40,12 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason) /// public bool AtClose { get; init; } + /// + /// For a new entry: how strong the signal is, on the strategy's own scale (0 to 1 for crypto_trend and + /// equity_meanrev, the mean return of the lookbacks for equity_momentum). A clue of SPEC 11.2: no rule reads it. + /// + public double? Strength { get; init; } + /// /// Reason codes of the correctives and of the risk engine that changed this intent after the strategy (SPEC 5.2): /// empty when it passed as the strategy proposed it. diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index a1d4198..68fa0e1 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -154,6 +154,9 @@ public sealed partial class LiveEngine : IDisposable /// public Func>? Earnings { get; init; } + /// Learning (SPEC 11): notes the examples of each decision. Null in tests that do not look at it. + public Anubis.Learning.LearningDesk? Learning { get; init; } + /// The time zone of the diary's times: Italian time. public TimeZoneInfo Zone { get; init; } = Zones.Rome; @@ -493,6 +496,15 @@ public sealed partial class LiveEngine : IDisposable var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters); var data = loaded.Data; var options = await WithEarningsAsync(StrategyPipeline.For(m.Strategy, data, new BacktestOptions()), m.Strategy, m.Day, cancellationToken).ConfigureAwait(false); + var turn = Learning is null + ? null + : await Learning.PrepareAsync(m.Strategy, stage.Stage, m.Day, data, () => CreateStrategy(m.Strategy, stage.Qualification?.Parameters), await EarningsOfAsync(m, cancellationToken) + .ConfigureAwait(false), cancellationToken).ConfigureAwait(false); + if (turn is not null) + { + options = options with { Correctives = turn.Around(options.Correctives) }; + } + DecisionRecord record; if (observation) { @@ -519,9 +531,12 @@ public sealed partial class LiveEngine : IDisposable plan = await GateAsync(m, mode, plan, data, cancellationToken).ConfigureAwait(false); var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false); var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); - await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false); + await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, turn, cancellationToken).ConfigureAwait(false); } + private async Task?> EarningsOfAsync(Moment m, CancellationToken cancellationToken) => + Earnings is null || m.Strategy == StrategyNames.CryptoTrend ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next; + private DateTimeOffset LateSince(string key, DateTimeOffset now) { if (!_lateSince.TryGetValue(key, out var since)) @@ -793,7 +808,8 @@ public sealed partial class LiveEngine : IDisposable r => r.Id("instrument_id"), ("a", account), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false)).ToHashSet(); private async Task WriteDecisionAsync(Moment m, StrategyStage stage, Guid account, string mode, DecisionRecord record, PlanResult plan, Book book, - IReadOnlyDictionary specs, (Guid DecisionId, bool Same, IReadOnlyList Different)? oneStep, CancellationToken cancellationToken) + IReadOnlyDictionary specs, (Guid DecisionId, bool Same, IReadOnlyList Different)? oneStep, Anubis.Learning.LearningTurn? turn, + CancellationToken cancellationToken) { var decisionId = Ids.NewId(_clock); var now = m.Now; @@ -839,6 +855,11 @@ public sealed partial class LiveEngine : IDisposable } } + if (turn is not null) + { + await turn.WriteAsync(s, decisionId, cancellationToken).ConfigureAwait(false); + } + foreach (var (symbol, hold, dropped) in plan.Holds) { await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Correctives, diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index d20da35..b209223 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -184,6 +184,7 @@ public sealed partial class TradingService : IDisposable Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false))); Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile }; _settings = settings; + Learning = new Anubis.Learning.LearningDesk(db, clock, settings, _logger); Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger) { WantData = market is null ? null : _ => market.WakeWorker(), @@ -191,6 +192,7 @@ public sealed partial class TradingService : IDisposable Earnings = market is null ? null : (day, ct) => EarningsAsync(market, day, ct), Ready = () => _started, AccountReady = AccountReady, + Learning = Learning, }; } @@ -216,6 +218,9 @@ public sealed partial class TradingService : IDisposable private readonly SettingsStore? _settings; + /// Learning beside the decisions (SPEC 11). + public Anubis.Learning.LearningDesk Learning { get; } + public StageBook Stages { get; } /// The risk engine every intent crosses (SPEC 9). Null only without settings, in tests of the order manager alone. diff --git a/tests/Anubis.Tests/LearningCasesTests.cs b/tests/Anubis.Tests/LearningCasesTests.cs new file mode 100644 index 0000000..7753e12 --- /dev/null +++ b/tests/Anubis.Tests/LearningCasesTests.cs @@ -0,0 +1,274 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Learning; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The archive of the examples and their labels (SPEC 11.2, issue #62). +[TestClass] +public sealed class LearningCasesTests +{ + private static readonly DateOnly First = new(2023, 1, 1); + + internal static BacktestDataset Coins(int days = 900, int coins = 3) + { + var names = new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR", "ADA-EUR", "XRP-EUR" }; + return new BacktestDataset(Enumerable.Range(0, coins).Select(i => + new BacktestInstrument(MarketDataStoreTests.Okx(names[i]) with { ListedAt = null }, LiveRig.Synthetic(First, days, 100 * (i + 1), (uint)(7 + i)))), "EUR"); + } + + internal static IReadOnlyList History(BacktestDataset data) => + HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, + StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = First.AddDays(420) })); + + /// Criterion of the phase: no clue changes when data after the decision is added. + [TestMethod] + [TestCategory(Category.Unit)] + public void NoClueUsesDataAfterTheDecision() + { + var data = Coins(); + var full = History(data); + Assert.IsGreaterThan(20, full.Count); + foreach (var cut in new[] { 500, 600, 700, 800, 890 }.Select(d => First.AddDays(d))) + { + var known = History(data.Through(cut)); + var before = full.Where(e => e.Day <= cut).ToList(); + Assert.HasCount(before.Count, known, $"cut {cut}"); + foreach (var (a, b) in before.Zip(known)) + { + Assert.AreEqual((a.Symbol, a.Day, a.Weight, a.Stop), (b.Symbol, b.Day, b.Weight, b.Stop)); + Assert.AreEqual(Text(a), Text(b), $"{a.Symbol} {a.Day}"); + + // The outcome is known only once the operation is closed, and then it is the final one. + Assert.AreEqual(a.Label is { ClosedDay: { } closed } && closed <= cut ? a.Label : null, b.Label); + } + } + } + + private static string Text(Example e) => string.Join(';', e.Features.Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture))); + + /// The same for what comes from outside the bars: only values already dated, saved and read. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task NothingSavedOrDatedAfterTheDecisionIsRead() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var none = CancellationToken.None; + var at = rig.Clock.UtcNow; + var mood = new MoodStore(rig.Db, rig.Clock); + var reader = new OutsideReader(rig.Db, rig.Clock); + var specs = new Dictionary { ["BTC-EUR"] = TradingRig.Btc }; + await mood.UpsertAsync([new(MoodIndicators.FearGreed, at.AddHours(-20), 30, null, "t"), new(MoodIndicators.Vix, at.AddDays(-1), 18, null, "t"), + new(MoodIndicators.BtcFunding, at.AddHours(-3), 0.0001, null, "t"), .. Enumerable.Range(1, 10).Select(i => new MoodReading(MoodIndicators.BtcOpenInterest, at.AddDays(-i), 100, null, "t")), + new(MoodIndicators.FearGreed, at.AddHours(1), 99, null, "t")], none).ConfigureAwait(false); + await StoryAsync(rig, "Nota prima", at.AddHours(-5), at.AddHours(-4), 0.5).ConfigureAwait(false); + var before = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false); + Assert.AreEqual(30d, before.FearGreed); + Assert.AreEqual(18d, before.Vix); + Assert.AreEqual(1d, before.BtcOpenInterest); + Assert.AreEqual(1, before.Stories3Days["BTC-EUR"]); + Assert.AreEqual(0.5, before.News["BTC-EUR"].Tone1Day); + + // Later: values dated before the decision but saved after it (published late), and a story published before and + // read after. The past must look the same. + rig.Clock.Advance(TimeSpan.FromHours(6)); + await mood.UpsertAsync([new(MoodIndicators.Vix, at.AddHours(-2), 44, null, "t"), new(MoodIndicators.FearGreed, at.AddHours(-1), 5, null, "t"), + new(MoodIndicators.BtcFunding, at.AddMinutes(-1), 0.9, null, "t"), new(MoodIndicators.BtcOpenInterest, at.AddMinutes(-1), 900, null, "t")], none).ConfigureAwait(false); + await StoryAsync(rig, "Letta dopo", at.AddHours(-1), at.AddHours(2), -0.9).ConfigureAwait(false); + var again = await reader.ReadAsync(at, specs, null, none).ConfigureAwait(false); + Assert.AreEqual((before.FearGreed, before.Vix, before.BtcFunding, before.BtcOpenInterest), (again.FearGreed, again.Vix, again.BtcFunding, again.BtcOpenInterest)); + Assert.AreEqual(before.Stories3Days["BTC-EUR"], again.Stories3Days["BTC-EUR"]); + Assert.AreEqual(before.News["BTC-EUR"].Tone3Days, again.News["BTC-EUR"].Tone3Days); + + // A value too old is no value: the source stopped. + rig.Clock.Advance(TimeSpan.FromDays(40)); + var late = await reader.ReadAsync(rig.Clock.UtcNow, specs, null, none).ConfigureAwait(false); + Assert.IsNull(late.FearGreed); + Assert.IsNull(late.Vix); + Assert.IsNull(late.BtcOpenInterest); + } + + private static async Task StoryAsync(TradingRig rig, string title, DateTimeOffset published, DateTimeOffset seen, double score) + { + var id = Ids.NewId(rig.Clock); + await rig.Db.WriteAsync(async s => + { + await s.ExecuteAsync( + "INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " + + "VALUES (@id, @t, @t, @p, @f, @f, 1, @yes, @s, 1, @f, @f)", ("id", id), ("t", title), ("p", published), ("f", seen), ("yes", true), ("s", score)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', 'okx:BTC-EUR', 'name', @f)", + ("id", Ids.NewId(rig.Clock)), ("st", id), ("f", seen)).ConfigureAwait(false); + }).ConfigureAwait(false); + } + + /// Enters while not held, on a fixed day leaves; every day proposes again what it does not hold. + private sealed class Stubborn(DateOnly from, DateOnly exit, decimal weight = 0.3m, decimal? stop = null) : IStrategy + { + public string Id => StrategyNames.CryptoTrend; + + public string Version => "t"; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) => ["BTC-EUR"]; + + public IReadOnlyList Decide(StrategyContext context) + { + if (context.Day < from) + { + return []; + } + + if (context.Portfolio.Holds("BTC-EUR")) + { + return context.Day == exit ? [new Intent("BTC-EUR", 0m, "trend_exit")] : [new Intent("BTC-EUR", weight * 2, "trend_increase")]; + } + + return [new Intent("BTC-EUR", weight, "trend_entry") { Strength = 0.5, Stop = stop }]; + } + } + + private sealed class RefuseAll : IIntentStage + { + public string Name => "refuse"; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) => [.. intents.Where(i => i.TargetWeight is 0m)]; + } + + private sealed class HalveAll : IIntentStage + { + public string Name => "halve"; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) => [.. intents.Select(i => i with { TargetWeight = i.TargetWeight / 2 })]; + } + + /// One example for the first entry, even refused: proposals repeated and increases make none until it closes. + [TestMethod] + [TestCategory(Category.Unit)] + public void OneExampleForEachFirstEntryEvenWhenNothingIsBought() + { + var data = Coins(400, 1); + var (from, exit) = (First.AddDays(100), First.AddDays(130)); + IReadOnlyList Build(params IIntentStage[] stages) => + HistoryCases.Build(StrategyNames.CryptoTrend, () => new Stubborn(from, exit), data, new BacktestOptions { To = First.AddDays(140), Correctives = stages }); + + var executed = Build(); + var refused = Build(new RefuseAll()); + var halved = Build(new HalveAll()); + Assert.AreEqual(from, executed[0].Day); + Assert.AreEqual(exit.AddDays(1), executed[0].Label!.ClosedDay, "sold at the open after the exit"); + + // After the exit the strategy enters again: a second example, still open at the end. + Assert.HasCount(2, executed); + Assert.IsNull(executed[1].Label); + foreach (var other in new[] { refused, halved }) + { + // The same examples and the same label whatever the bot did with the signal. + Assert.HasCount(2, other); + Assert.AreEqual((executed[0].Day, executed[0].Weight), (other[0].Day, other[0].Weight)); + Assert.AreEqual(executed[0].Label, other[0].Label); + } + + Assert.AreEqual(0.5, executed[0].Features[Clues.Strength]); + Assert.AreEqual(1d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.CryptoTrend]); + Assert.AreEqual(0d, executed[0].Features[Clues.StrategyPrefix + StrategyNames.EquityMeanrev]); + } + + /// The label: the result of the operation alone, net of every cost, with the exits and the stop of its strategy. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheLabelIsTheOperationAloneNetOfCosts() + { + var spec = MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null }; + DailyBar Bar(int i, double open, double low, double close) => new(First.AddDays(i), open, Math.Max(open, close), low, close, 1e6); + var bars = new List { Bar(0, 100, 99, 100), Bar(1, 100, 99, 100), Bar(2, 100, 99, 100), Bar(3, 100.4, 99, 100.4), Bar(4, 100.4, 99, 100.4), Bar(5, 100, 80, 85), Bar(6, 85, 84, 85) }; + var data = new BacktestDataset([new BacktestInstrument(spec, bars)], "EUR"); + var example = new Example(Guid.Empty, StrategyNames.CryptoTrend, "BTC-EUR", CaseSources.History, First.AddDays(1), default, "trend_entry", 0.2m, null, null, new Dictionary()); + + // Bought at the open of day 2, sold at the open of day 4: +0.4% gross, a loss once fees and slippage are paid. + var label = CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6))!; + Assert.AreEqual((First.AddDays(2), First.AddDays(4), "trend_exit"), (label.OpenedDay, label.ClosedDay, label.ExitReason)); + Assert.IsFalse(label.Win); + Assert.IsLessThan(0d, label.Result!.Value); + Assert.IsTrue(CaseLabels.Of(example, () => new Stubborn(First.AddDays(1), First.AddDays(3)), data, First.AddDays(6), new CostModel(0m))!.Win); + + // The stop of the intent closes it on day 5, and before that day the label is not known. + var stopped = example with { Stop = 90m }; + var never = () => (IStrategy)new Stubborn(First.AddDays(1), DateOnly.MaxValue); + Assert.AreEqual(First.AddDays(5), CaseLabels.Of(stopped, never, data, First.AddDays(6))!.ClosedDay); + Assert.IsNull(CaseLabels.Of(stopped, never, data, First.AddDays(4))); + Assert.IsNull(CaseLabels.Of(example, never, data, First.AddDays(6)), "an operation still open has no label"); + + // One that can never start (below the minimum of the market) has no outcome and never trains. + var tooBig = new BacktestDataset([new BacktestInstrument(spec with { MinSize = 1_000_000m }, bars)], "EUR"); + var empty = CaseLabels.Of(example, never, tooBig, First.AddDays(6))!; + Assert.IsNull(empty.Win); + Assert.IsFalse((example with { Label = empty }).IsLabelled); + Assert.IsTrue((example with { Label = label }).IsLabelled); + } + + /// Saved and read back the same on both engines; a label is written once. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheArchiveReadsBackTheSame() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var none = CancellationToken.None; + var store = new LearningStore(rig.Db, rig.Clock); + var example = new Example(Guid.Empty, StrategyNames.EquityMeanrev, "AAPL", CaseSources.Live, First, rig.Clock.UtcNow, "meanrev_entry", 0.123456m, null, 4.25m, + new Dictionary { [Clues.Strength] = 0.1 + 0.2, [Clues.Breadth] = 1 }) + { Stage = StrategyStages.Observation, DecisionId = Ids.NewId(rig.Clock), Multiplier = 0.4 }; + var id = await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false); + await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, example, none), none).ConfigureAwait(false); + var read = (await store.AllAsync(none).ConfigureAwait(false)).Single(); + Assert.AreEqual((id, example.Symbol, example.Weight, example.Stop, example.StopOffset, example.Stage, example.DecisionId, example.Multiplier), + (read.Id, read.Symbol, read.Weight, read.Stop, read.StopOffset, read.Stage, read.DecisionId, read.Multiplier)); + CollectionAssert.AreEqual(example.Features.ToList(), read.Features.OrderBy(f => f.Key, StringComparer.Ordinal).Reverse().ToList()); + Assert.HasCount(1, await store.OpenAsync(none).ConfigureAwait(false)); + + var label = new CaseLabel(true, 0.0123, First.AddDays(1), First.AddDays(4), "meanrev_exit_rsi"); + await store.AddLabelAsync(id, label, none).ConfigureAwait(false); + await store.AddLabelAsync(id, label with { Win = false }, none).ConfigureAwait(false); + Assert.AreEqual(label, (await store.AllAsync(none).ConfigureAwait(false)).Single().Label); + Assert.HasCount(0, await store.OpenAsync(none).ConfigureAwait(false)); + } + + /// + /// Live: the examples are those of the history on the same days, with the same clues, both for a strategy that trades + /// and for one in observation; a restart in the middle adds none. + /// + [TestMethod] + [TestCategory(Category.Integration)] + [DataRow(StrategyStages.Simulation)] + [DataRow(StrategyStages.Observation)] + public async Task TheLiveEngineSavesTheSameExamplesAsTheHistory(string stage) + { + var from = new DateOnly(2026, 6, 1); + var last = from.AddDays(40); + await using var rig = await LiveRig.CreateAsync(from, last, stage: stage).ConfigureAwait(false); + for (var day = from; day <= last; day = day.AddDays(1)) + { + await rig.DayAsync(day, morning: 6).ConfigureAwait(false); + if (day == from.AddDays(17)) + { + await rig.RestartAsync().ConfigureAwait(false); + } + } + + var data = new BacktestDataset(LiveRig.Coins.Select(c => new BacktestInstrument(rig.Instruments[c].Spec, rig.Bars[c].Where(b => b.Day < last).ToList())), "EUR"); + var expected = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, + StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { From = from.AddDays(-1) })); + var live = await new LearningStore(rig.Rig.Db, rig.Rig.Clock).AllAsync(CancellationToken.None).ConfigureAwait(false); + Assert.IsGreaterThan(1, expected.Count); + Assert.AreEqual(string.Join(", ", expected.Select(e => $"{e.Symbol} {e.Day:MM-dd}")), string.Join(", ", live.Select(e => $"{e.Symbol} {e.Day:MM-dd}"))); + foreach (var (a, b) in expected.Zip(live)) + { + Assert.AreEqual(stage, b.Stage); + Assert.AreEqual(Text(a), string.Join(';', b.Features.Where(f => a.Features.ContainsKey(f.Key)).OrderBy(f => f.Key, StringComparer.Ordinal) + .Select(f => f.Key + "=" + f.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)))); + } + } +} diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index dcf04c4..79afb8d 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -110,6 +110,7 @@ internal sealed class LiveRig : IAsyncDisposable { AccountReady = _ => AccountStarted, Gate = Gate, + Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock), }; }