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 2338 additions and 11 deletions
Showing only changes of commit 99ff2d9402 - Show all commits

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ TestResults/
docs/
!docs/design/logo/
!docs/backtests/*.outcome.json
!docs/learning/first-model.json
**/*.md
.env
.env.*
+1
View File
@@ -16,6 +16,7 @@ COPY src/Anubis.Guard/ src/Anubis.Guard/
COPY docs/design/logo/ docs/design/logo/
# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
COPY docs/backtests/ docs/backtests/
COPY docs/learning/ docs/learning/
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder.
RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app
+16
View File
@@ -29,3 +29,19 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d
- 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.
**5. Addestramento e scelta.**
- Gli esempi vivono dalla decisione alla chiusura dell'operazione simulata. Due prove, sempre su esempi mai studiati: finestre che avanzano (5 pezzi) e combinazioni purgate (6 gruppi, 2 in verifica, 15 combinazioni). Un esempio che si sovrappone nel tempo a uno di verifica, o comincia nei 10 giorni dopo, non addestra.
- La calibrazione si adatta su stime di esempi non studiati (5 pezzi purgati): Platt sotto 1.000 casi, isotonica sopra. Un punteggio che fuori campione non dice niente, o dice il contrario, diventa la frequenza di base.
- **Regola della scelta, fissata prima dei numeri**: vince il miglior guadagno medio per operazione proposta nelle combinazioni (al decimo di centesimo); a parità, il log-loss più basso; poi gli alberi potenziati. La foresta entra solo se batte gli altri su tutti e due.
- Il guadagno di un esempio è quota chiesta × risultato × capitale della strategia in euro. Se nessuna strategia con capitale ha esempi, si misura su tutte e il rapporto lo dice.
- Ogni tentativo è una riga di `ml_models`: il modello scelto con la sua versione, gli altri come `tried`.
- I pesi degli indizi vengono dal peggioramento delle stime, fuori campione, quando i valori di un gruppo di indizi si mescolano; su 100 con il metodo dei resti più alti.
- Meno di 100 esempi con esito: nessun modello.
**6. Moltiplicatore.** Come in 11.1, con le due soglie nelle Impostazioni (intero fino a 0 punti sotto la frequenza di base, zero da 10 punti sotto). Un numero non valido vale 1: un modello rotto non tocca le operazioni.
**7. Frequenza di base e primo modello.** `anubis learning base` ricostruisce gli esempi di `crypto_trend` sull'universo ampio del suo protocollo, con i parametri in uso, e scrive `docs/learning/first-model.json` (modello, rapporto, frequenze di base, esempi) e il rapporto leggibile. Il file viaggia nel programma come gli esiti dei backtest.
- Al primo avvio, se non ce n'è nessuno, diventa il modello in carica, in osservazione. Un file nuovo (revisione trimestrale) aggiorna frequenze di base ed esempi, non il modello: quello cambia solo con una promozione.
- Una strategia senza frequenza di base non viene stimata: moltiplicatore 1, nessuna stima, non conta tra i segnali valutati. Oggi vale per le due strategie sulle azioni, finché manca lo storico di Alpaca.
- **Esito onesto del primo modello**: 1.844 esempi crypto, 18,3% in guadagno. Nessuno dei tre modelli fa meglio di chi risponde sempre la frequenza di base (log-loss 0,494 contro 0,481 nelle combinazioni); il guadagno medio per operazione proposta passa da +1,69 a +1,76 euro, differenza che non vale niente. Resta in osservazione come tutti i modelli; i criteri di 11.5 lo fermano se non impara altro.
+1
View File
@@ -0,0 +1 @@
{"Through":"2026-10-31","BaseRates":{"crypto_trend":0.18329718004338394},"Model":{"Clues":["strength","stop_distance","volatility","volatility_ratio","volume","market_trend","market_volatility","breadth","weekday_sin","weekday_cos"],"Learned":{"Learner":"logistic","Linear":{"Intercept":-1.5574604345197345,"Weights":[0.1590340105154227,0.11908779476819635,-0.162432512465705,-0.08003982796993969,-0.19132480071600444,0.3022103731539277,0.10780995530583182,-0.23941305842109442,-0.22326128923555164,-0.15096635705365147],"Means":[0.19601108548807236,0.050460482868763604,0.8833982208676783,0.9192900882537972,0.9662490365618214,0.0835851831670285,0.5876342481616039,0.476247288508679,0.08773042725596508,-0.05221374460412148],"Scales":[0.165485155045225,0.04067752287292153,0.4848501513845519,0.310638619072209,1.0200137514523773,0.33648118132548555,0.2603576946488006,0.34682317518394806,0.7017578634342959,0.70506240583181]},"Trees":null},"Calibration":{"Kind":"isotonic","Slope":1,"Offset":0,"Scores":[-3.950815298593455,-2.295424845384458,-1.9151100659396874,-1.7663451007315563,-1.7294273092893189,-1.6834534361695037,-1.6486334946177699,-1.2851328574592205,-0.12266591732662607,0.08702724987460952],"Values":[0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.6666666666666667]},"Ranges":{"strength":{"Low":0.11111111,"High":1,"Cases":1844},"stop_distance":{"Low":0.00554256,"High":0.2,"Cases":1844},"volatility":{"Low":0.22509683,"High":2.6730656,"Cases":1844},"volatility_ratio":{"Low":0.33680145,"High":1.81238384,"Cases":1844},"volume":{"Low":0.31563245,"High":3.85783042,"Cases":1844},"market_trend":{"Low":-0.42829195,"High":1.23482451,"Cases":1844},"market_volatility":{"Low":0.25961056,"High":1.79265636,"Cases":1844},"breadth":{"Low":0,"High":1,"Cases":1844},"weekday_sin":{"Low":-0.97492791,"High":0.97492791,"Cases":1844},"weekday_cos":{"Low":-0.90096887,"High":1,"Cases":1844}},"Strategies":["crypto_trend"]},"Report":{"Examples":1844,"Live":0,"ByStrategy":{"crypto_trend":1844},"BaseRates":{"crypto_trend":0.18329718004338394},"FirstDay":"2019-01-01","LastDay":"2026-10-28","Attempts":[{"Learner":"boosting","Forward":{"Cases":1107,"LogLoss":0.5039820727635489,"BaseLogLoss":0.47884194965218496,"Brier":0.15907636401310338,"Precision":0.49573711063372716,"GainWithout":1.7619015934416593,"GainWith":1.3671192662708858,"Improvement":-0.39478232717077355,"CalibrationError":0.08995233818515404,"Bands":[{"From":0.05,"To":0.1,"Cases":27,"Estimated":0.08513321633688159,"Observed":0.33327967159013155},{"From":0.1,"To":0.15,"Cases":76,"Estimated":0.1205846499171033,"Observed":0.2692438228736069},{"From":0.15,"To":0.2,"Cases":240,"Estimated":0.17557548247994598,"Observed":0.15444000663544563},{"From":0.2,"To":0.25,"Cases":180,"Estimated":0.2232734796319761,"Observed":0.12922452472685167},{"From":0.25,"To":0.3,"Cases":291,"Estimated":0.25353021765415845,"Observed":0.1822752256443538},{"From":0.3,"To":0.35,"Cases":260,"Estimated":0.33272092703111206,"Observed":0.1947431154393129},{"From":0.35,"To":0.4,"Cases":16,"Estimated":0.37353561368298727,"Observed":0.35049852907302864},{"From":0.4,"To":0.45,"Cases":12,"Estimated":0.42519433372299786,"Observed":0.283533030708765},{"From":0.45,"To":0.5,"Cases":5,"Estimated":0.4714069044078384,"Observed":0}]},"Combined":{"Cases":9220,"LogLoss":0.49132446909272104,"BaseLogLoss":0.4806696575091626,"Brier":0.15507682960514105,"Precision":0.5230360608846665,"GainWithout":1.6880808292523108,"GainWith":1.6479770415699562,"Improvement":-0.040103787682354675,"CalibrationError":0.043970436437853075,"Bands":[{"From":0.05,"To":0.1,"Cases":189,"Estimated":0.08358931699861316,"Observed":0.15873015873015872},{"From":0.1,"To":0.15,"Cases":1511,"Estimated":0.13511708396610708,"Observed":0.19324950363997354},{"From":0.15,"To":0.2,"Cases":3905,"Estimated":0.1754909013303589,"Observed":0.18053777208706787},{"From":0.2,"To":0.25,"Cases":1563,"Estimated":0.2136126207759515,"Observed":0.19897632757517594},{"From":0.25,"To":0.3,"Cases":1051,"Estimated":0.26208823479755566,"Observed":0.16079923882017128},{"From":0.3,"To":0.35,"Cases":788,"Estimated":0.3288561548679041,"Observed":0.1700507614213198},{"From":0.35,"To":0.4,"Cases":102,"Estimated":0.3735783374752225,"Observed":0.22549019607843138},{"From":0.4,"To":0.45,"Cases":48,"Estimated":0.42372393439600436,"Observed":0.2916666666666667},{"From":0.45,"To":0.5,"Cases":28,"Estimated":0.47168117170804486,"Observed":0.25},{"From":0.5,"To":0.55,"Cases":15,"Estimated":0.5189195543992838,"Observed":0.13333333333333333},{"From":0.55,"To":0.6,"Cases":8,"Estimated":0.574330374974163,"Observed":0.125},{"From":0.6,"To":0.65,"Cases":3,"Estimated":0.6261332225482069,"Observed":0},{"From":0.65,"To":0.7,"Cases":9,"Estimated":0.6659045693196883,"Observed":0.2222222222222222}]},"Chosen":false},{"Learner":"logistic","Forward":{"Cases":1107,"LogLoss":0.49501524768221683,"BaseLogLoss":0.47884194965218496,"Brier":0.15713196527346796,"Precision":0.5181989063568011,"GainWithout":1.7619015934416593,"GainWLine truncated
+77
View File
@@ -0,0 +1,77 @@
# Primo modello: rapporto di convalida
Generato con `anubis learning base --to 2026-10-31` sullo storico fino al 31/10/2026. Gli stessi dati danno sempre lo stesso modello.
## La domanda
Il modello non prevede i prezzi. Guarda un segnale di una strategia e stima quanto è probabile che l'operazione chiuda in guadagno, al netto dei costi. Può solo rimpicciolire l'operazione.
## Gli esempi
1848 esempi ricostruiti facendo girare le strategie sullo storico: 1844 con un esito, 4 con l'operazione ancora aperta, 0 mai partiti (sotto il minimo).
| Strategia | Esempi con esito | Dal | Al | In guadagno (frequenza di base) | Risultato medio dell'operazione |
|---|---|---|---|---|---|
| crypto_trend | 1844 | 01/01/2019 | 28/10/2026 | 18,3% | +0,8% |
| equity_momentum | 0 | | | nessuna: aspetta lo storico di Alpaca | |
| equity_meanrev | 0 | | | nessuna: aspetta lo storico di Alpaca | |
Una strategia senza frequenza di base non viene stimata: il modello lascia le sue operazioni come sono.
## La convalida
Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si studia il passato e si verifica il periodo dopo, 5 volte. «A combinazioni»: 15 combinazioni di 6 periodi, togliendo dallo studio ogni esempio che si sovrappone nel tempo a quelli di verifica, più 10 giorni di distacco.
| Modello | Prova | Casi | Errore (log-loss) | Di chi risponde sempre la frequenza di base | Errore sulle probabilità (Brier) | Previsioni azzeccate | Guadagno medio per operazione proposta, senza filtro | con il filtro |
|---|---|---|---|---|---|---|---|---|
| Alberi potenziati | in avanti | 1107 | 0,5040 | 0,4788 | 0,1591 | 49,6% | +1,76 € | +1,37 € |
| Alberi potenziati | a combinazioni | 9220 | 0,4913 | 0,4807 | 0,1551 | 52,3% | +1,69 € | +1,65 € |
| Regressione logistica (scelto) | in avanti | 1107 | 0,4950 | 0,4788 | 0,1571 | 51,8% | +1,76 € | +1,78 € |
| Regressione logistica (scelto) | a combinazioni | 9220 | 0,4938 | 0,4807 | 0,1560 | 53,4% | +1,69 € | +1,76 € |
| Foresta casuale | in avanti | 1107 | 0,4960 | 0,4788 | 0,1569 | 50,2% | +1,76 € | +1,66 € |
| Foresta casuale | a combinazioni | 9220 | 0,4909 | 0,4807 | 0,1547 | 52,2% | +1,69 € | +1,63 € |
Il guadagno è calcolato sul capitale di riferimento (10.000 € in tutto, quote predefinite). Nelle combinazioni ogni caso è verificato più volte.
**Scelta.** Regressione logistica: il miglior guadagno medio per operazione proposta su esempi mai visti. La regola era fissata prima di guardare i numeri (ADR 0018).
**Lettura onesta.** Le stime non sono migliori di chi risponde sempre la frequenza di base: su questo storico il modello non ha trovato niente di solido. Con il filtro il guadagno medio per operazione proposta cambia di +0,07 € nelle combinazioni e di +0,02 € in avanti.
## Cosa guarda di più
| Indizio | Peso su 100 |
|---|---|
| Forza della tendenza | 40 |
| Quota di titoli in salita | 20 |
| Giorno della settimana | 17 |
| Agitazione recente dei prezzi | 14 |
| Fase generale del mercato | 9 |
| Distanza dallo stop | 0 |
| Volumi scambiati | 0 |
Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizio. Con tutti i pesi a zero nessun indizio aiuta.
## Ci si può fidare delle probabilità?
Verifica a combinazioni, fasce da 5 punti. Contano le fasce con almeno 20 casi; errore medio 6,3 punti.
| Stima | Casi | Stimato in media | Andate bene |
|---|---|---|---|
| 0–5% | 13 | 3,6% | 30,8% |
| 5–10% | 213 | 7,5% | 17,8% |
| 10–15% | 1475 | 13,3% | 15,5% |
| 15–20% | 2986 | 17,5% | 20,7% |
| 20–25% | 793 | 22,1% | 19,7% |
| 25–30% | 2412 | 25,6% | 17,5% |
| 30–35% | 1275 | 33,3% | 16,5% |
| 35–40% | 17 | 37,5% | 23,5% |
| 40–45% | 9 | 42,3% | 33,3% |
| 45–50% | 10 | 47,5% | 20,0% |
| 50–55% | 9 | 50,5% | 22,2% |
| 60–65% | 1 | 61,5% | 0,0% |
| 65–70% | 1 | 66,7% | 100,0% |
| 75–80% | 6 | 75,0% | 33,3% |
## Cosa succede adesso
Il modello parte in osservazione: stima ogni segnale e non cambia nessuna operazione. Comincerà a contare solo dopo almeno 300 segnali dal vivo, con probabilità ben tarate e un miglioramento distinguibile dal caso (SPEC 11.5).
+59
View File
@@ -0,0 +1,59 @@
using System.Collections;
using System.Globalization;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Learning;
namespace Anubis.Server;
/// <summary>
/// "anubis learning base": the first model (SPEC 11.2, issue #63). It rebuilds the examples of <c>crypto_trend</c> on the
/// history that "anubis backtest base" already downloaded and converted, trains, and writes the validation report and the
/// file that travels with the program. It never uses the network. The stock strategies wait for the Alpaca history.
/// </summary>
internal static class LearningCommand
{
private const string Usage =
"Uso: anubis learning base [--to AAAA-MM-GG] [--out docs/learning]\n" +
" Usa gli storici già scaricati da 'anubis backtest base', senza rete. Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
{
output ??= Console.Out;
if (args.Length < 1 || args[0] != "base")
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
return 2;
}
var rest = args[1..].ToList();
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var config = ServerOptions.Parse([.. rest], environment).LoadConfig(environment);
var now = new SystemClock().UtcNow;
var to = Option(rest, "--to") is { } t ? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture) : new DateOnly(now.Year, now.Month, 1).AddDays(-1);
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "learning"));
try
{
Directory.CreateDirectory(outDir);
var file = await FirstModel.BuildAsync(config.Data.Research, to, null, CancellationToken.None).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.json"), FirstModel.ToJson(file)).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(outDir, "first-model.md"),
FirstModel.Markdown(file, "anubis learning base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{file.Examples.Count} esempi, {file.Examples.Count(e => e.IsLabelled)} con un esito. ")
+ (file.Report is { } report ? report.Reason : "Nessun modello: esempi troppo pochi.")).ConfigureAwait(false);
await output.WriteLineAsync("Rapporto scritto in " + outDir).ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or FormatException or UnauthorizedAccessException or InvalidDataException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
private static string? Option(List<string> args, string name)
{
var index = args.IndexOf(name);
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
}
}
+6
View File
@@ -18,6 +18,12 @@ if (args.Length >= 1 && args[0] == "backtest")
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis learning base": the first model and its validation report, written to docs/learning (Phase 8).
if (args.Length >= 1 && args[0] == "learning")
{
return await LearningCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6).
if (args.Length >= 1 && args[0] == "soak")
{
+2
View File
@@ -19,6 +19,8 @@
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
<!-- The first model with its examples and base rates (SPEC 11.2): loaded at the first start. -->
<EmbeddedResource Include="..\..\docs\learning\first-model.json" LogicalName="Anubis.Learning.first-model.json" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Anubis.Tests" />
+17 -11
View File
@@ -158,17 +158,7 @@ public static class CryptoTrendProtocol
public static async Task<ProtocolOutcome> RunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action<string>? progress, CancellationToken cancellationToken)
{
var store = new ResearchStore(researchRoot);
var broad = new List<string>();
foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day))
{
// Every converted pair goes in: the strategy picks its top 10 month by month, among coins that died too.
if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false))
{
broad.Add(symbol);
}
}
var broad = await BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
if (Narrow.Any(s => !broad.Contains(s)))
{
throw new InvalidOperationException("Mancano gli storici di BTC, ETH o SOL in euro: scarica prima gli archivi Binance e il cambio BCE.");
@@ -184,6 +174,22 @@ public static class CryptoTrendProtocol
return new ProtocolOutcome(QualificationOf(runs), runs);
}
/// <summary>Every converted pair with bars in the period: the strategy picks its top 10 month by month, among coins that died too.</summary>
public static async Task<IReadOnlyList<string>> BroadAsync(ResearchStore store, DateOnly to, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(store);
var broad = new List<string>();
foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day))
{
if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false))
{
broad.Add(symbol);
}
}
return broad;
}
/// <summary>The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live.</summary>
public static Qualification QualificationOf(IReadOnlyList<ProtocolRun> runs)
{
+2
View File
@@ -1,3 +1,4 @@
using System.Text.Json.Serialization;
using Anubis.Backtest;
using Anubis.Strategies;
using Anubis.Trading;
@@ -26,6 +27,7 @@ public sealed record Example(Guid Id, string Strategy, string Symbol, string Sou
public CaseLabel? Label { get; init; }
/// <summary>A label that can train: the operation started and closed.</summary>
[JsonIgnore]
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);
+195
View File
@@ -0,0 +1,195 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Learning;
/// <summary>
/// The first model (SPEC 11.2): trained on the examples rebuilt by running the strategies on the history. The file travels
/// with the program, as the outcomes of the backtests do: it also gives the base rate of each strategy (SPEC 11.1), which
/// a new file updates at each quarterly review.
/// </summary>
public sealed record FirstModelFile
{
/// <summary>The last day of the history it was built on.</summary>
public DateOnly Through { get; init; }
/// <summary>The share of winners of each strategy on the history; a strategy not here has no base rate yet.</summary>
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
public TrainedModel? Model { get; init; }
public ModelReport? Report { get; init; }
public IReadOnlyList<Example> Examples { get; init; } = [];
}
public static class FirstModel
{
public const string Resource = "Anubis.Learning.first-model.json";
/// <summary>The reference total the gain is measured on when no strategy has capital yet (SPEC 8.6).</summary>
public const double ReferenceCapital = 10_000;
private static readonly Lazy<FirstModelFile?> Loaded = new(Load);
/// <summary>The file built into the program; null when there is none.</summary>
public static FirstModelFile? Embedded => Loaded.Value;
public static IReadOnlyDictionary<string, double> ReferenceCapitals { get; } =
StrategyNames.Base.ToDictionary(s => s.Name, s => ReferenceCapital * (double)(StrategyPipeline.DefaultShare(s.Name) ?? 0m), StringComparer.Ordinal);
private static FirstModelFile? Load()
{
using var stream = typeof(FirstModel).Assembly.GetManifestResourceStream(Resource);
return stream is null ? null : JsonSerializer.Deserialize<FirstModelFile>(stream);
}
public static string ToJson(FirstModelFile file) => JsonSerializer.Serialize(file) + "\n";
public static string Fingerprint(FirstModelFile file) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(ToJson(file))));
/// <summary>Rebuilds the examples of <c>crypto_trend</c> on the broad universe of its protocol, then trains.</summary>
public static async Task<FirstModelFile> BuildAsync(string researchRoot, DateOnly to, Action<string>? progress, CancellationToken cancellationToken)
{
var symbols = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
if (symbols.Count == 0)
{
throw new InvalidOperationException("Mancano gli storici delle crypto in euro: esegui prima anubis backtest base.");
}
var data = await Laboratory.LoadResearchAsync(researchRoot, new TrialData(TrialSources.Research, EuroHistory.Venue, symbols, CryptoTrendProtocol.From, to), cancellationToken).ConfigureAwait(false);
var parameters = BacktestOutcomes.Find(StrategyNames.CryptoTrend)?.Parameters;
var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = CryptoTrendProtocol.Capital, From = CryptoTrendProtocol.From, To = to });
var examples = HistoryCases.Build(StrategyNames.CryptoTrend, () => LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, parameters), data, options,
n => progress?.Invoke(string.Create(CultureInfo.InvariantCulture, $"esempi: {n}")), cancellationToken);
return Train([.. examples.Select(WithStableId)], to, cancellationToken);
}
public static FirstModelFile Train(IReadOnlyList<Example> examples, DateOnly through, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(examples);
var rates = Trainer.SharesOf(examples);
var result = Trainer.Train(new TrainingInput(examples)
{
BaseRates = rates,
Capital = ReferenceCapitals,
}, cancellationToken);
return new FirstModelFile { Through = through, BaseRates = rates, Model = result?.Model, Report = result?.Report, Examples = examples };
}
// The same example always has the same id, so the same history writes the same file.
private static Example WithStableId(Example example) =>
example with { Id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes($"{example.Strategy}|{example.Symbol}|{example.Day:yyyy-MM-dd}")).AsSpan(0, 16)) };
/// <summary>The validation report, in plain Italian.</summary>
public static string Markdown(FirstModelFile file, string command)
{
ArgumentNullException.ThrowIfNull(file);
var it = CultureInfo.GetCultureInfo("it-IT");
var text = new StringBuilder();
void Line(FormattableString line) => text.Append(line.ToString(it)).Append('\n');
Line($"# Primo modello: rapporto di convalida");
Line($"");
Line($"Generato con `{command}` sullo storico fino al {file.Through:dd/MM/yyyy}. Gli stessi dati danno sempre lo stesso modello.");
Line($"");
Line($"## La domanda");
Line($"");
Line($"Il modello non prevede i prezzi. Guarda un segnale di una strategia e stima quanto è probabile che l'operazione chiuda in guadagno, al netto dei costi. Può solo rimpicciolire l'operazione.");
Line($"");
Line($"## Gli esempi");
Line($"");
var labelled = file.Examples.Where(e => e.IsLabelled).ToList();
var open = file.Examples.Count(e => e.Label is null);
Line($"{file.Examples.Count} esempi ricostruiti facendo girare le strategie sullo storico: {labelled.Count} con un esito, {open} con l'operazione ancora aperta, {file.Examples.Count - labelled.Count - open} mai partiti (sotto il minimo).");
Line($"");
Line($"| Strategia | Esempi con esito | Dal | Al | In guadagno (frequenza di base) | Risultato medio dell'operazione |");
Line($"|---|---|---|---|---|---|");
foreach (var group in labelled.GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal))
{
Line($"| {group.Key} | {group.Count()} | {group.Min(e => e.Day):dd/MM/yyyy} | {group.Max(e => e.Day):dd/MM/yyyy} | {file.BaseRates[group.Key] * 100:0.0}% | {group.Average(e => e.Label!.Result ?? 0) * 100:+0.0;-0.0}% |");
}
foreach (var missing in StrategyNames.Base.Select(s => s.Name).Where(s => !file.BaseRates.ContainsKey(s)))
{
Line($"| {missing} | 0 | | | nessuna: aspetta lo storico di Alpaca | |");
}
Line($"");
Line($"Una strategia senza frequenza di base non viene stimata: il modello lascia le sue operazioni come sono.");
if (file.Report is not { } report || file.Model is not { } model)
{
Line($"");
Line($"**Nessun modello**: gli esempi sono troppo pochi.");
return text.ToString();
}
Line($"");
Line($"## La convalida");
Line($"");
Line($"Ogni numero viene da esempi che il modello non aveva studiato. «In avanti»: si studia il passato e si verifica il periodo dopo, 5 volte. «A combinazioni»: {report.Splits} combinazioni di 6 periodi, togliendo dallo studio ogni esempio che si sovrappone nel tempo a quelli di verifica, più {CaseSplits.Embargo} giorni di distacco.");
Line($"");
Line($"| Modello | Prova | Casi | Errore (log-loss) | Di chi risponde sempre la frequenza di base | Errore sulle probabilità (Brier) | Previsioni azzeccate | Guadagno medio per operazione proposta, senza filtro | con il filtro |");
Line($"|---|---|---|---|---|---|---|---|---|");
foreach (var attempt in report.Attempts)
{
foreach (var (name, s) in new[] { ("in avanti", attempt.Forward), ("a combinazioni", attempt.Combined) })
{
Line($"| {LearnerNames.Label(attempt.Learner)}{(attempt.Chosen ? " (scelto)" : "")} | {name} | {s.Cases} | {s.LogLoss:0.0000} | {s.BaseLogLoss:0.0000} | {s.Brier:0.0000} | {(s.Precision is { } p ? p * 100 : 0):0.0}% | {s.GainWithout:+0.00;-0.00} € | {s.GainWith:+0.00;-0.00} € |");
}
}
Line($"");
Line($"Il guadagno è calcolato sul capitale di riferimento ({ReferenceCapital:#,0} € in tutto, quote predefinite). Nelle combinazioni ogni caso è verificato più volte.");
Line($"");
Line($"**Scelta.** {report.Reason} La regola era fissata prima di guardare i numeri (ADR 0018).");
Line($"");
Line($"**Lettura onesta.** {Verdict(report.Chosen!, it)}");
Line($"");
Line($"## Cosa guarda di più");
Line($"");
Line($"| Indizio | Peso su 100 |");
Line($"|---|---|");
foreach (var weight in report.Weights)
{
Line($"| {weight.Group} | {weight.Share:0} |");
}
Line($"");
Line($"Il peso dice quanto peggiorano le stime se si mescolano i valori di quell'indizio. Con tutti i pesi a zero nessun indizio aiuta.");
Line($"");
Line($"## Ci si può fidare delle probabilità?");
Line($"");
Line($"Verifica a combinazioni, fasce da 5 punti. Contano le fasce con almeno {Judge.BandMin} casi; errore medio {(report.Chosen!.Combined.CalibrationError is { } error ? error * 100 : 0):0.0} punti.");
Line($"");
Line($"| Stima | Casi | Stimato in media | Andate bene |");
Line($"|---|---|---|---|");
foreach (var band in report.Chosen.Combined.Bands)
{
Line($"| {band.From * 100:0}–{band.To * 100:0}% | {band.Cases} | {band.Estimated * 100:0.0}% | {band.Observed * 100:0.0}% |");
}
Line($"");
Line($"## Cosa succede adesso");
Line($"");
Line($"Il modello parte in osservazione: stima ogni segnale e non cambia nessuna operazione. Comincerà a contare solo dopo almeno 300 segnali dal vivo, con probabilità ben tarate e un miglioramento distinguibile dal caso (SPEC 11.5).");
return text.ToString();
}
private static string Verdict(Attempt chosen, CultureInfo it)
{
var (s, f) = (chosen.Combined, chosen.Forward);
var probabilities = s.LogLoss < s.BaseLogLoss && f.LogLoss < f.BaseLogLoss
? "Le stime sono migliori di chi risponde sempre la frequenza di base, in tutte e due le prove."
: s.LogLoss >= s.BaseLogLoss && f.LogLoss >= f.BaseLogLoss
? "Le stime non sono migliori di chi risponde sempre la frequenza di base: su questo storico il modello non ha trovato niente di solido."
: "Le stime sono migliori di chi risponde sempre la frequenza di base in una sola delle due prove: non è un risultato solido.";
return probabilities + string.Create(it, $" Con il filtro il guadagno medio per operazione proposta cambia di {s.Improvement:+0.00;-0.00} € nelle combinazioni e di {f.Improvement:+0.00;-0.00} € in avanti.");
}
}
+310
View File
@@ -0,0 +1,310 @@
namespace Anubis.Learning;
/// <summary>
/// The multiplier of SPEC 11.1: 1 at the base rate or above, 0 at <paramref name="Zero"/> or more below it, in proportion
/// between. <paramref name="Full"/> is how far below the base rate the size is still whole. It can never exceed 1.
/// </summary>
public sealed record MultiplierRule(double Full, double Zero)
{
public static readonly MultiplierRule Standard = new(0, 0.10);
public double Of(double probability, double baseRate)
{
// A number that is not a number must never move an operation.
if (!double.IsFinite(probability) || !double.IsFinite(baseRate) || !double.IsFinite(Full) || !double.IsFinite(Zero) || Zero <= Full)
{
return 1;
}
// A hair below the base rate is the base rate: a model that always answers the base rate leaves everything as it is.
var below = baseRate - probability;
return below <= Full + 1e-9 ? 1 : Math.Round(Math.Clamp((Zero - below) / (Zero - Full), 0, 1), 4);
}
}
/// <summary>One estimate on an example whose outcome is known. <see cref="Weight"/> is its weight by maturation.</summary>
public sealed record Estimate(Example Case, double Probability, double BaseRate, double Multiplier)
{
public double Weight { get; init; } = 1;
public bool Win => Case.Label?.Win == true;
/// <summary>The estimate says the operation is at least as likely to win as usual.</summary>
public bool SaysWin => Probability >= BaseRate - 1e-9;
}
/// <summary>A band of estimated probabilities and how often it went well.</summary>
public sealed record CalibrationBand(double From, double To, int Cases, double Estimated, double Observed);
/// <summary>How good a set of estimates is (SPEC 11.3): the gain per proposed operation counts, not the accuracy.</summary>
public sealed record Scores
{
public int Cases { get; init; }
public double LogLoss { get; init; }
/// <summary>The log-loss of who always answers the base rate.</summary>
public double BaseLogLoss { get; init; }
/// <summary>Brier score: what the interface calls "errore sulle probabilità".</summary>
public double Brier { get; init; }
/// <summary>"Previsioni azzeccate": balanced, 50% for who always says the same. Null without both wins and losses.</summary>
public double? Precision { get; init; }
public double GainWithout { get; init; }
public double GainWith { get; init; }
public double Improvement => GainWith - GainWithout;
/// <summary>Mean calibration error on the bands with at least <see cref="Judge.BandMin"/> cases; null with none.</summary>
public double? CalibrationError { get; init; }
public IReadOnlyList<CalibrationBand> Bands { get; init; } = [];
}
/// <summary>The measures of SPEC 11.3–11.5.</summary>
public static class Judge
{
/// <summary>A band counts with at least this many cases (SPEC 11.5).</summary>
public const int BandMin = 20;
public const double BandWidth = 0.05;
/// <summary>What an example earned or lost in euro: the share it asked for, its return, the capital of its strategy.</summary>
public static double Gain(Example example, IReadOnlyDictionary<string, double> capital)
{
ArgumentNullException.ThrowIfNull(example);
ArgumentNullException.ThrowIfNull(capital);
return (double)example.Weight * (example.Label?.Result ?? 0) * capital.GetValueOrDefault(example.Strategy);
}
public static double LogLoss(bool win, double probability)
{
var p = Math.Clamp(probability, 1e-6, 1 - 1e-6);
return -Math.Log(win ? p : 1 - p);
}
/// <summary>
/// The weights of SPEC 11.4: losses close before gains, so among what matured so far the losses are too many. In each
/// strategy wins and losses count in the proportion of its base rate. Without both in a strategy nothing can be weighed.
/// </summary>
public static IReadOnlyList<Estimate> Weigh(IReadOnlyList<Estimate> estimates, IReadOnlyDictionary<string, double> baseRates)
{
ArgumentNullException.ThrowIfNull(estimates);
ArgumentNullException.ThrowIfNull(baseRates);
var shares = estimates.GroupBy(e => e.Case.Strategy, StringComparer.Ordinal).ToDictionary(g => g.Key, g => (double)g.Count(e => e.Win) / g.Count(), StringComparer.Ordinal);
return
[
.. estimates.Select(e =>
{
var seen = shares[e.Case.Strategy];
return seen is > 0 and < 1 && baseRates.TryGetValue(e.Case.Strategy, out var rate)
? e with { Weight = e.Win ? rate / seen : (1 - rate) / (1 - seen) }
: e with { Weight = 1 };
}),
];
}
/// <summary>The scores of weighed estimates. The gain counts only the <paramref name="funded"/> ones.</summary>
public static Scores Score(IReadOnlyList<Estimate> estimates, IReadOnlyDictionary<string, double> capital, Func<Example, bool>? funded = null)
{
ArgumentNullException.ThrowIfNull(estimates);
ArgumentNullException.ThrowIfNull(capital);
if (estimates.Count == 0)
{
return new Scores();
}
var total = estimates.Sum(e => e.Weight);
var counted = estimates.Where(e => funded?.Invoke(e.Case) ?? true).ToList();
var proposals = counted.Sum(e => e.Weight);
var bands = Bands(estimates);
return new Scores
{
Cases = estimates.Count,
LogLoss = total > 0 ? estimates.Sum(e => e.Weight * LogLoss(e.Win, e.Probability)) / total : 0,
BaseLogLoss = total > 0 ? estimates.Sum(e => e.Weight * LogLoss(e.Win, e.BaseRate)) / total : 0,
Brier = total > 0 ? estimates.Sum(e => e.Weight * Math.Pow(e.Probability - (e.Win ? 1 : 0), 2)) / total : 0,
Precision = Precision(estimates),
GainWithout = proposals > 0 ? counted.Sum(e => e.Weight * Gain(e.Case, capital)) / proposals : 0,
GainWith = proposals > 0 ? counted.Sum(e => e.Weight * e.Multiplier * Gain(e.Case, capital)) / proposals : 0,
CalibrationError = ErrorOf(bands),
Bands = bands,
};
}
/// <summary>
/// "Previsioni azzeccate" (SPEC 11.3): the mean of two shares, the winners it had estimated at the base rate or above
/// and the losers it had estimated below. Chance, or always the same answer, stays at 50%.
/// </summary>
public static double? Precision(IReadOnlyList<Estimate> estimates)
{
ArgumentNullException.ThrowIfNull(estimates);
var wins = estimates.Where(e => e.Win).ToList();
var losses = estimates.Where(e => !e.Win).ToList();
return wins.Count == 0 || losses.Count == 0
? null
: (((double)wins.Count(e => e.SaysWin) / wins.Count) + ((double)losses.Count(e => !e.SaysWin) / losses.Count)) / 2;
}
public static IReadOnlyList<CalibrationBand> Bands(IReadOnlyList<Estimate> estimates)
{
ArgumentNullException.ThrowIfNull(estimates);
var last = (int)Math.Round(1 / BandWidth) - 1;
return
[
.. estimates.GroupBy(e => Math.Clamp((int)Math.Floor((e.Probability / BandWidth) + 1e-9), 0, last)).OrderBy(g => g.Key).Select(g =>
{
var weight = g.Sum(e => e.Weight);
return new CalibrationBand(Math.Round(g.Key * BandWidth, 2), Math.Round((g.Key + 1) * BandWidth, 2), g.Count(),
weight > 0 ? g.Sum(e => e.Weight * e.Probability) / weight : 0, weight > 0 ? g.Sum(e => e.Weight * (e.Win ? 1 : 0)) / weight : 0);
}),
];
}
/// <summary>The mean distance between estimated and observed on the bands that count; null with none.</summary>
public static double? ErrorOf(IReadOnlyList<CalibrationBand> bands)
{
var solid = bands.Where(b => b.Cases >= BandMin).ToList();
return solid.Count > 0 ? solid.Sum(b => b.Cases * Math.Abs(b.Estimated - b.Observed)) / solid.Sum(b => b.Cases) : null;
}
/// <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.
/// </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)
{
ArgumentNullException.ThrowIfNull(values);
ArgumentNullException.ThrowIfNull(weights);
var n = values.Count;
if (n == 0)
{
return (0, 0);
}
var size = Math.Clamp(block, 1, n);
var random = new FixedRandom(seed);
var means = new double[rounds];
for (var r = 0; r < rounds; r++)
{
double sum = 0, weight = 0;
for (var filled = 0; filled < n;)
{
var start = random.Next(n);
for (var k = 0; k < size && filled < n; k++, filled++)
{
var at = (start + k) % n;
sum += weights[at] * values[at];
weight += weights[at];
}
}
means[r] = weight > 0 ? sum / weight : 0;
}
Array.Sort(means);
var tail = (1 - confidence) / 2;
return (means[(int)Math.Floor(tail * (rounds - 1))], means[(int)Math.Ceiling((1 - tail) * (rounds - 1))]);
}
}
/// <summary>A split of the examples: which train and which test, by position.</summary>
public sealed record Split(IReadOnlyList<int> Train, IReadOnlyList<int> Test);
/// <summary>
/// Splits that never mix in time (SPEC 11.3): an example lives from its decision to the close of its operation, and one
/// that overlaps a test example, or starts within the embargo after one, never trains for it. The examples are in order of decision.
/// </summary>
public static class CaseSplits
{
/// <summary>Days after a test operation in which no training example may start.</summary>
public const int Embargo = 10;
/// <summary>Windows that go forward: the first part trains, the rest is verified in pieces, each on what was already over before it.</summary>
public static IReadOnlyList<Split> Forward(IReadOnlyList<Example> cases, int pieces = 5, double first = 0.4)
{
ArgumentNullException.ThrowIfNull(cases);
var start = (int)(cases.Count * first);
var splits = new List<Split>();
for (var k = 0; k < pieces; k++)
{
var from = start + (int)((long)(cases.Count - start) * k / pieces);
var to = start + (int)((long)(cases.Count - start) * (k + 1) / pieces);
if (to > from)
{
var begins = cases[from].Day;
splits.Add(new Split([.. Enumerable.Range(0, from).Where(i => Closed(cases[i]) < begins)], [.. Enumerable.Range(from, to - from)]));
}
}
return splits;
}
/// <summary>Every choice of <paramref name="tested"/> groups out of <paramref name="groups"/>, purged and with embargo.</summary>
public static IReadOnlyList<Split> Combinatorial(IReadOnlyList<Example> cases, int groups = 6, int tested = 2)
{
ArgumentNullException.ThrowIfNull(cases);
var group = Enumerable.Range(0, cases.Count).Select(i => (int)((long)i * groups / cases.Count)).ToArray();
var splits = new List<Split>();
foreach (var chosen in Choices(groups, tested))
{
var test = Enumerable.Range(0, cases.Count).Where(i => chosen.Contains(group[i])).ToList();
splits.Add(new Split(Purge(cases, test), test));
}
return splits;
}
/// <summary>Consecutive folds, purged: for the estimates the calibration is fitted on.</summary>
public static IReadOnlyList<Split> Folds(IReadOnlyList<Example> cases, int folds = 5) => Combinatorial(cases, folds, 1);
private static List<int> Purge(IReadOnlyList<Example> cases, List<int> test)
{
// The lives of the test examples, embargo included, joined where they touch.
var lives = new List<(DateOnly From, DateOnly To)>();
foreach (var (from, to) in test.Select(i => (From: cases[i].Day, To: Closed(cases[i]).AddDays(Embargo))).OrderBy(x => x.From))
{
if (lives.Count > 0 && from <= lives[^1].To)
{
lives[^1] = (lives[^1].From, to > lives[^1].To ? to : lives[^1].To);
}
else
{
lives.Add((from, to));
}
}
var inTest = test.ToHashSet();
return [.. Enumerable.Range(0, cases.Count).Where(i => !inTest.Contains(i) && !lives.Any(l => cases[i].Day <= l.To && Closed(cases[i]) >= l.From))];
}
private static DateOnly Closed(Example example) => example.Label?.ClosedDay ?? DateOnly.MaxValue.AddDays(-Embargo);
private static IEnumerable<HashSet<int>> Choices(int groups, int tested)
{
var picks = Enumerable.Range(0, tested).ToArray();
while (true)
{
yield return [.. picks];
var at = tested - 1;
while (at >= 0 && picks[at] == groups - tested + at)
{
at--;
}
if (at < 0)
{
yield break;
}
picks[at]++;
for (var k = at + 1; k < tested; k++)
{
picks[k] = picks[k - 1] + 1;
}
}
}
}
+680
View File
@@ -0,0 +1,680 @@
namespace Anubis.Learning;
/// <summary>Names of the learners (SPEC 11.3, ADR 0018): all written here.</summary>
public static class LearnerNames
{
/// <summary>Regularised logistic regression: the reference.</summary>
public const string Logistic = "logistic";
/// <summary>Boosted trees: the main one.</summary>
public const string Boosting = "boosting";
/// <summary>Random forest: it must beat the others at the same rules.</summary>
public const string Forest = "forest";
public static readonly IReadOnlyList<string> All = [Boosting, Logistic, Forest];
public static string Label(string learner) => learner switch
{
Logistic => "Regressione logistica",
Boosting => "Alberi potenziati",
Forest => "Foresta casuale",
_ => learner,
};
}
/// <summary>SplitMix64: the same sequence on every platform and version, so the same data always give the same model.</summary>
public sealed class FixedRandom(long seed)
{
private ulong _state = unchecked((ulong)seed);
public ulong NextBits()
{
var z = _state += 0x9E3779B97F4A7C15UL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
public double NextDouble() => (NextBits() >> 11) * (1.0 / (1UL << 53));
public int Next(int below) => (int)(NextDouble() * below);
public void Shuffle<T>(IList<T> items)
{
ArgumentNullException.ThrowIfNull(items);
for (var i = items.Count - 1; i > 0; i--)
{
var j = Next(i + 1);
(items[i], items[j]) = (items[j], items[i]);
}
}
}
/// <summary>What a learner has learned: a score in log-odds for a row of clues (NaN: the clue is missing).</summary>
public sealed record Learned
{
public string Learner { get; init; } = "";
public LinearBody? Linear { get; init; }
public TreesBody? Trees { get; init; }
public double Score(IReadOnlyList<double> row) => Linear?.Score(row) ?? Trees?.Score(row) ?? 0;
}
/// <summary>A logistic regression on standardised clues: a missing clue counts as its mean.</summary>
public sealed record LinearBody(double Intercept, IReadOnlyList<double> Weights, IReadOnlyList<double> Means, IReadOnlyList<double> Scales)
{
public double Score(IReadOnlyList<double> row)
{
ArgumentNullException.ThrowIfNull(row);
var score = Intercept;
for (var j = 0; j < Weights.Count; j++)
{
if (double.IsFinite(row[j]))
{
// A value far beyond what was studied must not carry the sum away.
score += Weights[j] * Math.Clamp((row[j] - Means[j]) / Scales[j], -5, 5);
}
}
return score;
}
}
/// <summary>Trees: summed with a step (boosting) or averaged as probabilities (forest).</summary>
public sealed record TreesBody(double Start, double Rate, bool Average, IReadOnlyList<Tree> Trees)
{
public double Score(IReadOnlyList<double> row)
{
ArgumentNullException.ThrowIfNull(row);
if (Trees.Count == 0)
{
return Start;
}
var sum = 0.0;
foreach (var tree in Trees)
{
sum += tree.Value(row);
}
return Average ? Odds.Logit(sum / Trees.Count) : Start + (Rate * sum);
}
}
/// <summary>A small tree as arrays: a node with no feature (-1) is a leaf.</summary>
public sealed record Tree(IReadOnlyList<int> Feature, IReadOnlyList<double> Threshold, IReadOnlyList<int> Left, IReadOnlyList<int> Right, IReadOnlyList<bool> MissingLeft, IReadOnlyList<double> Values)
{
public double Value(IReadOnlyList<double> row)
{
ArgumentNullException.ThrowIfNull(row);
var node = 0;
while (Feature[node] >= 0)
{
var value = row[Feature[node]];
node = (double.IsFinite(value) ? value <= Threshold[node] : MissingLeft[node]) ? Left[node] : Right[node];
}
return Values[node];
}
}
/// <summary>Log-odds and probabilities.</summary>
public static class Odds
{
public const double Epsilon = 1e-4;
public static double Logit(double probability)
{
var p = Math.Clamp(probability, Epsilon, 1 - Epsilon);
return Math.Log(p / (1 - p));
}
public static double Probability(double score) => 1 / (1 + Math.Exp(-Math.Clamp(score, -35, 35)));
}
/// <summary>Fits a learner on rows of clues and outcomes. The same input always gives the same result.</summary>
public static class Learners
{
private const int Bins = 32;
public static Learned Fit(string learner, IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
{
ArgumentNullException.ThrowIfNull(rows);
ArgumentNullException.ThrowIfNull(wins);
if (rows.Count == 0 || rows.Count != wins.Count)
{
throw new ArgumentException("Rows and outcomes must be as many, and not zero.", nameof(rows));
}
return learner switch
{
LearnerNames.Logistic => new Learned { Learner = learner, Linear = Logistic(rows, wins) },
LearnerNames.Boosting => new Learned { Learner = learner, Trees = Boosting(rows, wins, seed) },
LearnerNames.Forest => new Learned { Learner = learner, Trees = Forest(rows, wins, seed) },
_ => throw new ArgumentOutOfRangeException(nameof(learner), learner, "Unknown learner."),
};
}
// ---- Logistic regression ------------------------------------------------------------------------------------
/// <summary>Strength of the L2 penalty, in examples' worth of information per clue.</summary>
private const double Ridge = 10;
private static LinearBody Logistic(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins)
{
var d = rows[0].Length;
var means = new double[d];
var scales = new double[d];
for (var j = 0; j < d; j++)
{
var values = rows.Select(r => r[j]).Where(double.IsFinite).ToList();
means[j] = values.Count > 0 ? values.Average() : 0;
var variance = values.Count > 1 ? values.Sum(v => (v - means[j]) * (v - means[j])) / values.Count : 0;
scales[j] = variance > 1e-18 ? Math.Sqrt(variance) : 1;
}
var x = rows.Select(r => r.Select((v, j) => double.IsFinite(v) ? Math.Clamp((v - means[j]) / scales[j], -5, 5) : 0).ToArray()).ToList();
var beta = new double[d + 1];
beta[0] = Odds.Logit((double)wins.Count(w => w) / wins.Count);
for (var step = 0; step < 50; step++)
{
// One Newton step of the penalised likelihood: the intercept is not penalised.
var gradient = new double[d + 1];
var hessian = new double[d + 1, d + 1];
for (var i = 0; i < x.Count; i++)
{
var score = beta[0];
for (var j = 0; j < d; j++)
{
score += beta[j + 1] * x[i][j];
}
var p = Odds.Probability(score);
var error = (wins[i] ? 1 : 0) - p;
var weight = Math.Max(p * (1 - p), 1e-6);
for (var a = 0; a <= d; a++)
{
var xa = a == 0 ? 1 : x[i][a - 1];
gradient[a] += error * xa;
for (var b = 0; b <= a; b++)
{
hessian[a, b] += weight * xa * (b == 0 ? 1 : x[i][b - 1]);
}
}
}
for (var a = 0; a <= d; a++)
{
if (a > 0)
{
gradient[a] -= Ridge * beta[a];
hessian[a, a] += Ridge;
}
for (var b = a + 1; b <= d; b++)
{
hessian[a, b] = hessian[b, a];
}
}
var delta = Solve(hessian, gradient);
var largest = 0.0;
for (var a = 0; a <= d; a++)
{
var change = Math.Clamp(delta[a], -2, 2);
beta[a] += change;
largest = Math.Max(largest, Math.Abs(change));
}
if (largest < 1e-9)
{
break;
}
}
return new LinearBody(beta[0], beta[1..], means, scales);
}
private static double[] Solve(double[,] matrix, double[] right)
{
var n = right.Length;
var a = (double[,])matrix.Clone();
var b = (double[])right.Clone();
for (var column = 0; column < n; column++)
{
var pivot = column;
for (var row = column + 1; row < n; row++)
{
if (Math.Abs(a[row, column]) > Math.Abs(a[pivot, column]))
{
pivot = row;
}
}
if (Math.Abs(a[pivot, column]) < 1e-12)
{
continue;
}
if (pivot != column)
{
for (var k = 0; k < n; k++)
{
(a[column, k], a[pivot, k]) = (a[pivot, k], a[column, k]);
}
(b[column], b[pivot]) = (b[pivot], b[column]);
}
for (var row = column + 1; row < n; row++)
{
var factor = a[row, column] / a[column, column];
for (var k = column; k < n; k++)
{
a[row, k] -= factor * a[column, k];
}
b[row] -= factor * b[column];
}
}
var solution = new double[n];
for (var row = n - 1; row >= 0; row--)
{
var sum = b[row];
for (var k = row + 1; k < n; k++)
{
sum -= a[row, k] * solution[k];
}
solution[row] = Math.Abs(a[row, row]) < 1e-12 ? 0 : sum / a[row, row];
}
return solution;
}
// ---- Trees --------------------------------------------------------------------------------------------------
private sealed record Shape(int Depth, int MinLeaf, double Lambda, double MinGain, int Features);
private static TreesBody Boosting(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
{
const double rate = 0.05;
const int count = 150;
var n = rows.Count;
var random = new FixedRandom(seed);
var grid = new Grid(rows, Bins);
var start = Odds.Logit((double)wins.Count(w => w) / n);
var scores = Enumerable.Repeat(start, n).ToArray();
var gradient = new double[n];
var hessian = new double[n];
var shape = new Shape(3, MinLeaf(n), 10, 0.05, rows[0].Length);
var trees = new List<Tree>(count);
for (var t = 0; t < count; t++)
{
for (var i = 0; i < n; i++)
{
var p = Odds.Probability(scores[i]);
gradient[i] = (wins[i] ? 1 : 0) - p;
hessian[i] = Math.Max(p * (1 - p), 1e-6);
}
// Every tree sees a random 70% of the examples: less noise learned by heart.
var members = Enumerable.Range(0, n).Where(_ => random.NextDouble() < 0.7).ToArray();
if (members.Length < 2)
{
continue;
}
var tree = Grow(grid, members, gradient, hessian, shape, random);
if (tree.Feature[0] < 0)
{
continue;
}
trees.Add(tree);
for (var i = 0; i < n; i++)
{
scores[i] += rate * tree.Value(rows[i]);
}
}
return new TreesBody(start, rate, false, trees);
}
private static TreesBody Forest(IReadOnlyList<double[]> rows, IReadOnlyList<bool> wins, long seed)
{
const int count = 200;
var n = rows.Count;
var d = rows[0].Length;
var random = new FixedRandom(seed ^ 0x5DEECE66DL);
var grid = new Grid(rows, Bins);
var share = (double)wins.Count(w => w) / n;
// With the outcome as gradient and 1 as curvature a leaf is its share of wins, pulled a little towards the mean.
var gradient = wins.Select(w => (w ? 1 : 0) - share).ToArray();
var hessian = Enumerable.Repeat(1.0, n).ToArray();
var shape = new Shape(4, MinLeaf(n), 5, 0.02, Math.Max(2, (int)Math.Ceiling(Math.Sqrt(d))));
var trees = new List<Tree>(count);
for (var t = 0; t < count; t++)
{
var members = Enumerable.Range(0, n).Select(_ => random.Next(n)).Order().ToArray();
var tree = Grow(grid, members, gradient, hessian, shape, random);
trees.Add(tree with { Values = [.. tree.Values.Select(v => Math.Clamp(share + v, 0, 1))] });
}
return new TreesBody(0, 1, true, trees);
}
/// <summary>Many examples per leaf (ADR 0018): 40, fewer only when there are not enough of them to split at all.</summary>
public static int MinLeaf(int examples) => Math.Clamp(examples / 8, 10, 40);
/// <summary>The values of each clue cut in a few bins of about the same number of examples.</summary>
private sealed class Grid
{
public const byte Missing = 255;
public Grid(IReadOnlyList<double[]> rows, int bins)
{
var d = rows[0].Length;
Cuts = new double[d][];
Bin = new byte[d][];
for (var j = 0; j < d; j++)
{
var values = rows.Select(r => r[j]).Where(double.IsFinite).Order().ToArray();
var cuts = new List<double>();
if (values.Length > 0)
{
for (var k = 1; k < bins; k++)
{
// A cut lies halfway between two different values.
var at = (int)((long)k * values.Length / bins);
if (at > 0 && values[at] > values[at - 1])
{
cuts.Add((values[at] + values[at - 1]) / 2);
}
}
// Few different values: the jumps may fall between two quantiles.
var distinct = values.Distinct().ToList();
if (distinct.Count <= bins)
{
cuts = [.. distinct.Zip(distinct.Skip(1), (a, b) => (a + b) / 2)];
}
}
Cuts[j] = [.. cuts.Distinct().Order()];
Bin[j] = [.. rows.Select(r => BinOf(Cuts[j], r[j]))];
}
}
public double[][] Cuts { get; }
public byte[][] Bin { get; }
private static byte BinOf(double[] cuts, double value)
{
if (!double.IsFinite(value))
{
return Missing;
}
var bin = 0;
while (bin < cuts.Length && value > cuts[bin])
{
bin++;
}
return (byte)bin;
}
}
private static Tree Grow(Grid grid, int[] members, double[] gradient, double[] hessian, Shape shape, FixedRandom random)
{
var feature = new List<int>();
var threshold = new List<double>();
var left = new List<int>();
var right = new List<int>();
var missingLeft = new List<bool>();
var values = new List<double>();
Add(members, 0);
return new Tree(feature, threshold, left, right, missingLeft, values);
int Add(int[] inside, int depth)
{
var node = feature.Count;
feature.Add(-1);
threshold.Add(0);
left.Add(-1);
right.Add(-1);
missingLeft.Add(true);
double g = 0, h = 0;
foreach (var i in inside)
{
g += gradient[i];
h += hessian[i];
}
values.Add(g / (h + shape.Lambda));
if (depth >= shape.Depth || inside.Length < 2 * shape.MinLeaf || BestSplit(inside, g, h) is not { } best)
{
return node;
}
feature[node] = best.Feature;
threshold[node] = grid.Cuts[best.Feature][best.Cut];
missingLeft[node] = best.MissingLeft;
var bins = grid.Bin[best.Feature];
bool GoesLeft(int i) => bins[i] == Grid.Missing ? best.MissingLeft : bins[i] <= best.Cut;
left[node] = Add([.. inside.Where(GoesLeft)], depth + 1);
right[node] = Add([.. inside.Where(i => !GoesLeft(i))], depth + 1);
return node;
}
(int Feature, int Cut, bool MissingLeft)? BestSplit(int[] inside, double g, double h)
{
var d = grid.Cuts.Length;
var candidates = Enumerable.Range(0, d).ToList();
if (shape.Features < d)
{
random.Shuffle(candidates);
candidates = [.. candidates.Take(shape.Features).Order()];
}
var parent = g * g / (h + shape.Lambda);
var bestGain = shape.MinGain;
(int, int, bool)? best = null;
Span<double> sumG = stackalloc double[Bins + 1];
Span<double> sumH = stackalloc double[Bins + 1];
Span<int> counts = stackalloc int[Bins + 1];
foreach (var j in candidates)
{
var cuts = grid.Cuts[j].Length;
if (cuts == 0)
{
continue;
}
sumG.Clear();
sumH.Clear();
counts.Clear();
double missingG = 0, missingH = 0;
var missing = 0;
var bins = grid.Bin[j];
foreach (var i in inside)
{
if (bins[i] == Grid.Missing)
{
missingG += gradient[i];
missingH += hessian[i];
missing++;
}
else
{
sumG[bins[i]] += gradient[i];
sumH[bins[i]] += hessian[i];
counts[bins[i]]++;
}
}
double leftG = 0, leftH = 0;
var leftN = 0;
for (var cut = 0; cut < cuts; cut++)
{
leftG += sumG[cut];
leftH += sumH[cut];
leftN += counts[cut];
for (var side = 0; side < (missing > 0 ? 2 : 1); side++)
{
var missingGoesLeft = side == 0;
var gl = leftG + (missingGoesLeft ? missingG : 0);
var hl = leftH + (missingGoesLeft ? missingH : 0);
var nl = leftN + (missingGoesLeft ? missing : 0);
var nr = inside.Length - nl;
if (nl < shape.MinLeaf || nr < shape.MinLeaf)
{
continue;
}
var gain = (gl * gl / (hl + shape.Lambda)) + ((g - gl) * (g - gl) / (h - hl + shape.Lambda)) - parent;
if (gain > bestGain + 1e-12)
{
bestGain = gain;
best = (j, cut, missingGoesLeft);
}
}
}
}
return best;
}
}
}
/// <summary>
/// From a score to a probability that can be trusted (SPEC 11.3), fitted on scores the learner had not studied: Platt with
/// few cases, isotonic with many. A score that tells nothing, or the opposite, becomes the plain share of wins.
/// </summary>
public sealed record Calibration
{
public const string PlattKind = "platt";
public const string IsotonicKind = "isotonic";
/// <summary>Below this many cases the isotonic steps would follow the noise.</summary>
public const int IsotonicFrom = 1000;
public string Kind { get; init; } = PlattKind;
public double Slope { get; init; } = 1;
public double Offset { get; init; }
public IReadOnlyList<double> Scores { get; init; } = [];
public IReadOnlyList<double> Values { get; init; } = [];
public double Probability(double score)
{
if (Kind != IsotonicKind || Scores.Count == 0)
{
return Odds.Probability((Slope * score) + Offset);
}
if (score <= Scores[0])
{
return Values[0];
}
for (var i = 1; i < Scores.Count; i++)
{
if (score <= Scores[i])
{
var share = (score - Scores[i - 1]) / (Scores[i] - Scores[i - 1]);
return Values[i - 1] + (share * (Values[i] - Values[i - 1]));
}
}
return Values[^1];
}
public static Calibration Fit(IReadOnlyList<double> scores, IReadOnlyList<bool> wins) =>
scores?.Count >= IsotonicFrom ? Isotonic(scores, wins) : Platt(scores ?? [], wins);
public static Calibration Platt(IReadOnlyList<double> scores, IReadOnlyList<bool> wins)
{
ArgumentNullException.ThrowIfNull(scores);
ArgumentNullException.ThrowIfNull(wins);
var positives = wins.Count(w => w);
var flat = new Calibration { Slope = 0, Offset = Odds.Logit((positives + 1.0) / (wins.Count + 2)) };
if (positives == 0 || positives == wins.Count || scores.Distinct().Count() < 2)
{
return flat;
}
// Platt's smoothed targets, then Newton on two numbers.
var high = (positives + 1.0) / (positives + 2);
var low = 1.0 / (wins.Count - positives + 2);
double slope = 0, offset = flat.Offset;
for (var step = 0; step < 100; step++)
{
double ga = 0, gb = 0, haa = 1e-9, hab = 0, hbb = 1e-9;
for (var i = 0; i < scores.Count; i++)
{
var p = Odds.Probability((slope * scores[i]) + offset);
var error = (wins[i] ? high : low) - p;
var weight = Math.Max(p * (1 - p), 1e-9);
ga += error * scores[i];
gb += error;
haa += weight * scores[i] * scores[i];
hab += weight * scores[i];
hbb += weight;
}
var determinant = (haa * hbb) - (hab * hab);
if (Math.Abs(determinant) < 1e-15)
{
break;
}
var da = Math.Clamp(((ga * hbb) - (gb * hab)) / determinant, -5, 5);
var db = Math.Clamp(((gb * haa) - (ga * hab)) / determinant, -5, 5);
slope += da;
offset += db;
if (Math.Abs(da) < 1e-10 && Math.Abs(db) < 1e-10)
{
break;
}
}
// A negative slope says the learner was wrong more than right where it had not studied: it knows nothing.
return slope > 0 && double.IsFinite(slope) && double.IsFinite(offset) ? new Calibration { Slope = slope, Offset = offset } : flat;
}
/// <summary>Pool adjacent violators, then a line through the middle of each step; never exactly 0 or 1.</summary>
public static Calibration Isotonic(IReadOnlyList<double> scores, IReadOnlyList<bool> wins)
{
ArgumentNullException.ThrowIfNull(scores);
ArgumentNullException.ThrowIfNull(wins);
var blocks = new List<(double Score, double Wins, double Count)>();
foreach (var same in scores.Select((s, i) => (Score: s, Win: wins[i])).GroupBy(x => x.Score).OrderBy(g => g.Key))
{
blocks.Add((same.Key * same.Count(), same.Count(x => x.Win), same.Count()));
while (blocks.Count > 1 && blocks[^2].Wins / blocks[^2].Count >= blocks[^1].Wins / blocks[^1].Count)
{
var (a, b) = (blocks[^2], blocks[^1]);
blocks.RemoveAt(blocks.Count - 1);
blocks[^1] = (a.Score + b.Score, a.Wins + b.Wins, a.Count + b.Count);
}
}
return new Calibration
{
Kind = IsotonicKind,
Scores = [.. blocks.Select(b => b.Score / b.Count)],
Values = [.. blocks.Select(b => Math.Clamp(b.Wins / b.Count, 1.0 / (blocks[0].Count + 2), 1 - (1.0 / (blocks[^1].Count + 2))))],
};
}
}
+48
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
@@ -20,6 +21,53 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
public LearningStore Store { get; } = new(db, clock);
public ModelStore Models { get; } = new(db);
/// <summary>The file of the first model; the one built into the program unless a test gives another.</summary>
public FirstModelFile? First { get; init; } = FirstModel.Embedded;
private const string HistoryKey = "history";
private sealed record HistoryState(string Fingerprint);
/// <summary>
/// At the start (SPEC 11.2): the examples of the history in the program, when they changed, take the place of the old
/// ones; with no model at all the first one takes charge, in observation.
/// </summary>
public async Task PrepareHistoryAsync(CancellationToken cancellationToken)
{
if (First is not { } file)
{
return;
}
var fingerprint = FirstModel.Fingerprint(file);
if (await Store.StateAsync<HistoryState>(HistoryKey, cancellationToken).ConfigureAwait(false) is { } state && state.Fingerprint == fingerprint)
{
return;
}
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("DELETE FROM ml_labels WHERE feature_id IN (SELECT id FROM ml_features WHERE source = @h)", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false);
await s.ExecuteAsync("DELETE FROM ml_features WHERE source = @h", cancellationToken, ("h", CaseSources.History)).ConfigureAwait(false);
foreach (var example in file.Examples)
{
await LearningStore.AddAsync(s, clock, example, cancellationToken).ConfigureAwait(false);
}
if (file.Model is { } model && file.Report is { } report && await s.CountAsync("SELECT COUNT(*) FROM ml_models").ConfigureAwait(false) == 0)
{
var row = await ModelStore.RegisterAsync(s, clock, model, report, ModelStatuses.Champion, CaseSources.History, clock.UtcNow, cancellationToken).ConfigureAwait(false);
await ModelStore.AddEventAsync(s, clock, ModelEvents.First, row.Version,
$"Primo modello: versione {row.Version}, {LearnerNames.Label(row.Learner).ToLower(CultureInfo.GetCultureInfo("it-IT"))}, addestrata su {row.Examples} esempi ricostruiti dallo storico. Parte in osservazione.",
cancellationToken).ConfigureAwait(false);
}
await LearningStore.SaveStateAsync(s, clock, HistoryKey, new HistoryState(fingerprint), cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>What the decision of <paramref name="day"/> needs from learning; null when it could not be prepared.</summary>
public async Task<LearningTurn?> PrepareAsync(string strategy, string stage, DateOnly day, BacktestDataset data, Func<IStrategy> create, IReadOnlyDictionary<string, DateOnly>? earnings,
CancellationToken cancellationToken)
+155
View File
@@ -0,0 +1,155 @@
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Learning;
/// <summary>What became of a model.</summary>
public static class ModelStatuses
{
/// <summary>In charge: its estimates count (or are only noted, in observation).</summary>
public const string Champion = "champion";
/// <summary>On trial beside the one in charge.</summary>
public const string Challenger = "challenger";
/// <summary>Replaced by a promotion.</summary>
public const string Retired = "retired";
/// <summary>A challenger that did not do better in time.</summary>
public const string Discarded = "discarded";
/// <summary>Promoted, then the user took the promotion back.</summary>
public const string Undone = "undone";
/// <summary>Tried while choosing and not chosen: it is in the register because the number of attempts counts.</summary>
public const string Tried = "tried";
}
/// <summary>A row of the register of the models (SPEC 11.3).</summary>
public sealed record ModelRow(Guid Id, int? Version, string Learner, string Status, string Source, DateTimeOffset TrainedAt, int Examples, int ThresholdDone, Guid? ReplacedId, TrainedModel? Model,
ModelReport Report);
/// <summary>An estimate on an example as it was saved when the example was born (SPEC 11.5).</summary>
public sealed record PredictionRow(Guid FeatureId, Guid ModelId, double Probability, double BaseRate, double Multiplier, bool InCharge);
/// <summary>An entry of the history of the model: what the user reads in "Storia".</summary>
public sealed record ModelEvent(string Kind, int? Version, string Text, DateTimeOffset At);
/// <summary>Kinds of the events of the model.</summary>
public static class ModelEvents
{
public const string First = "first";
public const string Trained = "trained";
public const string Promoted = "promoted";
public const string Discarded = "discarded";
public const string Undone = "undone";
public const string Activated = "activated";
public const string SetAside = "set_aside";
public const string Back = "back";
public const string Drift = "drift";
}
/// <summary>The register of the models, their estimates and their history (SPEC 11.3–11.5).</summary>
public sealed class ModelStore(Database db)
{
private const string Columns = "id, version, learner, status, source, trained_at, examples, threshold_done, replaced_id, model, report FROM ml_models";
public Task<List<ModelRow>> AllAsync(CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT " + Columns + " ORDER BY trained_at, id", Read), cancellationToken);
public Task<ModelRow?> FindAsync(string status, CancellationToken cancellationToken) => db.ReadAsync(s => FindAsync(s, status), cancellationToken);
public static Task<ModelRow?> FindAsync(DbSession s, string status)
{
ArgumentNullException.ThrowIfNull(s);
return s.FirstOrDefaultAsync("SELECT " + Columns + " WHERE status = @s ORDER BY trained_at DESC, id DESC", Read, ("s", status));
}
public Task<long> CountAsync(CancellationToken cancellationToken) => db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_models"), cancellationToken);
/// <summary>Writes the result of a training in the register: the chosen model with its version, the others as attempts.</summary>
public static async Task<ModelRow> RegisterAsync(DbSession s, IClock clock, TrainedModel model, ModelReport report, string status, string source, DateTimeOffset trainedAt,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(model);
ArgumentNullException.ThrowIfNull(report);
var version = (int)await s.CountAsync("SELECT COALESCE(MAX(version), 0) FROM ml_models").ConfigureAwait(false) + 1;
var row = new ModelRow(Ids.NewId(clock), version, model.Learned.Learner, status, source, trainedAt, report.Examples, 0, null, model, report);
await AddAsync(s, clock, row, cancellationToken).ConfigureAwait(false);
foreach (var attempt in report.Attempts.Where(a => !a.Chosen))
{
await AddAsync(s, clock, new ModelRow(Ids.NewId(clock), null, attempt.Learner, ModelStatuses.Tried, source, trainedAt, report.Examples, 0, row.Id, null,
new ModelReport { Examples = report.Examples, Live = report.Live, Attempts = [attempt] }), cancellationToken).ConfigureAwait(false);
}
return row;
}
private static Task<int> AddAsync(DbSession s, IClock clock, ModelRow row, CancellationToken cancellationToken) =>
s.ExecuteAsync(
"INSERT INTO ml_models (id, version, learner, status, source, trained_at, examples, threshold_done, replaced_id, model, report, created_at, updated_at) " +
"VALUES (@id, @v, @l, @st, @src, @at, @n, 0, @r, @m, @rep, @now, @now)", cancellationToken,
("id", row.Id), ("v", row.Version), ("l", row.Learner), ("st", row.Status), ("src", row.Source), ("at", row.TrainedAt), ("n", row.Examples), ("r", row.ReplacedId),
("m", row.Model is { } model ? new DbJson(JsonSerializer.Serialize(model)) : null), ("rep", new DbJson(JsonSerializer.Serialize(row.Report))), ("now", clock.UtcNow));
public static Task<int> SetStatusAsync(DbSession s, IClock clock, Guid id, string status, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync("UPDATE ml_models SET status = @st, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("st", status), ("now", clock.UtcNow));
}
/// <summary>The model a promotion replaced, so the promotion can be taken back.</summary>
public static Task<int> SetReplacedAsync(DbSession s, IClock clock, Guid id, Guid? replaced, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync("UPDATE ml_models SET replaced_id = @r, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("r", replaced), ("now", clock.UtcNow));
}
public static Task<int> SetThresholdAsync(DbSession s, IClock clock, Guid id, int threshold, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync("UPDATE ml_models SET threshold_done = @t, updated_at = @now WHERE id = @id", cancellationToken, ("id", id), ("t", threshold), ("now", clock.UtcNow));
}
// ---- Estimates ----------------------------------------------------------------------------------------------
public static Task<int> AddPredictionAsync(DbSession s, IClock clock, PredictionRow p, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(p);
return s.ExecuteAsync(
"INSERT INTO ml_predictions (id, feature_id, model_id, probability, base_rate, multiplier, in_charge, created_at) VALUES (@id, @f, @m, @p, @b, @mu, @c, @now) " +
"ON CONFLICT (feature_id, model_id) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("f", p.FeatureId), ("m", p.ModelId), ("p", p.Probability), ("b", p.BaseRate), ("mu", p.Multiplier), ("c", p.InCharge), ("now", clock.UtcNow));
}
public Task<List<PredictionRow>> PredictionsAsync(CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT feature_id, model_id, probability, base_rate, multiplier, in_charge FROM ml_predictions ORDER BY created_at, id",
r => new PredictionRow(r.Id("feature_id"), r.Id("model_id"), r.Measure("probability"), r.Measure("base_rate"), r.Measure("multiplier"), r.Bool("in_charge"))), cancellationToken);
// ---- History ------------------------------------------------------------------------------------------------
public static Task<int> AddEventAsync(DbSession s, IClock clock, string kind, int? version, string text, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(clock);
return s.ExecuteAsync("INSERT INTO ml_events (id, kind, version, text, data, created_at) VALUES (@id, @k, @v, @t, NULL, @now)", cancellationToken,
("id", Ids.NewId(clock)), ("k", kind), ("v", version), ("t", text), ("now", clock.UtcNow));
}
public Task<List<ModelEvent>> EventsAsync(CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT kind, version, text, created_at FROM ml_events ORDER BY created_at, id",
r => new ModelEvent(r.Text("kind"), r.IsNull("version") ? null : (int)r.Number("version"), r.Text("text"), r.Moment("created_at"))), cancellationToken);
private static ModelRow Read(DbRow r) => new(r.Id("id"), r.IsNull("version") ? null : (int)r.Number("version"), r.Text("learner"), r.Text("status"), r.Text("source"), r.Moment("trained_at"),
(int)r.Number("examples"), (int)r.Number("threshold_done"), r.IdOrNull("replaced_id"), r.IsNull("model") ? null : JsonSerializer.Deserialize<TrainedModel>(r.Json("model").Text),
JsonSerializer.Deserialize<ModelReport>(r.Json("report").Text) ?? new ModelReport());
}
+308
View File
@@ -0,0 +1,308 @@
using Anubis.Core;
using Anubis.Strategies;
namespace Anubis.Learning;
/// <summary>The values of a clue the model studied: below the 1% or above the 99% it has hardly ever seen it.</summary>
public sealed record ClueRange(double Low, double High, int Cases);
/// <summary>A model ready to estimate: the clues it uses, what it learned, how its score becomes a probability.</summary>
public sealed record TrainedModel
{
public IReadOnlyList<string> Clues { get; init; } = [];
public Learned Learned { get; init; } = new();
public Calibration Calibration { get; init; } = new();
public IReadOnlyDictionary<string, ClueRange> Ranges { get; init; } = new Dictionary<string, ClueRange>();
/// <summary>The strategies whose examples trained it.</summary>
public IReadOnlyList<string> Strategies { get; init; } = [];
public double Probability(IReadOnlyDictionary<string, double> features) => Calibration.Probability(Learned.Score(Trainer.Row(Clues, features)));
}
/// <summary>How much a group of clues weighs, out of 100.</summary>
public sealed record ClueWeight(string Group, decimal Share);
/// <summary>What one learner did in the validation: the register keeps every attempt (SPEC 11.3).</summary>
public sealed record Attempt(string Learner, Scores Forward, Scores Combined, bool Chosen);
/// <summary>The validation of a model: how many examples, every attempt, why this one, what it looks at.</summary>
public sealed record ModelReport
{
public int Examples { get; init; }
public int Live { get; init; }
public IReadOnlyDictionary<string, int> ByStrategy { get; init; } = new Dictionary<string, int>();
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
public DateOnly? FirstDay { get; init; }
public DateOnly? LastDay { get; init; }
public IReadOnlyList<Attempt> Attempts { get; init; } = [];
/// <summary>The whole reason of the choice, in Italian.</summary>
public string Reason { get; init; } = "";
/// <summary>True when no strategy with capital had examples, so the gain was measured on all of them.</summary>
public bool AllStrategiesCounted { get; init; }
public IReadOnlyList<ClueWeight> Weights { get; init; } = [];
public int Splits { get; init; }
public Attempt? Chosen => Attempts.FirstOrDefault(a => a.Chosen);
}
/// <summary>What a training starts from.</summary>
public sealed record TrainingInput(IReadOnlyList<Example> Examples)
{
/// <summary>The share of winners of each strategy in its backtest (SPEC 11.1).</summary>
public IReadOnlyDictionary<string, double> BaseRates { get; init; } = new Dictionary<string, double>();
/// <summary>The capital of each strategy in euro.</summary>
public IReadOnlyDictionary<string, double> Capital { get; init; } = new Dictionary<string, double>();
/// <summary>The strategies with capital: the only ones the gain is measured on (SPEC 11.3).</summary>
public IReadOnlySet<string> Funded { get; init; } = new HashSet<string>();
public MultiplierRule Rule { get; init; } = MultiplierRule.Standard;
public long Seed { get; init; } = 11;
}
public sealed record TrainingResult(TrainedModel Model, ModelReport Report);
/// <summary>
/// Trains and chooses (SPEC 11.3, ADR 0018). The rule is fixed before looking: the winner is the learner with the best mean
/// gain per proposed operation on examples it had not studied; at equal gain the smaller log-loss. The forest must beat the
/// others on both, or it stays out.
/// </summary>
public static class Trainer
{
/// <summary>With fewer examples nothing can be verified.</summary>
public const int MinExamples = 100;
private const int MinTrain = 40;
public static double[] Row(IReadOnlyList<string> clues, IReadOnlyDictionary<string, double> features)
{
ArgumentNullException.ThrowIfNull(clues);
ArgumentNullException.ThrowIfNull(features);
return [.. clues.Select(c => features.TryGetValue(c, out var value) ? value : double.NaN)];
}
/// <summary>The share of winners by strategy: what a model that knows nothing would answer.</summary>
public static IReadOnlyDictionary<string, double> SharesOf(IEnumerable<Example> examples) =>
examples.Where(e => e.IsLabelled).GroupBy(e => e.Strategy, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => (double)g.Count(e => e.Label!.Win == true) / g.Count(), StringComparer.Ordinal);
/// <summary>
/// The clues that enter (SPEC 11.2): those rebuilt from the history, and those without one only when at least
/// <see cref="Clues.MinLive"/> live examples contain them. A clue that never changes tells nothing.
/// </summary>
public static IReadOnlyList<string> CluesOf(IReadOnlyList<Example> examples)
{
ArgumentNullException.ThrowIfNull(examples);
return
[
.. Clues.All.Where(c => c.FromHistory || examples.Count(e => e.Source == CaseSources.Live && e.Features.ContainsKey(c.Key)) >= Clues.MinLive)
.Select(c => c.Key)
.Where(key => examples.Where(e => e.Features.ContainsKey(key)).Select(e => e.Features[key]).Distinct().Take(2).Count() > 1),
];
}
/// <summary>Null when there are too few examples, or only winners or only losers.</summary>
public static TrainingResult? Train(TrainingInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(input);
var cases = input.Examples.Where(e => e.IsLabelled).OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal).ToList();
var clues = CluesOf(cases);
if (cases.Count < MinExamples || clues.Count == 0 || !BothOutcomes(cases))
{
return null;
}
bool IsFunded(Example e) => input.Funded.Contains(e.Strategy);
var all = !cases.Any(IsFunded);
var forward = CaseSplits.Forward(cases);
var combined = CaseSplits.Combinatorial(cases);
var attempts = new List<Attempt>();
var fitted = new Dictionary<string, List<(TrainedModel Model, Split Split, IReadOnlyDictionary<string, double> Rates)>>(StringComparer.Ordinal);
foreach (var learner in LearnerNames.All)
{
cancellationToken.ThrowIfCancellationRequested();
var folds = new List<(TrainedModel, Split, IReadOnlyDictionary<string, double>)>();
var ahead = Verify(learner, cases, forward, clues, input, null, cancellationToken);
var mixed = Verify(learner, cases, combined, clues, input, folds, cancellationToken);
fitted[learner] = folds;
attempts.Add(new Attempt(learner, ScoresOf(ahead, input, all ? null : IsFunded), ScoresOf(mixed, input, all ? null : IsFunded), false));
}
var (chosen, reason) = Choose(attempts);
var model = Fit(chosen, cases, clues, input.Seed, cancellationToken);
var report = new ModelReport
{
Examples = cases.Count,
Live = cases.Count(e => e.Source == CaseSources.Live),
ByStrategy = cases.GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal),
BaseRates = input.BaseRates,
FirstDay = cases[0].Day,
LastDay = cases[^1].Day,
Attempts = [.. attempts.Select(a => a with { Chosen = a.Learner == chosen })],
Reason = reason,
AllStrategiesCounted = all,
Weights = WeightsOf(fitted[chosen], cases, clues, input.Seed),
Splits = combined.Count,
};
return new TrainingResult(model, report);
}
/// <summary>The rule of the choice, fixed before looking at the numbers.</summary>
public static (string Learner, string Reason) Choose(IReadOnlyList<Attempt> attempts)
{
ArgumentNullException.ThrowIfNull(attempts);
// Gains that differ by less than a tenth of a cent are the same gain.
static double Gain(Attempt a) => Math.Round(a.Combined.Improvement, 3);
var best = attempts.Where(a => a.Learner != LearnerNames.Forest).OrderByDescending(Gain).ThenBy(a => a.Combined.LogLoss).ThenBy(a => a.Learner == LearnerNames.Boosting ? 0 : 1).First();
var forest = attempts.FirstOrDefault(a => a.Learner == LearnerNames.Forest);
if (forest is not null && attempts.Where(a => a != forest).All(a => Gain(forest) > Gain(a) && forest.Combined.LogLoss < a.Combined.LogLoss))
{
return (forest.Learner, "La foresta casuale ha battuto gli altri due sia sul guadagno medio per operazione proposta sia sulle probabilità.");
}
var others = attempts.Where(a => a.Learner != LearnerNames.Forest && a != best).ToList();
return (best.Learner, others.All(a => Gain(best) > Gain(a))
? $"{LearnerNames.Label(best.Learner)}: il miglior guadagno medio per operazione proposta su esempi mai visti."
: $"{LearnerNames.Label(best.Learner)}: a parità di guadagno, probabilità più vicine al vero su esempi mai visti.");
}
/// <summary>A model on all the given examples: the calibration is fitted on estimates of examples each fit had not studied.</summary>
public static TrainedModel Fit(string learner, IReadOnlyList<Example> cases, IReadOnlyList<string> clues, long seed, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(cases);
ArgumentNullException.ThrowIfNull(clues);
var scores = new List<double>();
var wins = new List<bool>();
foreach (var fold in CaseSplits.Folds(cases))
{
cancellationToken.ThrowIfCancellationRequested();
var train = fold.Train.Select(i => cases[i]).ToList();
if (train.Count < MinTrain || !BothOutcomes(train))
{
continue;
}
var inner = Learners.Fit(learner, Rows(train, clues), Wins(train), seed);
scores.AddRange(fold.Test.Select(i => inner.Score(Row(clues, cases[i].Features))));
wins.AddRange(fold.Test.Select(i => cases[i].Label!.Win == true));
}
return new TrainedModel
{
Clues = clues,
Learned = Learners.Fit(learner, Rows(cases, clues), Wins(cases), seed),
Calibration = wins.Count > 0 ? Calibration.Fit(scores, wins) : Calibration.Platt([], Wins(cases)),
Ranges = clues.ToDictionary(c => c, c => RangeOf(cases, c), StringComparer.Ordinal),
Strategies = [.. cases.Select(c => c.Strategy).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)],
};
}
private static List<Estimate> Verify(string learner, List<Example> cases, IReadOnlyList<Split> splits, IReadOnlyList<string> clues, TrainingInput input,
List<(TrainedModel, Split, IReadOnlyDictionary<string, double>)>? folds, CancellationToken cancellationToken)
{
var estimates = new List<Estimate>();
foreach (var split in splits)
{
cancellationToken.ThrowIfCancellationRequested();
var train = split.Train.Select(i => cases[i]).ToList();
if (train.Count < MinTrain || !BothOutcomes(train))
{
continue;
}
// The base rate too is what the training examples knew: the one of the whole history would look ahead.
var model = Fit(learner, train, clues, input.Seed, cancellationToken);
var rates = SharesOf(train);
folds?.Add((model, split, rates));
foreach (var example in split.Test.Select(i => cases[i]).Where(e => rates.ContainsKey(e.Strategy)))
{
var probability = model.Probability(example.Features);
var rate = rates[example.Strategy];
estimates.Add(new Estimate(example, probability, rate, input.Rule.Of(probability, rate)));
}
}
return estimates;
}
private static Scores ScoresOf(IReadOnlyList<Estimate> estimates, TrainingInput input, Func<Example, bool>? funded) =>
Judge.Score(Judge.Weigh(estimates, input.BaseRates), input.Capital, funded);
/// <summary>
/// What the model looks at: how much worse its estimates get, on examples it had not studied, when the values of a
/// group of clues are shuffled among them. Out of 100 with the largest remainder; all zero when nothing helps.
/// </summary>
private static List<ClueWeight> WeightsOf(IReadOnlyList<(TrainedModel Model, Split Split, IReadOnlyDictionary<string, double> Rates)> folds, List<Example> cases,
IReadOnlyList<string> clues, long seed)
{
var groups = clues.GroupBy(c => Clues.Find(c)!.Group, StringComparer.Ordinal).Select(g => (Name: g.Key, Columns: g.Select(c => IndexOf(clues, c)).ToArray())).ToList();
var losses = new double[groups.Count];
foreach (var (model, split, _) in folds)
{
var rows = split.Test.Select(i => Row(clues, cases[i].Features)).ToList();
var wins = split.Test.Select(i => cases[i].Label!.Win == true).ToList();
double Loss(IEnumerable<double[]> x) => x.Select((r, i) => Judge.LogLoss(wins[i], model.Calibration.Probability(model.Learned.Score(r)))).Sum();
var whole = Loss(rows);
for (var g = 0; g < groups.Count; g++)
{
var order = Enumerable.Range(0, rows.Count).ToArray();
new FixedRandom(seed + g).Shuffle(order);
losses[g] += Loss(rows.Select((r, i) =>
{
var mixed = (double[])r.Clone();
foreach (var column in groups[g].Columns)
{
mixed[column] = rows[order[i]][column];
}
return mixed;
})) - whole;
}
}
var shares = Format.Shares([.. losses.Select(l => (decimal)Math.Round(Math.Max(0, l), 9))], 0);
return [.. groups.Select((g, i) => new ClueWeight(g.Name, shares[i])).OrderByDescending(w => w.Share).ThenBy(w => w.Group, StringComparer.Ordinal)];
}
private static int IndexOf(IReadOnlyList<string> clues, string key)
{
for (var i = 0; i < clues.Count; i++)
{
if (clues[i] == key)
{
return i;
}
}
return -1;
}
private static ClueRange RangeOf(IReadOnlyList<Example> cases, string clue)
{
var values = cases.Where(c => c.Features.ContainsKey(clue)).Select(c => c.Features[clue]).Order().ToList();
return values.Count == 0 ? new ClueRange(0, 0, 0) : new ClueRange(values[(int)(0.01 * (values.Count - 1))], values[(int)Math.Ceiling(0.99 * (values.Count - 1))], values.Count);
}
private static List<double[]> Rows(IReadOnlyList<Example> cases, IReadOnlyList<string> clues) => [.. cases.Select(c => Row(clues, c.Features))];
private static List<bool> Wins(IReadOnlyList<Example> cases) => [.. cases.Select(c => c.Label!.Win == true)];
private static bool BothOutcomes(IReadOnlyList<Example> cases) => cases.Any(c => c.Label!.Win == true) && cases.Any(c => c.Label!.Win != true);
}
+1
View File
@@ -332,6 +332,7 @@ public sealed partial class TradingService : IDisposable
_accountsRetryAt = _clock.UtcNow + AccountRetry;
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("modello", () => Learning.PrepareHistoryAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false);
_started = true;
+459
View File
@@ -0,0 +1,459 @@
using System.Text.Json;
using Anubis.Learning;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The learners, their calibration, the purged validation and the choice (SPEC 11.1, 11.3; issue #63).</summary>
[TestClass]
[TestCategory(Category.Unit)]
public sealed class LearningModelTests
{
private static readonly DateOnly First = new(2020, 1, 1);
/// <summary>
/// Examples whose outcome depends on what <paramref name="chance"/> says of the clues. Wins pay 2%, losses cost 2%:
/// a filter that avoids likely losses earns.
/// </summary>
internal static IReadOnlyList<Example> Cases(int count, Func<double[], double> chance, int seed = 5, string strategy = StrategyNames.CryptoTrend, int length = 8, string source = CaseSources.History)
{
var gen = new Gen(seed);
return
[
.. Enumerable.Range(0, count).Select(i =>
{
var clues = new[] { gen.Double(), gen.Normal(), gen.Double(), gen.Normal() };
var win = gen.Double() < chance(clues);
var day = First.AddDays(i * 2);
var result = win ? 0.02 : -0.02;
return new Example(Guid.NewGuid(), strategy, "C" + (i % 7), source, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "test", 0.2m, null, null,
new Dictionary<string, double>
{
[Clues.Strength] = clues[0],
[Clues.Volatility] = clues[1],
[Clues.Volume] = clues[2],
[Clues.MarketTrend] = clues[3],
})
{
Label = new CaseLabel(win, result, day, day.AddDays(1 + (i % length)), "exit"),
};
}),
];
}
private static List<double[]> Rows(IEnumerable<Example> cases) => [.. cases.Select(c => Trainer.Row([Clues.Strength, Clues.Volatility, Clues.Volume, Clues.MarketTrend], c.Features))];
private static List<bool> Wins(IEnumerable<Example> cases) => [.. cases.Select(c => c.Label!.Win == true)];
private static double Loss(Learned model, IReadOnlyList<Example> cases) =>
cases.Average(c => Judge.LogLoss(c.Label!.Win == true, Odds.Probability(model.Score(Rows([c])[0]))));
/// <summary>Each learner finds a relation that is there: on new examples it is clearly better than the plain share of wins.</summary>
[TestMethod]
[DataRow(LearnerNames.Logistic)]
[DataRow(LearnerNames.Boosting)]
[DataRow(LearnerNames.Forest)]
public void ALearnerFindsWhatIsThere(string learner)
{
static double Chance(double[] x) => Odds.Probability((4 * x[0]) - 2);
var train = Cases(1200, Chance, 5);
var fresh = Cases(1200, Chance, 6);
var model = Learners.Fit(learner, Rows(train), Wins(train), 1);
var share = Wins(train).Count(w => w) / 1200.0;
var plain = fresh.Average(c => Judge.LogLoss(c.Label!.Win == true, share));
Assert.IsLessThan(plain - 0.03, Loss(model, fresh));
}
/// <summary>The trees find what a straight line cannot: an exclusive or.</summary>
[TestMethod]
public void TheTreesFindWhatALineCannot()
{
static double Chance(double[] x) => (x[0] > 0.5) == (x[2] > 0.5) ? 0.85 : 0.15;
var train = Cases(1500, Chance, 5);
var fresh = Cases(1500, Chance, 6);
var line = Loss(Learners.Fit(LearnerNames.Logistic, Rows(train), Wins(train), 1), fresh);
var trees = Loss(Learners.Fit(LearnerNames.Boosting, Rows(train), Wins(train), 1), fresh);
Assert.IsGreaterThan(0.65, line);
Assert.IsLessThan(0.55, trees);
}
/// <summary>Same data and seed, same model, to the last digit; and it survives the database as it was.</summary>
[TestMethod]
[DataRow(LearnerNames.Logistic)]
[DataRow(LearnerNames.Boosting)]
[DataRow(LearnerNames.Forest)]
public void TheSameDataGiveTheSameModel(string learner)
{
var cases = Cases(300, x => Odds.Probability(x[1]));
var clues = Trainer.CluesOf(cases);
var one = Trainer.Fit(learner, cases, clues, 3);
var two = Trainer.Fit(learner, cases, clues, 3);
Assert.AreEqual(JsonSerializer.Serialize(one), JsonSerializer.Serialize(two));
var back = JsonSerializer.Deserialize<TrainedModel>(JsonSerializer.Serialize(one))!;
foreach (var c in cases)
{
Assert.AreEqual(one.Probability(c.Features), back.Probability(c.Features));
}
}
/// <summary>A missing clue is no trouble, neither to learn nor to estimate, and tells what it tells.</summary>
[TestMethod]
[DataRow(LearnerNames.Logistic)]
[DataRow(LearnerNames.Boosting)]
[DataRow(LearnerNames.Forest)]
public void AMissingClueIsNoTrouble(string learner)
{
var cases = Cases(600, x => Odds.Probability((4 * x[0]) - 2)).Select((c, i) => i % 3 > 0 ? c
: c with { Features = c.Features.Where(f => f.Key != Clues.Strength).ToDictionary(f => f.Key, f => f.Value) }).ToList();
var model = Trainer.Fit(learner, cases, Trainer.CluesOf(cases), 3);
foreach (var features in new[] { new Dictionary<string, double>(), new Dictionary<string, double> { [Clues.Strength] = double.NaN }, new Dictionary<string, double> { [Clues.Strength] = 1e9, [Clues.Volatility] = -1e9 } })
{
var p = model.Probability(features);
Assert.IsTrue(p is > 0 and < 1, $"{p}");
}
}
/// <summary>Trees keep many examples in every leaf.</summary>
[TestMethod]
public void EveryLeafHasManyExamples()
{
var cases = Cases(800, x => Odds.Probability(x[1]));
var rows = Rows(cases);
Assert.AreEqual(40, Learners.MinLeaf(800));
foreach (var tree in Learners.Fit(LearnerNames.Boosting, rows, Wins(cases), 1).Trees!.Trees)
{
Assert.IsLessThanOrEqualTo(15, tree.Feature.Count, "no more than three levels");
}
}
[TestMethod]
public void PlattBringsScoresBackToTheTruth()
{
// The scores are three times too sure: the calibration must bring them back.
var gen = new Gen(9);
var scores = Enumerable.Range(0, 900).Select(_ => gen.Normal() * 3).ToList();
var wins = scores.Select(s => gen.Double() < Odds.Probability(s / 3)).ToList();
var fitted = Calibration.Fit(scores, wins);
Assert.AreEqual(Calibration.PlattKind, fitted.Kind);
Assert.AreEqual(1.0 / 3, fitted.Slope, 0.07);
// Scores that say the opposite, or nothing, become the plain share of wins.
var upside = Calibration.Fit(scores, [.. wins.Select(w => !w)]);
Assert.AreEqual(0, upside.Slope);
Assert.AreEqual((double)wins.Count(w => !w) / wins.Count, upside.Probability(5), 0.01);
Assert.AreEqual(0, Calibration.Platt([1, 1, 1, 1], [true, false, true, true]).Slope);
}
/// <summary>Isotonic on a known case: the classic pools, never down, never 0 or 1.</summary>
[TestMethod]
public void IsotonicNeverGoesDown()
{
var known = Calibration.Isotonic([1, 2, 3, 4, 5, 6], [false, true, false, true, true, true]);
Assert.AreEqual(0.5, known.Probability(2.5), 1e-9);
var gen = new Gen(4);
var scores = Enumerable.Range(0, 1500).Select(_ => gen.Normal()).ToList();
var wins = scores.Select(s => gen.Double() < Odds.Probability(2 * s)).ToList();
var fitted = Calibration.Fit(scores, wins);
Assert.AreEqual(Calibration.IsotonicKind, fitted.Kind);
var last = 0.0;
for (var s = -6.0; s <= 6; s += 0.01)
{
var p = fitted.Probability(s);
Assert.IsTrue(p >= last && p is > 0 and < 1, $"{s}: {p} after {last}");
last = p;
}
Assert.AreEqual(Odds.Probability(1), fitted.Probability(0.5), 0.08);
}
// ---- Validation -------------------------------------------------------------------------------------------------
/// <summary>No training example overlaps a test one in time, nor starts in the embargo after it; going forward, all is over before.</summary>
[TestMethod]
public void TrainingAndTestNeverOverlap() => Property.ForAll(
gen =>
{
var at = First;
return Enumerable.Range(0, gen.Int(20, 80)).Select(i =>
{
at = at.AddDays(gen.Int(0, 6));
return Cases(1, _ => 0.5)[0] with { Day = at, Symbol = "S" + i, Label = new CaseLabel(gen.Bool(), 0.01, at, at.AddDays(gen.Int(0, 90)), "x") };
}).ToList();
},
cases =>
{
var splits = CaseSplits.Combinatorial(cases);
Assert.HasCount(15, splits);
foreach (var split in splits.Concat(CaseSplits.Folds(cases)))
{
foreach (var train in split.Train.Select(i => cases[i]))
{
foreach (var test in split.Test.Select(i => cases[i]))
{
Assert.IsTrue(train.Label!.ClosedDay < test.Day || train.Day > test.Label!.ClosedDay!.Value.AddDays(CaseSplits.Embargo), $"{train.Day}..{train.Label.ClosedDay} / {test.Day}..{test.Label!.ClosedDay}");
}
}
}
// Each example is verified by as many splits as it should be: 5 of the 15.
Assert.IsTrue(splits.SelectMany(s => s.Test).GroupBy(i => i).All(g => g.Count() == 5));
foreach (var split in CaseSplits.Forward(cases))
{
var begins = split.Test.Min(i => cases[i].Day);
Assert.IsTrue(split.Train.All(i => cases[i].Label!.ClosedDay < begins));
}
}, 40);
/// <summary>Known case: ten examples a month apart, each 40 days long.</summary>
[TestMethod]
public void ThePurgeOnAKnownCase()
{
var cases = Enumerable.Range(0, 6).Select(i =>
{
var day = First.AddDays(i * 30);
return Cases(1, _ => 0.5)[0] with { Day = day, Symbol = "S" + i, Label = new CaseLabel(true, 0.01, day, day.AddDays(40), "x") };
}).ToList();
// Groups of one example. Testing on example 2 (day 60 to 100, embargo to 110): 1 ends on day 70 and 3 starts on 90, so both go; 0 ends on day 40, 4 starts on 120.
var split = CaseSplits.Folds(cases, 6)[2];
CollectionAssert.AreEqual(new[] { 0, 4, 5 }, split.Train.ToArray());
}
// ---- Measures ---------------------------------------------------------------------------------------------------
private static Estimate Of(bool win, double probability, double rate = 0.4, double multiplier = 1, double result = 0.02, string strategy = StrategyNames.CryptoTrend) =>
new(Cases(1, _ => 0.5, strategy: strategy)[0] with { Label = new CaseLabel(win, win ? result : -result, First, First, "x") }, probability, rate, multiplier);
private static readonly Dictionary<string, double> Capital = new() { [StrategyNames.CryptoTrend] = 1000, [StrategyNames.EquityMomentum] = 1000 };
/// <summary>Who always says the same stays at 50%, whatever the share of wins.</summary>
[TestMethod]
public void AlwaysTheSameAnswerIsFiftyPercent()
{
foreach (var answer in new[] { 0.1, 0.4, 0.9 })
{
Assert.AreEqual(0.5, Judge.Precision([.. Enumerable.Range(0, 100).Select(i => Of(i < 37, answer))]));
}
Assert.AreEqual(1.0, Judge.Precision([Of(true, 0.6), Of(false, 0.2), Of(false, 0.1)]));
Assert.IsNull(Judge.Precision([Of(true, 0.6)]));
}
/// <summary>The gain is divided by the proposed operations, not by those left: discarding nearly all cannot look good.</summary>
[TestMethod]
public void AModelThatDiscardsNearlyAllDoesNotLookBetter()
{
// 50 wins of 4 euro, 50 losses of 2: keeping a single win earns 4 a piece on what is left, but 0.04 per proposal.
var all = Enumerable.Range(0, 100).Select(i => Of(i < 50, 0.4, result: i < 50 ? 0.02 : 0.01)).ToList();
var picky = all.Select((e, i) => e with { Multiplier = i == 0 ? 1 : 0 }).ToList();
Assert.AreEqual(1.0, Judge.Score(all, Capital).GainWith, 1e-9);
Assert.AreEqual(0.04, Judge.Score(picky, Capital).GainWith, 1e-9);
Assert.IsLessThan(0, Judge.Score(picky, Capital).Improvement);
// Zeroing the signals of a strategy without capital is no merit.
var other = Enumerable.Range(0, 100).Select(_ => Of(false, 0.1, multiplier: 0, strategy: StrategyNames.EquityMomentum));
Assert.AreEqual(0, Judge.Score([.. all, .. other], Capital, e => e.Strategy == StrategyNames.CryptoTrend).Improvement, 1e-9);
}
/// <summary>Losses mature first (SPEC 11.4): the weights give back the proportion of the base rate.</summary>
[TestMethod]
public void TheWeightsGiveBackTheProportionOfTheBaseRate()
{
var estimates = Enumerable.Range(0, 100).Select(i => Of(i < 20, 0.4)).ToList();
var weighed = Judge.Weigh(estimates, new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 });
Assert.AreEqual(0.4, weighed.Where(e => e.Win).Sum(e => e.Weight) / weighed.Sum(e => e.Weight), 1e-9);
Assert.AreEqual(100, weighed.Sum(e => e.Weight), 1e-9);
Assert.IsTrue(Judge.Weigh([.. estimates.Where(e => e.Win)], new Dictionary<string, double> { [StrategyNames.CryptoTrend] = 0.4 }).All(e => e.Weight == 1));
}
[TestMethod]
public void TheCalibrationErrorCountsOnlyBandsWithEnoughCases()
{
// 20 cases at 42% with 8 wins (40%), 19 cases at 80% all lost: only the first band counts.
var estimates = Enumerable.Range(0, 20).Select(i => Of(i < 8, 0.42)).Concat(Enumerable.Range(0, 19).Select(_ => Of(false, 0.8))).ToList();
var scores = Judge.Score(estimates, Capital);
Assert.AreEqual(0.02, scores.CalibrationError!.Value, 1e-9);
Assert.HasCount(2, scores.Bands);
Assert.IsNull(Judge.Score([.. estimates.Take(19)], Capital).CalibrationError);
}
/// <summary>The interval contains the truth and knows that neighbours are not independent.</summary>
[TestMethod]
public void TheIntervalKeepsNeighboursTogether()
{
var gen = new Gen(3);
var alone = Enumerable.Range(0, 400).Select(_ => gen.Normal() + 0.05).ToList();
var ones = alone.Select(_ => 1.0).ToList();
var (low, high) = Judge.Interval(alone, ones, 0.95);
Assert.IsTrue(low < 0.05 && high > 0.05 && high - low is > 0.1 and < 0.3, $"{low} {high}");
var twins = alone.SelectMany(v => Enumerable.Repeat(v, 10)).Take(400).ToList();
var (from, to) = Judge.Interval(twins, ones, 0.95);
Assert.IsGreaterThan(1.8 * (high - low), to - from);
}
// ---- Multiplier -------------------------------------------------------------------------------------------------
/// <summary>Criterion of the phase: whatever the numbers and the thresholds, the multiplier is between 0 and 1.</summary>
[TestMethod]
public void TheMultiplierNeverExceedsOne()
{
double[] odd = [double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1, 0, 1, 2, 1e300, -1e300];
Property.ForAll(
gen => (P: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(), B: gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double(),
Rule: new MultiplierRule(gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.2, gen.Int(0, 20) == 0 ? gen.Pick(odd) : gen.Double() * 0.4)),
x =>
{
var m = x.Rule.Of(x.P, x.B);
Assert.IsTrue(m is >= 0 and <= 1, $"{m}");
Assert.IsGreaterThanOrEqualTo(x.Rule.Of(x.P - 0.01, x.B) - 1e-4, m, "a better estimate never shrinks more");
}, 5000);
Assert.AreEqual(1, MultiplierRule.Standard.Of(0.42, 0.42));
Assert.AreEqual(1, MultiplierRule.Standard.Of(0.9, 0.42));
Assert.AreEqual(0.5, MultiplierRule.Standard.Of(0.37, 0.42), 1e-4);
Assert.AreEqual(0, MultiplierRule.Standard.Of(0.32, 0.42));
Assert.AreEqual(0, MultiplierRule.Standard.Of(0.01, 0.42));
}
// ---- Training ---------------------------------------------------------------------------------------------------
internal static TrainingInput Input(IReadOnlyList<Example> cases) => new(cases)
{
BaseRates = Trainer.SharesOf(cases),
Capital = Capital,
Funded = new HashSet<string> { StrategyNames.CryptoTrend },
};
/// <summary>With something to learn the model earns on examples it had not studied, and it says what it looks at.</summary>
[TestMethod]
public void TrainingFindsTheClueThatCounts()
{
var cases = Cases(500, x => x[0] > 0.5 ? 0.75 : 0.25);
var result = Trainer.Train(Input(cases))!;
Assert.IsNotNull(result);
var chosen = result.Report.Chosen!;
Assert.IsGreaterThan(0.2, chosen.Combined.Improvement);
Assert.IsGreaterThan(0.2, chosen.Forward.Improvement);
Assert.IsLessThan(chosen.Combined.BaseLogLoss - 0.05, chosen.Combined.LogLoss);
Assert.IsGreaterThan(0.65, chosen.Combined.Precision!.Value);
Assert.AreEqual("Forza della tendenza", result.Report.Weights[0].Group);
Assert.IsGreaterThan(80m, result.Report.Weights[0].Share);
Assert.AreEqual(100m, result.Report.Weights.Sum(w => w.Share));
// Every attempt is in the report, with the same number of verified cases.
CollectionAssert.AreEquivalent(LearnerNames.All.ToArray(), result.Report.Attempts.Select(a => a.Learner).ToArray());
Assert.HasCount(1, result.Report.Attempts.Where(a => a.Chosen));
Assert.HasCount(1, result.Report.Attempts.Select(a => a.Combined.Cases).Distinct());
Assert.IsFalse(result.Report.AllStrategiesCounted);
}
/// <summary>With nothing to learn it answers about the base rate: it does not invent a gain nor lose much.</summary>
[TestMethod]
public void WithNothingToLearnItChangesLittle()
{
var result = Trainer.Train(Input(Cases(500, _ => 0.42)))!;
var chosen = result.Report.Chosen!;
Assert.AreEqual(chosen.Combined.BaseLogLoss, chosen.Combined.LogLoss, 0.02);
Assert.AreEqual(0.5, chosen.Combined.Precision!.Value, 0.07);
foreach (var example in Cases(100, _ => 0.42, 77))
{
Assert.AreEqual(0.42, result.Model.Probability(example.Features), 0.12);
}
}
[TestMethod]
public void TooFewExamplesOrOneOutcomeTrainNothing()
{
Assert.IsNull(Trainer.Train(Input(Cases(99, _ => 0.5))));
Assert.IsNull(Trainer.Train(Input(Cases(300, _ => 2))));
var open = Cases(300, _ => 0.5).Select((c, i) => i < 99 ? c : c with { Label = i % 2 == 0 ? null : new CaseLabel(null, null, null, c.Day, CaseOutcomes.NeverStarted) }).ToList();
Assert.IsNull(Trainer.Train(Input(open)), "an example without outcome never trains");
}
/// <summary>SPEC 11.2: a clue without history waits for 200 live examples that contain it.</summary>
[TestMethod]
public void AClueWithoutHistoryWaitsForTwoHundredLiveExamples()
{
var history = Cases(300, _ => 0.5);
IReadOnlyList<Example> With(int live, string source) =>
[
.. history, .. Cases(live, _ => 0.5, 8, source: source).Select((c, i) => c with { Features = new Dictionary<string, double>(c.Features) { [Clues.FearGreed] = i } }),
];
Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(199, CaseSources.Live)));
Assert.Contains(Clues.FearGreed, Trainer.CluesOf(With(200, CaseSources.Live)));
Assert.DoesNotContain(Clues.FearGreed, Trainer.CluesOf(With(400, CaseSources.History)));
Assert.DoesNotContain(Clues.Breadth, Trainer.CluesOf(history), "never seen");
}
// ---- The first model ----------------------------------------------------------------------------------------------
/// <summary>
/// The file in the program is whole: its base rates are the shares of its examples, its report counts them, and
/// training again on them gives the same estimates (to the sixth digit: the platforms differ in the last ones).
/// </summary>
[TestMethod]
public void TheFirstModelIsTheOneOfItsExamples()
{
var file = FirstModel.Embedded!;
Assert.IsNotNull(file);
var labelled = file.Examples.Where(e => e.IsLabelled).ToList();
Assert.IsGreaterThan(1000, labelled.Count);
Assert.AreEqual(labelled.Count, file.Report!.Examples);
foreach (var (strategy, rate) in Trainer.SharesOf(file.Examples))
{
Assert.AreEqual(rate, file.BaseRates[strategy], 1e-12);
}
Assert.IsTrue(file.Examples.All(e => e.Source == CaseSources.History && e.Day <= file.Through && (e.Label?.ClosedDay is not { } closed || closed <= file.Through)));
Assert.HasCount(3, file.Report.Attempts);
var again = Trainer.Fit(file.Model!.Learned.Learner, [.. labelled.OrderBy(e => e.Day).ThenBy(e => e.Strategy, StringComparer.Ordinal).ThenBy(e => e.Symbol, StringComparer.Ordinal)], file.Model.Clues, 11);
foreach (var e in labelled)
{
Assert.AreEqual(file.Model.Probability(e.Features), again.Probability(e.Features), 1e-6);
}
Assert.Contains("parte in osservazione", FirstModel.Markdown(file, "x"));
}
/// <summary>At the first start the examples and the model are there, once; a new file replaces the examples and not the model.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstModelTakesChargeAtTheFirstStart()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var none = CancellationToken.None;
var file = FirstModel.Train(Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), none);
var desk = new LearningDesk(rig.Db, rig.Clock) { First = file };
await desk.PrepareHistoryAsync(none).ConfigureAwait(false);
await desk.PrepareHistoryAsync(none).ConfigureAwait(false);
Assert.AreEqual(300, await desk.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false));
var models = await desk.Models.AllAsync(none).ConfigureAwait(false);
Assert.HasCount(3, models, "the chosen one and the two attempts");
var champion = models.Single(m => m.Status == ModelStatuses.Champion);
Assert.AreEqual((1, 300), (champion.Version, champion.Examples));
Assert.IsTrue(models.Where(m => m.Id != champion.Id).All(m => m is { Status: ModelStatuses.Tried, Version: null, Model: null } && m.Report.Attempts.Count == 1));
foreach (var e in file.Examples)
{
Assert.AreEqual(file.Model!.Probability(e.Features), champion.Model!.Probability(e.Features));
}
Assert.HasCount(1, await desk.Models.EventsAsync(none).ConfigureAwait(false));
var later = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), none) };
await later.PrepareHistoryAsync(none).ConfigureAwait(false);
Assert.AreEqual(320, await later.Store.CountAsync(CaseSources.History, none).ConfigureAwait(false));
Assert.AreEqual(champion.Id, (await later.Models.FindAsync(ModelStatuses.Champion, none).ConfigureAwait(false))!.Id);
Assert.HasCount(1, await later.Models.EventsAsync(none).ConfigureAwait(false));
}
/// <summary>The rule of the choice, fixed before the numbers.</summary>
[TestMethod]
public void TheChoiceFollowsTheRule()
{
static Attempt A(string learner, double gain, double loss) => new(learner, new Scores(), new Scores { GainWith = gain, LogLoss = loss }, false);
string Chosen(params Attempt[] attempts) => Trainer.Choose(attempts).Learner;
Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.66)));
Assert.AreEqual(LearnerNames.Forest, Chosen(A(LearnerNames.Boosting, 2, 0.70), A(LearnerNames.Logistic, 1, 0.65), A(LearnerNames.Forest, 3, 0.64)));
Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 1, 0.60), A(LearnerNames.Logistic, 2, 0.65), A(LearnerNames.Forest, 1, 0.5)));
Assert.AreEqual(LearnerNames.Logistic, Chosen(A(LearnerNames.Boosting, 0, 0.66), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.5)));
Assert.AreEqual(LearnerNames.Boosting, Chosen(A(LearnerNames.Boosting, 0, 0.65), A(LearnerNames.Logistic, 0, 0.65), A(LearnerNames.Forest, 0, 0.65)));
}
}