Fase 8 — Apprendimento #109

Merged
Alby96 merged 8 commits from fase-8 into main 2026-12-01 16:58:07 +01:00
18 changed files with 371 additions and 26 deletions
Showing only changes of commit c7e462b6f4 - Show all commits

No files matched your search

+1 -1
View File
@@ -120,7 +120,7 @@ Aggiornato: 2026-12-01
- Ciclo continuo (#64): stime in ombra, controllo ogni notte alle 03:00, messa da parte e rientro automatici, sfidante la domenica, promozione o scarto a soglie fisse, avvio solo con i criteri di 11.5. Il moltiplicatore sta tra 0 e 1 e vale per l'operazione dalla nascita alla chiusura.
- Altri apprendimenti (#65): scostamento misurato sulle esecuzioni, impatto delle notizie, scoperte dette a parole.
- Schermata Apprendimento come il mockup 06 e sezione del modello in Impostazioni (#66).
- Correzioni della revisione indipendente (#67, ADR 0018 punto 17).
- Correzioni di due revisioni indipendenti (#67, ADR 0018 punti 17 e 18).
## In corso
+12 -1
View File
@@ -62,7 +62,7 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
**10. Domenica.** Senza sfidante se ne addestra uno, se ci sono esiti nuovi rispetto all'ultimo addestramento; con uno sfidante si guarda solo se i casi di confronto hanno passato una nuova soglia. Una domenica persa si recupera al primo controllo, una volta sola. Una promozione annullata lascia la versione tra le annullate: non torna da sola.
- Le strategie senza frequenza di base non addestrano: nessuno potrebbe stimarle.
**11. Avvio (11.5).** I 300 segnali sono quelli con un esito. Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte.
**11. Avvio (11.5).** I 300 segnali sono quelli con un esito; almeno 100 devono essere di strategie con capitale (punto 18). Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte.
**12. Scostamento (11.6).** Il primo controllo notturno di ogni mese confronta, per fascia di liquidità (azioni; BTC, ETH e SOL; altre crypto), lo scostamento delle esecuzioni di conti di prova e reali degli ultimi 365 giorni. La fascia è l’unica variabile della regressione: il suo risultato è la media, con un intervallo al 95% a blocchi.
- Servono 30 esecuzioni. Gli stop scattati non contano: il salto di prezzo è già nel modo in cui simulatore e backtest li eseguono.
@@ -95,3 +95,14 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
- Una precisione sotto la soglia d'allarme non si mostra mai come 50%.
- La conferma di una stima di costo e "ho visto l'assenza" controllano il codice della pagina (CSRF), come gli altri moduli.
- La scheda di un'operazione mostra la stima anche quando il segnale è nato giorni prima dell'acquisto, e dice se il modello era messo da parte.
**18. Seconda lettura, sulle correzioni** (quattro lettori a contesto pulito, ogni rilievo passato da chi provava a smentirlo).
- **Avvio (11.5)**: il miglioramento si misura su almeno 100 segnali di strategie con capitale, oltre ai 300 in tutto. Prima ne bastava uno: l'intervallo su pochi casi aveva larghezza zero. Con meno di tre blocchi (30 casi) un intervallo non dice più niente. Questi segnali si pesano per maturazione tra loro, non insieme a quelli più vecchi in osservazione. La schermata dice quanti ne mancano.
- **Lavori recuperabili (5.6)**: un lavoro da recuperare conta dal primo avvio che lo conosce (la riga in `jobs` nasce subito). Prima, su un computer sempre spento alle 03:00, la notte del modello non sarebbe mai partita.
- **La notte aspetta le barre**: dopo un'assenza aspetta che lo storico dell'ultimo giorno chiuso sia scaricato, al massimo mezz'ora. Senza rete prosegue con quello che ha.
- **Notizie all'ora della decisione**: una storia si ricostruisce dagli articoli, dai collegamenti e dai giudizi salvati fino a quell'ora, perché cresce anche dopo la prima lettura.
- **Etichetta e trimestrali**: una trimestrale già uscita entro la seduta d'ingresso non chiude l'operazione simulata. Limite: l'orario della trimestrale non è tra gli indizi, quindi quella della seduta d'ingresso vale sempre come uscita. Succede solo con il filtro delle trimestrali spento dall'utente.
- Una promozione annullata fa ripartire da zero le soglie dello sfidante in prova.
- Una stima che fallisce vale 1 solo per l'operazione nuova; quelle già nate tengono il loro moltiplicatore.
- Scheda dell'operazione: la riga del modello si cerca quando manca nella decisione dell'acquisto, non in tutta la finestra, e vale anche se l'operazione simulata si è chiusa lo stesso giorno. Una riduzione non si scrive mai "al 100%" né "al 0%".
- La frase "è ben tarato" sui segnali dal vivo usa l'errore del criterio di avvio, come il resto della pagina; punti e percentuali restano conteggi semplici.
+25 -2
View File
@@ -377,6 +377,11 @@ internal sealed partial class AnubisHost(
lastDues[name] = due;
}
if (!options.Demo)
{
await StartCountingAsync([.. SchedulerJobs(backups)], lastDues, cancellationToken).ConfigureAwait(false);
}
if (_sampler is not null)
{
await _sampler.TakeAsync(SampleKinds.Start, cancellationToken).ConfigureAwait(false);
@@ -506,13 +511,31 @@ internal sealed partial class AnubisHost(
!options.Demo && (overrides is null ? true : overrides.Trading == true) &&
environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false");
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
private IEnumerable<ScheduledJob> SchedulerJobs(Backups backups)
{
// A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6).
var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) };
foreach (var job in new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []))
return new[] { backup }.Concat(_sampler is { } sampler ? new[] { sampler.Job() } : []).Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? []);
}
/// <summary>
/// A job to make up for after an absence counts from the first start that knows it. Otherwise a computer always off at
/// its hour would never make it: without a first run there would be no run to find missed (SPEC 5.6).
/// </summary>
private Task StartCountingAsync(IReadOnlyList<ScheduledJob> jobs, Dictionary<string, DateTimeOffset> lastDues, CancellationToken cancellationToken) => _db!.WriteAsync(async s =>
{
foreach (var job in jobs.Where(j => j.CatchUpWithin is not null && !lastDues.ContainsKey(j.Name)))
{
await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, created_at, updated_at) VALUES (@id, @n, @d, @now, @now, @now) ON CONFLICT (name) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("n", job.Name), ("d", job.Description), ("now", clock.UtcNow)).ConfigureAwait(false);
}
}, cancellationToken);
private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary<string, DateTimeOffset> lastDues)
{
foreach (var job in SchedulerJobs(backups))
{
scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null);
}
+13 -6
View File
@@ -230,7 +230,7 @@ internal sealed record LearningView
Missing = state.ActivatedAt is null && activation.Enough ? Missings(activation) : [],
LastTraining = last is null ? "mai" : $"{LongDay(DayOf(last.TrainedAt), now)}, versione {last.Version}",
Bands = bands,
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands),
BandsText = bands.Count == 0 ? "Nessuna stima ha ancora un esito." : BandsWords(bands, history ? null : activation.CalibrationError),
BandsFromHistory = history && bands.Count > 0,
Champion = Column(champion, now),
Challenger = Column(challenger, now),
@@ -341,7 +341,11 @@ internal sealed record LearningView
: $"Nessuna fascia di probabilità ha ancora {Judge.BandMin} casi.");
}
if (!check.Improves)
if (check.Funded < ActivationCheck.FundedNeeded)
{
missing.Add($"Servono almeno {ActivationCheck.FundedNeeded} segnali di strategie con un capitale, anche in simulazione: per ora {(check.Funded == 1 ? "è uno" : $"sono {Format.Number(check.Funded)}")}.");
}
else if (!check.Improves)
{
missing.Add("Non è ancora provato che, filtrando lui, si guadagni di più per operazione proposta: la differenza può essere caso.");
}
@@ -353,8 +357,11 @@ internal sealed record LearningView
private static LearningBand Band(CalibrationBand b) => new((int)Math.Round(b.From * 100), (int)Math.Round(b.To * 100), b.Cases, Round(b.Estimated * 100, 1), Round(b.Observed * 100, 1));
/// <summary>The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not count.</summary>
public static string BandsWords(IReadOnlyList<LearningBand> bands)
/// <summary>
/// The sentence under the chart: the highest band that counts, whether it is well calibrated, the bands that do not
/// count. <paramref name="measured"/> is the error of the criterion to start counting (11.5), when it is the judge.
/// </summary>
public static string BandsWords(IReadOnlyList<LearningBand> bands, double? measured = null)
{
ArgumentNullException.ThrowIfNull(bands);
var solid = bands.Where(b => b.Solid).ToList();
@@ -363,10 +370,10 @@ internal sealed record LearningView
return $"Nessuna fascia ha ancora {Judge.BandMin} casi: troppo pochi per contarci.";
}
var error = solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
var error = measured is { } known ? Round(known * 100, 1) : solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases);
var best = solid[^1];
var text = $"Quando stima tra il {best.From} e il {best.To}%, è andata bene il {Format.Number(best.Observed)}% delle volte: " +
(error < (decimal)ActivationCheck.MaxCalibrationError * 100 ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
((measured is { } exact ? exact < ActivationCheck.MaxCalibrationError : error < (decimal)ActivationCheck.MaxCalibrationError * 100) ? "è ben tarato." : $"non è ancora ben tarato, in media sbaglia di {Format.Number(error, 1)} punti.");
var above = bands.Where(b => !b.Solid && b.From >= best.To).ToList();
var below = bands.Where(b => !b.Solid && b.To <= solid[0].From).ToList();
var between = bands.Where(b => !b.Solid).Except(above).Except(below).Sum(b => b.Cases);
+1 -1
View File
@@ -77,7 +77,7 @@ internal static class ReasonTexts
var applied = Number("applied") ?? 1;
if (applied < 1)
{
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {applied * 100:0}%") : said + ": acquisto non fatto";
return applied > 0 ? string.Create(it, $"{said}: acquisto ridotto al {Math.Clamp(Math.Round(applied * 100), 1, 99):0}%") : said + ": acquisto non fatto";
}
bool Is(string name) => json.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
+6 -3
View File
@@ -180,9 +180,9 @@ internal sealed record TradesView(
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
var m = d.Any(x => x.Stage == DecisionStages.Model) ? [] : await s.QueryAsync(
var m = await s.QueryAsync(
"SELECT d.outcome, d.data FROM decisions d JOIN ml_features f ON f.decision_id = d.decision_id AND f.symbol = d.symbol LEFT JOIN ml_labels l ON l.feature_id = f.id " +
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day > @o) ORDER BY d.created_at DESC LIMIT 1",
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day >= @o) ORDER BY d.created_at DESC LIMIT 1",
r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), ("st", DecisionStages.Model), ("s", t.Strategy), ("sym", t.Symbol), ("t", t.OpenedAt.AddMinutes(5)),
("o", DateOnly.FromDateTime(t.OpenedAt.UtcDateTime).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
return (e, d, m);
@@ -200,7 +200,10 @@ internal sealed record TradesView(
: sell.Purpose is "stop" or "protective" ? "stop" : null;
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
List<WhyLine> bought = [.. Lines(buy.Key), .. earlier.SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
// The decision of the purchase has its own line when the example was born with it.
var own = buy.Key is not null && byKey.TryGetValue(buy.Key, out var entryRows) && entryRows.Any(r => r.Stage == DecisionStages.Model);
List<WhyLine> bought = [.. Lines(buy.Key), .. (own ? [] : earlier).SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
return (bought, sold, entrySlip, exitSlip, code);
}
}
+1 -1
View File
@@ -232,7 +232,7 @@ public sealed class OutsideReader(Database db, IClock clock, SettingsStore? sett
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);
var stories = await _desk.StoriesAtAsync(NewsDesk.Target(spec), at - NewsRules.NormWindow, at, 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);
}
+6 -1
View File
@@ -146,7 +146,7 @@ public static class CaseLabels
/// <summary>
/// The outcome with the bars of <paramref name="data"/> up to <paramref name="through"/>; null while the operation is
/// open. The strategy is built fresh: it walks the bars again. <paramref name="earnings"/> is the first report after the
/// decision, which <c>equity_meanrev</c> leaves before.
/// decision, which <c>equity_meanrev</c> leaves before; one out by the entry session is not ahead any more.
/// </summary>
public static CaseLabel? Of(Example example, Func<IStrategy> strategy, BacktestDataset data, DateOnly through, CostModel? costs = null, DateOnly? earnings = null)
{
@@ -158,6 +158,11 @@ public static class CaseLabels
return null;
}
if (earnings is { } report && (instrument.Bars.FirstOrDefault(b => b.Day > example.Day) is not { } entry || report <= entry.Day))
{
earnings = 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))
{
+12 -6
View File
@@ -195,26 +195,32 @@ public sealed record ActivationCheck(int Evaluated, Scores Scores, double? Calib
public const double MaxCalibrationError = 0.05;
/// <summary>The improvement is measured on at least this many signals of strategies with capital (ADR 0018).</summary>
public const int FundedNeeded = 100;
/// <summary>The signals of strategies with capital at that moment: those the improvement is measured on.</summary>
public int Funded { get; init; }
public bool Enough => Evaluated >= Needed;
public bool Calibrated => CalibrationError is { } error && error < MaxCalibrationError;
public bool Improves => Low > 0;
public bool Improves => Funded >= FundedNeeded && Low > 0;
public bool Passed => Enough && Calibrated && Improves;
/// <summary>
/// On the estimates that were in charge when each signal came, whatever version made them, weighed by maturation; the
/// improvement only on signals of strategies with capital at that moment.
/// improvement only on signals of strategies with capital at that moment, weighed among themselves.
/// </summary>
public static ActivationCheck Of(IReadOnlyList<Estimate> inCharge, IReadOnlyDictionary<string, double> baseRates, IReadOnlyDictionary<string, double> capital)
{
ArgumentNullException.ThrowIfNull(inCharge);
var weighed = Judge.Weigh(inCharge, baseRates);
var scores = Judge.Score(weighed, capital, IsFunded);
var funded = weighed.Where(e => IsFunded(e.Case)).ToList();
var funded = Judge.Weigh([.. inCharge.Where(e => IsFunded(e.Case))], baseRates);
var paid = Judge.Score(funded, capital);
var scores = Judge.Score(Judge.Weigh(inCharge, baseRates), capital) with { GainWithout = paid.GainWithout, GainWith = paid.GainWith };
var (low, high) = Judge.Interval([.. funded.Select(e => (e.Multiplier - 1) * Judge.Gain(e.Case, capital))], [.. funded.Select(e => e.Weight)], 0.90);
return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high);
return new ActivationCheck(inCharge.Count, scores, scores.CalibrationError, low, high) { Funded = funded.Count };
}
/// <summary>A signal of a strategy that had capital: zeroing those of a candidate in observation is no merit (SPEC 11.3).</summary>
+8 -2
View File
@@ -177,7 +177,8 @@ public static class Judge
/// <summary>
/// A bootstrap interval of the weighted mean of <paramref name="values"/> that keeps neighbours together: blocks of
/// <paramref name="block"/> in a row, because operations close in time win and lose together.
/// <paramref name="block"/> in a row, because operations close in time win and lose together. With fewer than three
/// blocks nothing can be said: the interval is everything.
/// </summary>
public static (double Low, double High) Interval(IReadOnlyList<double> values, IReadOnlyList<double> weights, double confidence, int block = 10, int rounds = 2000, long seed = 20_261_201)
{
@@ -189,7 +190,12 @@ public static class Judge
return (0, 0);
}
var size = Math.Clamp(block, 1, n);
var size = Math.Max(block, 1);
if (n < 3 * size)
{
return (double.NegativeInfinity, double.PositiveInfinity);
}
var random = new FixedRandom(seed);
var means = new double[rounds];
for (var r = 0; r < rounds; r++)
+7
View File
@@ -319,6 +319,13 @@ public sealed class LearningCycle(Database db, IClock clock, LearningDesk desk,
await ModelStore.SetStatusAsync(s, clock, champion.Id, ModelStatuses.Undone, cancellationToken).ConfigureAwait(false);
await ModelStore.SetStatusAsync(s, clock, previous, ModelStatuses.Champion, cancellationToken).ConfigureAwait(false);
// The one on trial starts again: its cases of comparison were against the model just taken away.
if (await ModelStore.FindAsync(s, ModelStatuses.Challenger).ConfigureAwait(false) is { } trial)
{
await ModelStore.SetThresholdAsync(s, clock, trial.Id, 0, cancellationToken).ConfigureAwait(false);
}
var text = $"Promozione annullata da te: torna in carica la versione {back.Version} al posto della {champion.Version}.";
await ModelStore.AddEventAsync(s, clock, ModelEvents.Undone, back.Version, text, cancellationToken).ConfigureAwait(false);
await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "model_undone", text, null, cancellationToken).ConfigureAwait(false);
+10 -1
View File
@@ -314,7 +314,16 @@ public sealed class LearningTurn
{
if (context.Day == _day && _collector.Cases.FirstOrDefault(c => c.Symbol == symbol) is { } made)
{
return AppliedTo(made);
try
{
return AppliedTo(made);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Only the new operation goes on as without a model: those already born keep their multiplier.
_failed(ex);
return 1;
}
}
// The operation was born with the latest example before this day: without one, or with nothing held of one already
+20
View File
@@ -31,6 +31,26 @@ public sealed class NewsDesk(Database db, IClock clock, SettingsStore? settings
"WHERE l.scope = @scope AND l.target = @t AND st.last_seen_at >= @since ORDER BY st.published_at, st.id",
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since)), cancellationToken).ConfigureAwait(false);
/// <summary>
/// The stories as they were at <paramref name="at"/>: only the articles, the links and the verdicts saved by then. A
/// story keeps growing after it is first read, and a decision recovered hours later must not see it grown (11.2).
/// </summary>
public async Task<IReadOnlyList<StoryFact>> StoriesAtAsync(string target, DateTimeOffset since, DateTimeOffset at, CancellationToken cancellationToken)
{
const string Then = "FROM news_items i WHERE i.story_id = st.id AND i.created_at <= @at";
const string Highest = "(SELECT MAX(x.importance) FROM news_items x WHERE x.story_id = st.id AND x.created_at <= @at)";
return await db.ReadAsync(s => s.QueryAsync(
"SELECT st.id, st.title, st.published_at, st.first_seen_at, (SELECT COUNT(DISTINCT i.publisher) " + Then + ") AS sources, " +
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = st.id AND i.created_at <= @at AND so.trusted = @yes) > 0 AS trusted, " +
"(SELECT AVG(i.score) " + Then + ") AS score, (SELECT i.severe " + Then + " AND i.severe IS NOT NULL ORDER BY " + NewsStore.SevereOrder + ", i.id LIMIT 1) AS severe, " +
Highest + " AS importance, (SELECT MIN(i.published_at) " + Then + " AND i.importance = " + Highest + ") AS raised_at, " +
"v.direction AS model_direction, v.importance AS model_importance, v.instruments AS model_instruments, v.problem AS model_problem, " +
"(SELECT i.publisher " + Then + " ORDER BY i.created_at, i.id LIMIT 1) AS publisher " +
"FROM news_stories st JOIN news_links l ON l.story_id = st.id LEFT JOIN news_verdicts v ON v.id = st.verdict_id AND v.created_at <= @at " +
"WHERE l.scope = @scope AND l.target = @t AND l.created_at <= @at AND st.last_seen_at >= @since AND EXISTS (SELECT 1 " + Then + ") ORDER BY st.published_at, st.id",
r => ReadStory(r, [target]), ("scope", LinkScopes.Instrument), ("t", target), ("since", since), ("at", at), ("yes", true)), cancellationToken).ConfigureAwait(false);
}
/// <summary>The state of 10.2 point 6 of one instrument now.</summary>
public async Task<InstrumentNewsState> StateAsync(string target, CancellationToken cancellationToken)
{
+1 -1
View File
@@ -259,7 +259,7 @@ public sealed class NewsStore(Database db, IClock clock)
"(SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = news_stories.id AND so.trusted = @yes) > 0";
// The serious cases in the order of 10.2.
private const string SevereOrder =
internal const string SevereOrder =
"CASE i.severe WHEN '" + SevereKinds.Cyberattack + "' THEN 1 WHEN '" + SevereKinds.Suspension + "' THEN 2 WHEN '" + SevereKinds.Fraud + "' THEN 3 WHEN '" +
SevereKinds.Bankruptcy + "' THEN 4 WHEN '" + SevereKinds.Investigation + "' THEN 5 ELSE 6 END";
+31
View File
@@ -531,9 +531,40 @@ public sealed partial class TradingService : IDisposable
/// <summary>The slippage in force, from the next fill of the simulator on.</summary>
public async Task RefreshCostsAsync(CancellationToken cancellationToken) => _slippage = await Costs.TableAsync(cancellationToken).ConfigureAwait(false);
/// <summary>The longest the night waits for the bars: without a network it goes on with those it has.</summary>
public static readonly TimeSpan BarsWait = TimeSpan.FromMinutes(30);
/// <summary>
/// Waits until the bars through the last closed day are downloaded: after an absence the night starts with the process,
/// and labels made on the bars of before would see nothing of what happened meanwhile (SPEC 5.6, 9.4).
/// </summary>
public static async Task BarsReadyAsync(IClock clock, Func<DateTimeOffset?> lastRound, Func<Task> ask, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(lastRound);
ArgumentNullException.ThrowIfNull(ask);
var now = clock.UtcNow;
var midnight = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
if (lastRound() >= midnight)
{
return;
}
await ask().ConfigureAwait(false);
while (!(lastRound() >= midnight) && clock.UtcNow < now + BarsWait)
{
await clock.WaitUntilAsync(clock.UtcNow + TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);
}
}
// A part of the night that fails never stops the others.
private async Task NightAsync(CancellationToken cancellationToken)
{
if (_market is { } market)
{
await BarsReadyAsync(_clock, () => market.LastHistoryRun, market.WakeWorker, cancellationToken).ConfigureAwait(false);
}
try
{
await Cycle.RunAsync(cancellationToken).ConfigureAwait(false);
+13
View File
@@ -1,6 +1,7 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.Strategies;
using Anubis.Trading;
@@ -99,11 +100,23 @@ public sealed class LearningCasesTests
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 ArticleAsync(s, rig, id, title, published, seen, 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);
}
/// <summary>An article of a story, saved at a moment, from a source of its own.</summary>
internal static async Task ArticleAsync(DbSession s, TradingRig rig, Guid story, string title, DateTimeOffset published, DateTimeOffset saved, double score, int importance = 1)
{
var (source, item) = (Ids.NewId(rig.Clock), Ids.NewId(rig.Clock));
await s.ExecuteAsync("INSERT INTO news_sources (id, url, name, kind, trusted, enabled, failures, created_at, updated_at) VALUES (@id, @u, @u, 'rss', @yes, @yes, 0, @f, @f)",
("id", source), ("u", "https://t/" + source), ("yes", true), ("f", saved)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, language, published_at, score, importance, created_at) " +
"VALUES (@id, @st, @so, @u, @u, @pub, @t, 'en', @p, @s, @i, @f)", ("id", item), ("st", story), ("so", source), ("u", "https://t/a/" + item), ("pub", "t" + source), ("t", title), ("p", published), ("s", score),
("i", importance), ("f", saved)).ConfigureAwait(false);
}
/// <summary>Enters while not held, on a fixed day leaves; every day proposes again what it does not hold.</summary>
private sealed class Stubborn(DateOnly from, DateOnly exit, decimal weight = 0.3m, decimal? stop = null) : IStrategy
{
+185
View File
@@ -269,6 +269,191 @@ public sealed class LearningReviewTests
Assert.IsNull(Clues.ReportOf(With(StrategyNames.EquityMomentum, 6)));
}
private static Estimate Closed(int i, bool win, string stage, double p) => new(Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(i)) with
{
Id = Guid.NewGuid(),
Stage = stage,
Label = new CaseLabel(win, win ? 0.02 : -0.02, From.AddDays(i + 1), From.AddDays(i + 2), "x"),
}, p, 0.4, MultiplierRule.Standard.Of(p, 0.4));
private static readonly Dictionary<string, double> Money = new() { [StrategyNames.CryptoTrend] = 1000 };
/// <summary>SPEC 11.5: three hundred signals in observation and a handful with capital prove no gain, however lucky.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AFewFundedSignalsNeverStartTheModel()
{
List<Estimate> observed = [.. Enumerable.Range(0, 400).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
ActivationCheck With(int funded) => ActivationCheck.Of([.. observed, .. Enumerable.Range(0, funded).Select(i => Closed(1000 + i, i * 7 % 25 < 9, StrategyStages.Simulation, 0.36))], Rates.BaseRates, Money);
foreach (var few in new[] { 1, 5, 10, 30, 99 })
{
var check = With(few);
Assert.AreEqual((few, true, true), (check.Funded, check.Enough, check.Calibrated));
Assert.IsFalse(check.Improves || check.Passed, $"{few} signals");
}
Assert.IsTrue(With(100).Passed, "the same advantage on enough of them");
Assert.AreEqual((double.NegativeInfinity, double.PositiveInfinity), Judge.Interval([1, 1, 1], [1, 1, 1], 0.9), "nothing can be said of three");
}
/// <summary>SPEC 11.4: the signals with capital are weighed among themselves, not with the older ones in observation.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheGainIsWeighedOnTheSignalsItIsMeasuredOn()
{
List<Estimate> observed = [.. Enumerable.Range(0, 200).Select(i => Closed(i, i % 5 < 2, StrategyStages.Observation, 0.41))];
// Of those with capital only the losses have matured so far, nearly: without weights the filter would look good.
List<Estimate> funded = [.. Enumerable.Range(0, 100).Select(i => Closed(1000 + i, i % 10 == 0, StrategyStages.Simulation, 0.36))];
var check = ActivationCheck.Of([.. observed, .. funded], Rates.BaseRates, Money);
var alone = Judge.Score(Judge.Weigh(funded, Rates.BaseRates), Money);
Assert.AreEqual(alone.GainWithout, check.Scores.GainWithout, 1e-9);
Assert.AreEqual(alone.GainWith, check.Scores.GainWith, 1e-9);
Assert.AreEqual((0.4 * 0.02 * 200) - (0.6 * 0.02 * 200), check.Scores.GainWithout, 1e-9, "wins and losses in the proportion of the base rate");
}
/// <summary>A report already out when the operation starts is not one to leave before (ADR 0017, point 5).</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void AReportAlreadyOutDoesNotCloseTheLabel()
{
var bars = Enumerable.Range(0, 10).Select(i => new DailyBar(From.AddDays(i), 100, 101, 99, 100, 1e6)).ToList();
var data = new BacktestDataset([new BacktestInstrument(MarketDataStoreTests.Okx("BTC-EUR") with { ListedAt = null }, bars)], "EUR");
var example = Open(StrategyNames.CryptoTrend, "BTC-EUR", From.AddDays(1));
DateOnly? ClosedWith(int report) => CaseLabels.Of(example, () => new LeavesBeforeReports(), data, From.AddDays(9), earnings: From.AddDays(report))?.ClosedDay;
Assert.IsNull(ClosedWith(1), "the evening of the decision");
Assert.IsNull(ClosedWith(2), "the day of the purchase");
Assert.AreEqual(From.AddDays(4), ClosedWith(4), "sold at the open of the day of the report");
Assert.AreEqual(From.AddDays(7), ClosedWith(7));
}
private sealed class LeavesBeforeReports : IStrategy
{
public string Id => StrategyNames.CryptoTrend;
public string Version => "t";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => ["BTC-EUR"];
public IReadOnlyList<Intent> Decide(StrategyContext context) =>
!context.Portfolio.Holds("BTC-EUR") ? [new Intent("BTC-EUR", 0.2m, "x") { Strength = 0.5 }]
: context.NextEarnings?.Invoke("BTC-EUR") is { } report && context.NextSession is { } next && report <= next ? [new Intent("BTC-EUR", 0m, "report")] : [];
}
/// <summary>SPEC 5.6: a computer off every night from the day of the installation still makes the night at its return.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AJobNeverMadeCountsFromTheFirstStart()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true).ConfigureAwait(false);
var rows = await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE name IN ('modello', 'backup')",
r => (Name: r.Text("name"), Due: r.MomentOrNull("last_due_at"))), _none).ConfigureAwait(false);
Assert.HasCount(2, rows);
Assert.IsTrue(rows.All(r => r.Due is not null), "the next start has something to count from");
var clock = new ManualClock(rows[0].Due!.Value.AddDays(2));
var scheduler = new Scheduler(clock, new EventBus());
var runs = 0;
scheduler.Add(TradingService.ModelJob(_ => Task.FromResult(runs++)), rows.First(r => r.Name == "modello").Due);
await scheduler.RunDueAsync(_none).ConfigureAwait(false);
await scheduler.BesideAsync().ConfigureAwait(false);
Assert.AreEqual(1, runs);
}
/// <summary>SPEC 5.6, 9.4: the night made up for at the return waits for the bars of the absence, but not for ever.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task TheNightWaitsForTheBars()
{
var midnight = new DateTimeOffset(2027, 3, 8, 0, 0, 0, TimeSpan.Zero);
var clock = new ManualClock(midnight.AddHours(8));
DateTimeOffset? last = midnight.AddDays(-3);
var asked = 0;
Task Ready() => TradingService.BarsReadyAsync(clock, () => last, () => Task.FromResult(asked++), _none);
var waiting = Ready();
clock.Advance(TimeSpan.FromMinutes(5));
await Task.Delay(50, _none).ConfigureAwait(false);
Assert.IsFalse(waiting.IsCompleted);
last = clock.UtcNow;
await AdvanceAsync(waiting).ConfigureAwait(false);
Assert.AreEqual(1, asked);
await Ready().ConfigureAwait(false);
Assert.AreEqual(1, asked, "the bars of today are there");
// No network: after half an hour it goes on.
last = null;
var offline = Ready();
clock.Advance(TimeSpan.FromMinutes(29));
await Task.Delay(50, _none).ConfigureAwait(false);
Assert.IsFalse(offline.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(2));
await AdvanceAsync(offline).ConfigureAwait(false);
async Task AdvanceAsync(Task task)
{
for (var i = 0; i < 100 && !task.IsCompleted; i++)
{
clock.Advance(TimeSpan.FromSeconds(10));
await Task.Delay(20, _none).ConfigureAwait(false);
}
Assert.IsTrue(task.IsCompletedSuccessfully);
}
}
/// <summary>SPEC 11.4: with the promotion taken back, the one on trial is judged again from the first threshold.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnUndonePromotionStartsTheTrialAgain()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var old = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.3), ModelStatuses.Retired).ConfigureAwait(false);
var champion = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.4), ModelStatuses.Champion).ConfigureAwait(false);
var trial = await LearningCycleTests.AddModelAsync(rig.Db, rig.Clock, LearningCycleTests.Always(0.5), ModelStatuses.Challenger).ConfigureAwait(false);
await rig.Db.WriteAsync(async s =>
{
await ModelStore.SetReplacedAsync(s, rig.Clock, champion.Id, old.Id, _none).ConfigureAwait(false);
await ModelStore.SetThresholdAsync(s, rig.Clock, trial.Id, 150, _none).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
Assert.IsTrue(await LearningCycle.UndoPromotionAsync(rig.Db, rig.Clock, _none).ConfigureAwait(false));
var after = await new ModelStore(rig.Db).FindAsync(ModelStatuses.Challenger, _none).ConfigureAwait(false);
Assert.AreEqual((trial.Id, 0), (after!.Id, after.ThresholdDone));
}
/// <summary>SPEC 11.2: a story that grew after the decision was due is seen as it was then, articles, links and verdict.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStoryIsSeenAsItWasWhenTheDecisionWasDue()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var at = rig.Clock.UtcNow;
var story = Ids.NewId(rig.Clock);
Task LinkAsync(Database db, string target, DateTimeOffset when) => db.WriteAsync(s => s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, 'instrument', @t, 'name', @f)",
("id", Ids.NewId(rig.Clock)), ("st", story), ("t", target), ("f", when)), _none);
await rig.Db.WriteAsync(async s =>
{
// The row as it is now, grown: negative, serious, linked to one more coin.
await s.ExecuteAsync("INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, severe, importance, created_at, updated_at) " +
"VALUES (@id, 't', 't', @p, @f, @l, 2, @yes, -0.4, 'fraud', 4, @f, @l)", _none, ("id", story), ("p", at.AddHours(-5)), ("f", at.AddHours(-4)), ("l", at.AddHours(8)), ("yes", true)).ConfigureAwait(false);
await LearningCasesTests.ArticleAsync(s, rig, story, "first", at.AddHours(-5), at.AddHours(-4), 0.1).ConfigureAwait(false);
await LearningCasesTests.ArticleAsync(s, rig, story, "later", at.AddHours(3), at.AddHours(8), -0.9, 4).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
await LinkAsync(rig.Db, "okx:BTC-EUR", at.AddHours(-4)).ConfigureAwait(false);
await LinkAsync(rig.Db, "okx:ETH-EUR", at.AddHours(8)).ConfigureAwait(false);
rig.Clock.Set(at.AddHours(9));
var reader = new OutsideReader(rig.Db, rig.Clock);
var specs = new Dictionary<string, InstrumentSpec> { ["BTC-EUR"] = TradingRig.Btc, ["ETH-EUR"] = TradingRig.Btc with { Symbol = "ETH-EUR" } };
var then = await reader.ReadAsync(at, specs, null, _none).ConfigureAwait(false);
Assert.AreEqual(0.1, then.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
Assert.IsNull(then.News["BTC-EUR"].Active);
Assert.AreEqual((1, 0), (then.Stories3Days["BTC-EUR"], then.Stories3Days["ETH-EUR"]));
var now = await reader.ReadAsync(at.AddHours(9), specs, null, _none).ConfigureAwait(false);
Assert.AreEqual(-0.4, now.News["BTC-EUR"].Tone1Day!.Value, 1e-9);
Assert.AreEqual(4, now.News["BTC-EUR"].Active!.Story.RuleImportance);
Assert.AreEqual(1, now.Stories3Days["ETH-EUR"]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APrecisionUnderTheAlarmNeverReadsFiftyPercent()
+19
View File
@@ -67,6 +67,17 @@ public sealed class LearningScreenTests
{ DecisionId = earlier }, _none);
}, _none);
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
// Born the evening before, with the simulated operation closed on the day of the purchase: still the one bought.
var opened = (await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT t.opened_at FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE i.symbol = 'MSFT' AND t.status = 'closed' ORDER BY t.opened_at DESC LIMIT 1", r => (DateTimeOffset?)r.Moment("opened_at")), _none))!.Value;
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE decisions SET created_at = @at WHERE decision_id = @d", _none, ("at", opened.AddHours(-10)), ("d", earlier));
var example = (await s.FirstOrDefaultAsync("SELECT id FROM ml_features WHERE decision_id = @d", r => (Guid?)r.Id("id"), ("d", earlier)))!.Value;
var day = DateOnly.FromDateTime(opened.UtcDateTime);
await LearningStore.AddLabelAsync(s, clock, example, new CaseLabel(false, -0.01, day.AddDays(-2), day, "x"), _none);
}, _none);
HasAll(await server.TextAsync("/operazioni"), "Il modello stimava il 61% di probabilità di guadagno (di solito 48%)");
using var post = await server.PostFormAsync("/apprendimento", "/azioni/modello/annulla-promozione");
Assert.AreEqual("/apprendimento?errore=motore", ServerHarness.Location(post));
using var settings = await server.PostFormAsync("/impostazioni", "/azioni/modello", (LearningSettings.Aside.Key, "on"));
@@ -316,6 +327,10 @@ public sealed class LearningScreenTests
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":true"), ": era messo da parte, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":false,\"aside\":false"), ": solo osservazione, non ha cambiato la dimensione");
StringAssert.EndsWith(Line(",\"counts\":true,\"aside\":false"), ": taglia piena");
string Reduced(string applied) => ReasonTexts.Model("{\"probability\":0.61,\"base_rate\":0.48,\"applied\":" + applied + "}")!;
StringAssert.EndsWith(Reduced("0.996"), ": acquisto ridotto al 99%");
StringAssert.EndsWith(Reduced("0.004"), ": acquisto ridotto al 1%");
StringAssert.EndsWith(Reduced("0"), ": acquisto non fatto");
}
/// <summary>Bands under 20 cases are said unreliable, in the sentence and one by one.</summary>
@@ -332,6 +347,10 @@ public sealed class LearningScreenTests
LearningView.BandsWords([B(30, 1, 0), B(45, 30, 20)]));
StringAssert.EndsWith(LearningView.BandsWords([B(30, 30, 30), B(35, 3, 30), B(45, 30, 47)]), "Nelle fasce di mezzo con meno di 20 casi ha visto solo 3 casi, troppo pochi per contarci.");
Assert.AreEqual("Nessuna fascia ha ancora 20 casi: troppo pochi per contarci.", LearningView.BandsWords([B(30, 19, 30)]));
// The judge is the error of the criterion to start counting, as the rest of the page says it.
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 20)], 0.01), "è andata bene il 20% delle volte: è ben tarato.");
StringAssert.EndsWith(LearningView.BandsWords([B(45, 30, 47)], 0.06), "non è ancora ben tarato, in media sbaglia di 6,0 punti.");
}
/// <summary>The clues after the ninth are "Tutto il resto", the whole stays 100; the sentence about the news follows the numbers.</summary>