Fix the review findings of the basket engine, command and report

The independent review of Phase 14 found rules the engine applied
differently from the decisions, numbers the report labelled wrongly and
a command that left a trial "running" when interrupted.

Engine:
- The pause after the 9% account stop is read at the decision moment
  (the bar's close), like every other gate: on daily bars it no longer
  blocks one day past the server date change.
- In a one-pair basket, a level closed by the venue's mandatory stop
  closes the other levels at the next execution with their own reason,
  closed_with_stop (counted and labelled in the report); the basket's
  exit stays mandatory_stop, and a two-leg basket keeps orphan_leg.
- The cap of two entries per currency applies to new baskets only,
  never to the averagings of an open basket, and every leg is valued
  at the current mid: a Prudente long basket "come dal vivo" now makes
  its three averagings and Fedele writes no note on them.
- The surrogate of the control chains on the mid when the source has
  an ask, so each mid change keeps its size and the spread stays
  around the mid instead of moving the mid by a spread at each change
  of sign.
- The financing already charged on positions still open at the end is
  part of the run's fees (BacktestRun.AccruedFees, zero for the daily
  engine, kept in stored unit outcomes).

Report: the fee row says what it holds (commission and financing, the
spread is in the prices) and the cost-stress text matches what the
multiplier scales; baskets still open at the end are labelled as such
and left out of the share closed at the target; refusal labels say
what the engine checks; the ECB-price and cost limitations are no
longer printed twice; every count has the Italian thousands separator.

Command: Ctrl+C or SIGTERM cancels the run; the trial is recorded as
failed with "Prova interrotta prima della fine: rilancia «anubis
backtest baskets»." and the command exits 1; a trial that cannot start
is failed instead of thrown, and an unexpected error ends with an
Italian line, never a stack trace. The laboratory fails a leftover
basket trial with an accurate message instead of "Strategia non più
disponibile".

The Table 6.5 test comment no longer claims each price is the only one
that fits the row. The real report is regenerated on the same data and
database as the first run, which now counts as a prior trial.

refs #127 #129 #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 19:26:24 +01:00
1 parent 3bee136c74
commit a8defde572
15 files changed
+488 -143

No files matched your search

+18 -19
View File
@@ -1,6 +1,6 @@
# Backtest di `basket_reversion` (Rientro tra strumenti)
**Esito: non superato.** La prova «come dal vivo» non supera: risultato netto con costi doppi −1.580,16 USD, serve > 0,00 USD; deflated sharpe ratio 0,25, serve ≥ 0,9.
**Esito: non superato.** La prova «come dal vivo» non supera: risultato netto con costi doppi −1.580,16 USD, serve > 0,00 USD; deflated sharpe ratio 0,17, serve ≥ 0,9.
Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).
@@ -114,11 +114,11 @@ Una quota alta vuol dire che il risultato osservato è uno dei tanti che il caso
Le 28 coppie della BCE dal 1999: generazione A (i cinque spread a due gambe) e B (i dieci cambi da soli), segnale sui logaritmi, misure in σ, uscita sulla media degli ingressi. Modo «come dal vivo»: le regole del documento più i limiti del bot (SPEC 9.2) e quelli del margine; solo questo modo dà un giudizio (ADR 0026).
Dal 04/01/1999 al 30/11/2026, 7.147 punti di patrimonio giornalieri, capitale iniziale 20.000,00 USD. Costi di eToro del 02/12/2026. Impronta del piano `cb442c4b2b0a`, dei dati `babb6d7ba38f`. Varianti della griglia: 4; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: 4.
Dal 04/01/1999 al 30/11/2026, 7.147 punti di patrimonio giornalieri, capitale iniziale 20.000,00 USD. Costi di eToro del 02/12/2026. Impronta del piano `19fe8ff9386c`, dei dati `babb6d7ba38f`. Varianti della griglia: 4; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: 8.
| Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
|---|---:|---:|---:|---:|---:|---|
| `averagings=3;distance=10;entry_z=2;exit=2;generation=2;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | 0,1% | −12,0% | −1.580,16 USD | 0,25 | 0,15 | non superata |
| `averagings=3;distance=10;entry_z=2;exit=2;generation=2;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | 0,1% | −12,0% | −1.580,16 USD | 0,17 | 0,15 | non superata |
Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni né perdite.
@@ -130,9 +130,9 @@ Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni
| Volatilità annua | 1,8% | 0,0% |
| Calo massimo | −12,0% | 0,0% |
| Sharpe annuo | 0,06 | 0,00 |
| Costi pagati | 1.706,51 USD | 0,00 USD |
| Commissioni e finanziamento pagati (il differenziale è già nei prezzi) | 1.716,72 USD | 0,00 USD |
**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)
**Sensibilità ai costi** (differenziale, commissioni e finanziamento a carico moltiplicati insieme; gli accrediti di finanziamento restano uguali)
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo |
|---|---:|---:|---:|---:|
@@ -144,16 +144,16 @@ Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni
- Finestre che avanzano (4, con 72 giorni di stacco): rendimento fuori campione −4,4%, Sharpe annuo −0,10.
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,06, peggiore 0,06, percorsi positivi 100,0%.
- Deflated Sharpe Ratio 0,25, contando 4 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,15, su 12870 combinazioni di 4 varianti.
- Sguardo in avanti: 4817 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
- Deflated Sharpe Ratio 0,17, contando 8 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,15, su 12.870 combinazioni di 4 varianti.
- Sguardo in avanti: 4.817 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
**Soglie**
| Controllo | Valore | Soglia | Esito |
|---|---:|---:|---|
| Risultato netto con costi doppi | −1.580,16 USD | > 0,00 USD | **non superato** |
| Deflated Sharpe Ratio | 0,25 | ≥ 0,9 | **non superato** |
| Deflated Sharpe Ratio | 0,17 | ≥ 0,9 | **non superato** |
| Probabilità di sovra-adattamento (PBO) | 0,15 | ≤ 0,4 | superato |
| Calo massimo | 12,0% | ≤ 25% | superato |
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
@@ -175,14 +175,15 @@ Panieri della variante giudicata: 266.
|---|---:|
| obiettivo raggiunto | 242 |
| stop obbligatorio della piattaforma | 22 |
| fine del periodo | 2 |
| ancora aperto alla fine (valutato agli ultimi prezzi) | 2 |
Chiusi all'obiettivo: 91,0% dei panieri chiusi. La quota è mostrata e mai giudicata.
Chiusi all'obiettivo: 91,7% dei panieri chiusi. La quota è mostrata e mai giudicata.
- Gambe rimaste sole: 0 (una gamba chiusa da uno stop obbligatorio chiude il resto del paniere all'esecuzione successiva).
- Gambe rimaste sole: 0 (in un paniere di due coppie, una gamba chiusa da uno stop obbligatorio chiude l'altra all'esecuzione successiva).
- Chiusure d'ufficio per margine insufficiente: 0.
- Stop sul valore del conto: 0.
- Posizioni chiuse dallo stop obbligatorio della piattaforma: 22.
- Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 20 (in un paniere di una coppia gli altri livelli si chiudono all'esecuzione successiva: senza quel livello la scala delle mediazioni non regge più).
**Ingressi e mediazioni fermati o annotati**
@@ -190,11 +191,11 @@ Con il profilo Fedele la regola dei tre costi e il limite di esposizione per val
| Motivo | Volte |
|---|---:|
| già aperto il numero massimo di panieri | 1569 |
| esposizione su una valuta oltre il limite | 114 |
| perdita aperta oltre il 2%: nessun paniere nuovo | 31 |
| volatilità recente oltre il doppio del normale | 14 |
| dimensione dimezzata (perdita della settimana o calo dal massimo) | 11 |
| già aperto il numero massimo di panieri | 1.569 |
| esposizione netta su una valuta oltre due ingressi (solo panieri nuovi) | 73 |
| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 31 |
| volatilità recente oltre il doppio del normale, o non ancora nota | 14 |
| dimensione ridotta a metà o a un quarto (perdita della settimana o calo dal massimo) | 11 |
| livello sotto il minimo della piattaforma | 6 |
## Cosa il backtest non rappresenta
@@ -208,6 +209,4 @@ Con il profilo Fedele la regola dei tre costi e il limite di esposizione per val
- Nessuna notizia e nessun calendario economico: il filtro delle notizie è spento.
- Il confronto è con zero, cioè il capitale fermo, non con comprare e tenere.
- Sharpe e volatilità sono calcolati senza tasso privo di rischio.
- I prezzi sono i cambi di riferimento della BCE, uno al giorno: non si può negoziare a quei prezzi, e dentro la giornata il prezzo tocca livelli che i cambi non mostrano, stop compresi.
- I costi sono quelli di eToro letti il 02/12/2026: differenziali, commissioni e finanziamenti cambiano nel tempo.
- Mancano ancora i dati a 15 minuti: il giudizio che conta richiede i file a 1 minuto forniti dall'utente.
+86 -39
View File
@@ -1,5 +1,6 @@
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Brokers;
@@ -22,7 +23,7 @@ internal static class BasketCommand
private const string Progress = "costi doppi e tripli, comprare e tenere";
public static async Task<int> RunAsync(string[] args, TextWriter output, IReadOnlyDictionary<string, string?>? environment = null,
HttpMessageHandler? handler = null, IClock? clock = null)
HttpMessageHandler? handler = null, IClock? clock = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(output);
@@ -82,14 +83,23 @@ internal static class BasketCommand
return 1;
}
// Ctrl+C, or the stop of the container (SIGTERM), cancels the run: the trial is closed as failed with a reason the user
// can act on, instead of staying «running» for the laboratory to find at the next start.
using var interrupted = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Interrupt);
using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Interrupt);
var token = interrupted.Token;
TrialStore? trials = null;
Guid? owned = null; // The trial this command planned and has not closed yet.
Database? db = null; // Disposed in finally: a failure closes the trial on it first.
try
{
Redactor.Register(config.Db!.Password);
await using var db = Database.Open(config.Db!, allowCreate: false);
db = Database.Open(config.Db!, allowCreate: false);
config.Data.Ensure();
Directory.CreateDirectory(outDir);
var rates = await RatesAsync(config.Data.Research, offline, handler, clock, output).ConfigureAwait(false);
var rates = await RatesAsync(config.Data.Research, offline, handler, clock, output, token).ConfigureAwait(false);
var crosses = EcbCrosses.Build(rates);
var notes = BasketProtocol.Notes(crosses);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
@@ -97,11 +107,13 @@ internal static class BasketCommand
var series = StylisedReplica.EcbSeries(crosses, BasketProtocol.ReplicaThrough);
var replica = BasketProtocol.Replica(series);
token.ThrowIfCancellationRequested();
var binding = replica.Where(r => r.Case.Binding).ToList();
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Replica dell'appendice G fino al {Earlier(notes.Last, BasketProtocol.ReplicaThrough):yyyy-MM-dd}: {binding.Count(r => r.Case.Passes(r.Result.Total))} su {binding.Count} righe vincolanti dentro la tolleranza.")).ConfigureAwait(false);
var control = BasketProtocol.Control(series, repetitions, seed);
token.ThrowIfCancellationRequested();
var it = CultureInfo.GetCultureInfo("it-IT");
await output.WriteLineAsync(string.Create(it,
$"Controllo contro il caso: {repetitions} ripetizioni, seme {seed.ToString(CultureInfo.InvariantCulture)}. Pari o migliori: {string.Join("; ", control.Select(r => $"{r.Case.Label} {r.Case.StopLabel} {r.Control.Share * 100:0.0}% (documento {r.DocumentShare * 100:0}%)"))}."))
@@ -109,14 +121,15 @@ internal static class BasketCommand
var (plan, variants) = BasketProtocol.Plan(to, now);
var data = BasketProtocol.Dataset(crosses, to);
var trials = new TrialStore(db, clock);
var planned = await trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
if (!await trials.StartAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))
trials = new TrialStore(db, clock);
var planned = await trials.PlanAsync(plan, variants, token).ConfigureAwait(false);
owned = planned.Id;
if (!await trials.StartAsync(planned.Id, token).ConfigureAwait(false))
{
throw new InvalidOperationException("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.");
return await RefuseAsync("La prova appena pianificata non si può avviare: un'altra la sta già eseguendo.").ConfigureAwait(false);
}
var trial = (await trials.GetAsync(planned.Id, CancellationToken.None).ConfigureAwait(false))!;
var trial = (await trials.GetAsync(planned.Id, token).ConfigureAwait(false))!;
var refusal = !trial.PlanIntact
? "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."
: trial.PlanHash != TrialPlan.Hash(plan.ToJson())
@@ -124,59 +137,93 @@ internal static class BasketCommand
: null;
if (refusal is not null)
{
await trials.FailAsync(trial.Id, refusal, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync("Non riuscito: " + refusal).ConfigureAwait(false);
return 1;
return await RefuseAsync(refusal).ConfigureAwait(false);
}
BacktestReport report;
try
{
var prior = await trials.PriorAsync(trial.Strategy, trial.Id, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Prova {trial.Id} pianificata con il piano {trial.PlanHash[..12]}: {variants} varianti dal {plan.Data.From:yyyy-MM-dd} al {plan.Data.To:yyyy-MM-dd}, prove precedenti contate: {prior.Trials}."))
.ConfigureAwait(false);
var engine = new BasketTrialEngine(trial.Plan, BasketReversionFamily.Instance, data);
var watch = System.Diagnostics.Stopwatch.StartNew();
var (judged, summary) = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, BasketReversionFamily.Instance, engine, prior, now,
text => output.WriteLine("Prova: " + (text == Progress ? "costi doppi e tripli, confronto con zero" : text)));
await trials.FinishAsync(trial.Id, judged.DataFingerprint, summary, judged.ToJson(), judged.Passed, CancellationToken.None).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Prova calcolata in {watch.Elapsed.TotalSeconds:0} secondi.")).ConfigureAwait(false);
report = judged;
}
catch (Exception ex)
{
// A trial left running would be picked up by the laboratory at the next start: it is closed as failed.
await trials.FailAsync(trial.Id, Redactor.Redact(ex.Message), CancellationToken.None).ConfigureAwait(false);
throw;
}
var prior = await trials.PriorAsync(trial.Strategy, trial.Id, token).ConfigureAwait(false);
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture,
$"Prova {trial.Id} pianificata con il piano {trial.PlanHash[..12]}: {variants} varianti dal {plan.Data.From:yyyy-MM-dd} al {plan.Data.To:yyyy-MM-dd}, prove precedenti contate: {prior.Trials}."))
.ConfigureAwait(false);
var engine = new BasketTrialEngine(trial.Plan, BasketReversionFamily.Instance, data);
var watch = System.Diagnostics.Stopwatch.StartNew();
var (report, summary) = TrialRunner.Run(trial.Id, trial.Plan, trial.PlanHash, BasketReversionFamily.Instance, engine, prior, now,
text => output.WriteLine("Prova: " + (text == Progress ? "costi doppi e tripli, confronto con zero" : text)), token);
// Judged: the trial is recorded whatever comes now, an interruption included.
await trials.FinishAsync(trial.Id, report.DataFingerprint, summary, report.ToJson(), report.Passed, CancellationToken.None).ConfigureAwait(false);
owned = null;
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Prova calcolata in {watch.Elapsed.TotalSeconds:0} secondi.")).ConfigureAwait(false);
var section = new BasketTrialSection(BasketProtocol.TrialName, trial.Plan, trial.PlanHash, report, trial.Plan.Mode ?? BasketModes.AsLive);
var command = "anubis backtest baskets --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
+ (repetitions == BasketProtocol.ControlRepetitions ? "" : " --control " + repetitions.ToString(CultureInfo.InvariantCulture))
+ (seed == BasketProtocol.ControlSeed ? "" : " --seed " + seed.ToString(CultureInfo.InvariantCulture));
var file = Path.Combine(outDir, BasketReport.Strategy + ".md");
await File.WriteAllTextAsync(file, BasketReport.Markdown(new BasketReportInput(command, now, notes, trial.Plan.Costs ?? VenueCosts.Etoro, replica, control, section, null)))
await File.WriteAllTextAsync(file, BasketReport.Markdown(new BasketReportInput(command, now, notes, trial.Plan.Costs ?? VenueCosts.Etoro, replica, control, section, null)), CancellationToken.None)
.ConfigureAwait(false);
await output.WriteLineAsync((report.Passed ? "Esito: superato. " : "Esito: non superato. ") + BasketReport.Verdict(section)).ConfigureAwait(false);
await output.WriteLineAsync("Rapporto scritto in " + file).ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
or ArgumentException or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException or System.Text.Json.JsonException
or SchemaException or System.Data.Common.DbException)
catch (OperationCanceledException) when (interrupted.IsCancellationRequested)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return await RefuseAsync(owned is null ? "interrotto prima che la prova fosse pianificata: nessuna prova registrata." : Interrupted).ConfigureAwait(false);
}
catch (Exception ex)
{
// Any failure, expected or not, ends with an Italian line and exit 1, never a stack trace; the trial it leaves is closed.
var message = ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
or ArgumentException or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException or System.Text.Json.JsonException
or SchemaException or System.Data.Common.DbException
? Redactor.Redact(ex.Message)
: $"errore inatteso ({ex.GetType().Name}): {Redactor.Redact(ex.Message)}";
return await RefuseAsync(message).ConfigureAwait(false);
}
finally
{
if (db is not null)
{
await db.DisposeAsync().ConfigureAwait(false);
}
}
// Closes the trial this command still holds, if any, with the reason, and says it: exit 1.
async Task<int> RefuseAsync(string reason)
{
if (trials is not null && owned is { } id)
{
owned = null;
try
{
await trials.FailAsync(id, reason, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or InvalidOperationException or TimeoutException)
{
await output.WriteLineAsync("La prova non si è potuta segnare come non riuscita: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
}
}
await output.WriteLineAsync("Non riuscito: " + reason).ConfigureAwait(false);
return 1;
}
void Interrupt(PosixSignalContext context)
{
context.Cancel = true;
interrupted.Cancel();
}
}
/// <summary>What an interrupted trial says, in the register and on the console.</summary>
internal const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
/// <summary>
/// The ECB rates of the seven currencies from the zip shared with <c>anubis data ecb</c>: downloaded again on every run;
/// with <paramref name="offline"/> only the copy already in the research folder, and an error when there is none.
/// </summary>
private static async Task<IReadOnlyList<FxRate>> RatesAsync(string research, bool offline, HttpMessageHandler? handler, IClock clock, TextWriter output)
private static async Task<IReadOnlyList<FxRate>> RatesAsync(string research, bool offline, HttpMessageHandler? handler, IClock clock, TextWriter output, CancellationToken cancellationToken)
{
if (offline && !File.Exists(Ecb.HistoryPath(research)))
{
@@ -186,7 +233,7 @@ internal static class BasketCommand
using var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
http.Timeout = TimeSpan.FromMinutes(5);
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
var rates = await Ecb.LoadHistoryAsync(new ApiHttp(http, clock, Ecb.Source), research, offline, EcbCrosses.Rates, CancellationToken.None).ConfigureAwait(false);
var rates = await Ecb.LoadHistoryAsync(new ApiHttp(http, clock, Ecb.Source), research, offline, EcbCrosses.Rates, cancellationToken).ConfigureAwait(false);
if (rates.Count == 0)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
+6
View File
@@ -24,6 +24,12 @@ public static class BasketReasons
/// <summary>The leg left alone when the other leg's mandatory stop closed: it closes at the next execution.</summary>
public const string OrphanLeg = "orphan_leg";
/// <summary>
/// A level of a one-pair basket closed at the next execution because the mandatory stop closed another level: the
/// averaging ladder is broken, so the rest goes too. The basket's exit stays <see cref="MandatoryStop"/>.
/// </summary>
public const string ClosedWithStop = "closed_with_stop";
/// <summary>The venue closed everything: the equity fell below half the initial margin of the open positions.</summary>
public const string Liquidation = "liquidation";
+10 -7
View File
@@ -131,10 +131,12 @@ public sealed class BasketMarket
}
/// <summary>
/// The surrogate of the control against chance (<see cref="Surrogates"/>): every price of a bar is rebuilt from the close
/// before it with its log change turned by the sign of the bar's day (around the mean change of the series when
/// <paramref name="centred"/>). On a −1 day high and low swap, and so do bid and ask, so the ask stays above the bid. The
/// size of every change of the reference close is kept; all the pairs turn together, so the crosses stay consistent.
/// The surrogate of the control against chance (<see cref="Surrogates"/>): every price of a bar is rebuilt from the
/// reference close before it (<see cref="Reference"/>: the mid when the source gives the ask) with its log change turned by
/// the sign of the bar's day (around the mean change of the series when <paramref name="centred"/>). On a −1 day high and
/// low swap, and so do bid and ask, so the ask stays above the bid and the spread around the mid. The size of every change
/// of the reference close is kept (with bid and ask, to the square of the relative spread, about 1e-8); all the pairs turn
/// together, so the crosses stay consistent.
/// </summary>
public BasketMarket Surrogate(DaySigns signs, bool centred)
{
@@ -143,7 +145,7 @@ public sealed class BasketMarket
var asks = new Dictionary<string, PriceColumns>(StringComparer.Ordinal);
foreach (var symbol in Symbols)
{
var (bid, ask) = Flip(Bid(symbol), Ask(symbol), signs, centred);
var (bid, ask) = Flip(Bid(symbol), Ask(symbol), Reference(symbol), signs, centred);
bids[symbol] = bid;
if (ask is not null)
{
@@ -163,10 +165,11 @@ public sealed class BasketMarket
? DateOnly.FromDateTime(opensAt.UtcDateTime)
: ServerClock.Day(opensAt + Length - TimeSpan.FromTicks(1));
private (PriceColumns Bid, PriceColumns? Ask) Flip(PriceColumns bid, PriceColumns? ask, DaySigns signs, bool centred)
// The chain follows the price the engine reads, the mid when there is an ask: chained on the bid, a −1 day would turn the
// ask into the chained level and the mid would jump by a whole spread at every change of sign.
private (PriceColumns Bid, PriceColumns? Ask) Flip(PriceColumns bid, PriceColumns? ask, IReadOnlyList<double> reference, DaySigns signs, bool centred)
{
var n = _clock.Length;
var reference = bid.Close;
var mean = 0d;
if (centred)
{
+53 -48
View File
@@ -84,25 +84,25 @@ public static class BasketReport
(BasketReasons.MandatoryStop, "stop obbligatorio della piattaforma"),
(OrphanLeg, "gamba rimasta sola dopo uno stop obbligatorio"),
(Liquidation, "chiusura d'ufficio per margine insufficiente"),
(BasketReasons.End, "fine del periodo"),
(BasketReasons.End, "ancora aperto alla fine (valutato agli ultimi prezzi)"),
];
/// <summary>Why the engine did not open or add, with their Italian labels.</summary>
/// <summary>Why the engine did not open or add, with their Italian labels: what the engine checks (BasketSimulation).</summary>
private static readonly Dictionary<string, string> Refusals = new(StringComparer.Ordinal)
{
[BasketReasons.GateOpenLoss] = "perdita aperta oltre il 2%: nessun paniere nuovo",
[BasketReasons.PausedUntilNextDay] = "fermo dopo lo stop del 9% fino al cambio di data del server",
[BasketReasons.DailyLossBlock] = "perdita del giorno oltre il 2%: niente ingressi né mediazioni per 24 ore",
[BasketReasons.HalfSize] = "dimensione dimezzata (perdita della settimana o calo dal massimo)",
[BasketReasons.GateOpenLoss] = "perdita aperta pari o oltre il 2%: nessun paniere nuovo",
[BasketReasons.PausedUntilNextDay] = "niente ingressi né mediazioni dopo lo stop del 9%, fino al cambio di data del server",
[BasketReasons.DailyLossBlock] = "perdita del giorno pari o oltre il 2%: niente ingressi né mediazioni per 24 ore",
[BasketReasons.HalfSize] = "dimensione ridotta a metà o a un quarto (perdita della settimana o calo dal massimo)",
[BasketReasons.BelowVenueMinimum] = "livello sotto il minimo della piattaforma",
[BasketReasons.MarginLimit] = "margine impegnato oltre il 40%",
[BasketReasons.PositionLimit] = "troppe posizioni aperte per la piattaforma",
[BasketReasons.MarginLimit] = "margine impegnato oltre il 40% del patrimonio",
[BasketReasons.PositionLimit] = "si supererebbero 9 posizioni aperte (conto Demo condiviso)",
[BasketReasons.OppositePosition] = "posizione opposta sullo stesso strumento",
[BasketReasons.CurrencyExposure] = "esposizione su una valuta oltre il limite",
[BasketReasons.CurrencyExposure] = "esposizione netta su una valuta oltre due ingressi (solo panieri nuovi)",
[BasketReasons.CostRule] = "obiettivo sotto tre volte il costo del paniere",
[BasketReasons.RvolFilter] = "volatilità recente oltre il doppio del normale",
[BasketReasons.CorrelationLow] = "correlazione sotto 0,6",
[BasketReasons.SwitchTripped] = "interruttore scattato (calo del 15%)",
[BasketReasons.RvolFilter] = "volatilità recente oltre il doppio del normale, o non ancora nota",
[BasketReasons.CorrelationLow] = "correlazione tra le gambe sotto 0,6 sul segno atteso, o non ancora nota",
[BasketReasons.SwitchTripped] = "interruttore scattato (calo del 15% dal massimo)",
[BasketReasons.MaxOpenBaskets] = "già aperto il numero massimo di panieri",
[BasketReasons.ClockWindow] = "fuori dalla finestra oraria",
};
@@ -179,7 +179,7 @@ public static class BasketReport
var d = input.Data;
var c = input.Costs;
b.AppendLine("## Dati").AppendLine();
b.AppendLine(Text($"- Cambi di riferimento della BCE: {EcbCrosses.Rates.Count} valute contro l'euro ({string.Join(", ", EcbCrosses.Rates)}), da cui {d.Pairs} coppie incrociate. Fonte: {d.Source}."));
b.AppendLine(Text($"- Cambi di riferimento della BCE: {Count(EcbCrosses.Rates.Count)} valute contro l'euro ({string.Join(", ", EcbCrosses.Rates)}), da cui {Count(d.Pairs)} coppie incrociate. Fonte: {d.Source}."));
b.AppendLine(Text($"- Periodo: dal {d.First:dd/MM/yyyy} al {d.Last:dd/MM/yyyy}, {d.Days.ToString("#,0", It)} giorni con il cambio. Impronta dei dati `{Short(d.Fingerprint)}`."));
b.AppendLine(d.Last < d.ReplicaThrough
? Text($"- La replica dell'appendice G usa i dati fino al {d.ReplicaThrough:dd/MM/yyyy}, la fine del documento; qui i dati finiscono prima, il {d.Last:dd/MM/yyyy}.")
@@ -190,7 +190,7 @@ public static class BasketReport
var estimated = c.Pairs.Where(p => p.FinancingEstimated).Select(p => p.Pair).ToList();
if (estimated.Count > 0)
{
b.AppendLine(Text($"- Il finanziamento notturno di {estimated.Count} coppie su {c.Pairs.Count} non è nel documento: per prudenza pagano, su entrambi i lati, il costo più alto tra quelli noti. Sono segnate come stimate nella tabella."));
b.AppendLine(Text($"- Il finanziamento notturno di {Count(estimated.Count)} coppie su {Count(c.Pairs.Count)} non è nel documento: per prudenza pagano, su entrambi i lati, il costo più alto tra quelli noti. Sono segnate come stimate nella tabella."));
}
b.AppendLine();
@@ -227,7 +227,7 @@ public static class BasketReport
var binding = input.Replica.Where(r => r.Case.Binding).ToList();
var inside = binding.Count(r => r.Case.Passes(r.Result.Total));
b.AppendLine();
b.AppendLine(Text($"{inside} righe vincolanti su {binding.Count} dentro la tolleranza. Una riga è vincolante quando il totale del documento supera 100 obiettivi in valore assoluto: allora il nostro deve avere lo stesso segno e restare entro il più grande tra 25 obiettivi e il 5% del totale del documento."));
b.AppendLine(Text($"{Count(inside)} righe vincolanti su {Count(binding.Count)} dentro la tolleranza. Una riga è vincolante quando il totale del documento supera 100 obiettivi in valore assoluto: allora il nostro deve avere lo stesso segno e restare entro il più grande tra 25 obiettivi e il 5% del totale del documento."));
var reported = input.Replica.Where(r => !r.Case.Binding).ToList();
if (reported.Count > 0)
{
@@ -266,7 +266,7 @@ public static class BasketReport
{
var replicas = row.Control.Replicas.Where(double.IsFinite).Order().ToArray();
var spread = replicas.Length == 0 ? "—" : Ratio(Rank(replicas, 0.05)) + "; " + Ratio(Rank(replicas, 0.95));
b.AppendLine(Text($"| {row.Case.Label} | {row.Case.StopLabel} | {row.Repetitions} | {row.Seed.ToString(CultureInfo.InvariantCulture)} | {Ratio(row.Control.Observed)} | {Ratio(Median(replicas))} | {spread} | {Share(row.Control.Share)} | {Pct(row.DocumentShare, 0)} |"));
b.AppendLine(Text($"| {row.Case.Label} | {row.Case.StopLabel} | {Count(row.Repetitions)} | {row.Seed.ToString(CultureInfo.InvariantCulture)} | {Ratio(row.Control.Observed)} | {Ratio(Median(replicas))} | {spread} | {Share(row.Control.Share)} | {Pct(row.DocumentShare, 0)} |"));
}
b.AppendLine();
@@ -283,7 +283,7 @@ public static class BasketReport
b.AppendLine("## Prova del motore a panieri").AppendLine();
b.AppendLine(Text($"{trial.Name}. Modo {ModeName(trial.Mode)}: le regole del documento più i limiti del bot (SPEC 9.2) e quelli del margine; solo questo modo dà un giudizio (ADR 0026)."))
.AppendLine();
b.AppendLine(Text($"Dal {m.From:dd/MM/yyyy} al {m.To:dd/MM/yyyy}, {r.Sessions.ToString("#,0", It)} punti di patrimonio giornalieri, capitale iniziale {Money(m.InitialCapital, r.Currency)}. Costi di {VenueName(costs.Venue)} del {costs.AsOf:dd/MM/yyyy}. Impronta del piano `{Short(trial.PlanHash)}`, dei dati `{Short(r.DataFingerprint)}`. Varianti della griglia: {r.Variants.Count}; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: {r.TrialsCounted}."))
b.AppendLine(Text($"Dal {m.From:dd/MM/yyyy} al {m.To:dd/MM/yyyy}, {Count(r.Sessions)} punti di patrimonio giornalieri, capitale iniziale {Money(m.InitialCapital, r.Currency)}. Costi di {VenueName(costs.Venue)} del {costs.AsOf:dd/MM/yyyy}. Impronta del piano `{Short(trial.PlanHash)}`, dei dati `{Short(r.DataFingerprint)}`. Varianti della griglia: {Count(r.Variants.Count)}; varianti contate nel Deflated Sharpe Ratio, prove precedenti comprese: {Count(r.TrialsCounted)}."))
.AppendLine();
b.AppendLine("| Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |");
@@ -302,10 +302,10 @@ public static class BasketReport
Row(b, "Volatilità annua", Pct(m.Volatility), Pct(h.Volatility));
Row(b, "Calo massimo", Pct(-m.MaxDrawdown), Pct(-h.MaxDrawdown));
Row(b, "Sharpe annuo", Num(m.Sharpe), Num(h.Sharpe));
Row(b, "Costi pagati", Money(m.Fees, r.Currency), Money(h.Fees, r.Currency));
Row(b, "Commissioni e finanziamento pagati (il differenziale è già nei prezzi)", Money(m.Fees, r.Currency), Money(h.Fees, r.Currency));
b.AppendLine();
b.AppendLine("**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)").AppendLine();
b.AppendLine("**Sensibilità ai costi** (differenziale, commissioni e finanziamento a carico moltiplicati insieme; gli accrediti di finanziamento restano uguali)").AppendLine();
b.AppendLine("| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo |").AppendLine("|---|---:|---:|---:|---:|");
foreach (var c in r.Costs)
{
@@ -316,19 +316,19 @@ public static class BasketReport
b.AppendLine("**Convalide**").AppendLine();
if (r.WalkForward is { } wf)
{
b.AppendLine(Text($"- Finestre che avanzano ({wf.Windows.Count}, con {wf.Purge} giorni di stacco): rendimento fuori campione {Pct(wf.Return)}, Sharpe annuo {Num(wf.Sharpe * annual)}."));
b.AppendLine(Text($"- Finestre che avanzano ({Count(wf.Windows.Count)}, con {Count(wf.Purge)} giorni di stacco): rendimento fuori campione {Pct(wf.Return)}, Sharpe annuo {Num(wf.Sharpe * annual)}."));
}
if (r.Combinatorial is { } cv)
{
b.AppendLine(Text($"- K-fold purgato combinatorio ({cv.Groups} gruppi, {cv.TestGroups} di prova, {cv.Splits} divisioni): Sharpe annuo medio dei percorsi {Num(cv.MeanSharpe * annual)}, peggiore {Num(cv.WorstSharpe * annual)}, percorsi positivi {Pct(cv.PositiveShare)}."));
b.AppendLine(Text($"- K-fold purgato combinatorio ({Count(cv.Groups)} gruppi, {Count(cv.TestGroups)} di prova, {Count(cv.Splits)} divisioni): Sharpe annuo medio dei percorsi {Num(cv.MeanSharpe * annual)}, peggiore {Num(cv.WorstSharpe * annual)}, percorsi positivi {Pct(cv.PositiveShare)}."));
}
b.AppendLine(Text($"- Deflated Sharpe Ratio {Num(r.DeflatedSharpe.Value)}, contando {r.TrialsCounted} varianti provate in tutto."));
b.AppendLine(Text($"- Deflated Sharpe Ratio {Num(r.DeflatedSharpe.Value)}, contando {Count(r.TrialsCounted)} varianti provate in tutto."));
b.AppendLine(r.Overfitting is { } pbo
? Text($"- Probabilità di sovra-adattamento (PBO) {Num(pbo.Probability)}, su {pbo.Combinations} combinazioni di {pbo.Variants} varianti.")
? Text($"- Probabilità di sovra-adattamento (PBO) {Num(pbo.Probability)}, su {Count(pbo.Combinations)} combinazioni di {Count(pbo.Variants)} varianti.")
: "- Probabilità di sovra-adattamento: non calcolabile con una sola variante.");
b.AppendLine(Text($"- Sguardo in avanti: {r.LookAhead.Decisions} decisioni rifatte tagliando i dati in {r.LookAhead.Cutoffs.Count} punti, {r.LookAhead.Changed} cambiate."));
b.AppendLine(Text($"- Sguardo in avanti: {Count(r.LookAhead.Decisions)} decisioni rifatte tagliando i dati in {Count(r.LookAhead.Cutoffs.Count)} punti, {Count(r.LookAhead.Changed)} cambiate."));
b.AppendLine();
b.AppendLine("**Soglie**").AppendLine();
@@ -355,33 +355,30 @@ public static class BasketReport
var baskets = r.Baskets ?? [];
b.AppendLine("**Panieri**").AppendLine();
b.AppendLine(baskets.Count >= TrialRunner.MaxTrades
? Text($"Panieri della variante giudicata: gli ultimi {baskets.Count} aperti (il rapporto ne tiene al più {TrialRunner.MaxTrades}).")
: Text($"Panieri della variante giudicata: {baskets.Count}."));
? Text($"Panieri della variante giudicata: gli ultimi {Count(baskets.Count)} aperti (il rapporto ne tiene al più {Count(TrialRunner.MaxTrades)}).")
: Text($"Panieri della variante giudicata: {Count(baskets.Count)}."));
b.AppendLine();
if (baskets.Count > 0)
{
b.AppendLine("| Uscita | Panieri |").AppendLine("|---|---:|");
var counts = baskets.GroupBy(x => x.ExitReason ?? "", StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);
var counts = baskets.GroupBy(Exit, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);
foreach (var (code, label) in Exits)
{
if (counts.TryGetValue(code, out var n))
{
b.AppendLine(Text($"| {label} | {n} |"));
b.AppendLine(Text($"| {label} | {Count(n)} |"));
}
}
foreach (var (code, n) in counts.Where(x => x.Key.Length > 0 && !Exits.Any(e => e.Code == x.Key)).OrderBy(x => x.Key, StringComparer.Ordinal))
foreach (var (code, n) in counts.Where(x => !Exits.Any(e => e.Code == x.Key)).OrderBy(x => x.Key, StringComparer.Ordinal))
{
b.AppendLine(Text($"| `{code}` | {n} |"));
}
if (counts.TryGetValue("", out var open))
{
b.AppendLine(Text($"| ancora aperto alla fine | {open} |"));
b.AppendLine(Text($"| `{code}` | {Count(n)} |"));
}
b.AppendLine();
var closed = baskets.Count(x => x.ExitReason is not null);
// A basket still open at the end of the data was not closed: it is left out of the share.
var closed = baskets.Count(x => Exit(x) != BasketReasons.End);
var atTarget = baskets.Count(x => x.ExitReason == BasketReasons.Target);
b.AppendLine(Text($"Chiusi all'obiettivo: {Share(closed == 0 ? double.NaN : (double)atTarget / closed)} dei panieri chiusi. La quota è mostrata e mai giudicata."))
.AppendLine();
@@ -389,13 +386,15 @@ public static class BasketReport
// The notes count every event of the whole run; the baskets list is capped, so it is only the fallback.
int Events(string code) => r.Notes.TryGetValue(code, out var n) ? n : baskets.Count(x => x.ExitReason == code);
b.AppendLine(Text($"- Gambe rimaste sole: {Events(OrphanLeg)} (una gamba chiusa da uno stop obbligatorio chiude il resto del paniere all'esecuzione successiva)."));
b.AppendLine(Text($"- Chiusure d'ufficio per margine insufficiente: {Events(Liquidation)}."));
b.AppendLine(Text($"- Stop sul valore del conto: {Events(AccountStop)}."));
b.AppendLine(Text($"- Posizioni chiuse dallo stop obbligatorio della piattaforma: {(r.Notes.TryGetValue(BasketReasons.MandatoryStop, out var stopped) ? stopped : 0)}."));
int Positions(string code) => r.Notes.TryGetValue(code, out var n) ? n : 0;
b.AppendLine(Text($"- Gambe rimaste sole: {Count(Events(OrphanLeg))} (in un paniere di due coppie, una gamba chiusa da uno stop obbligatorio chiude l'altra all'esecuzione successiva)."));
b.AppendLine(Text($"- Chiusure d'ufficio per margine insufficiente: {Count(Events(Liquidation))}."));
b.AppendLine(Text($"- Stop sul valore del conto: {Count(Events(AccountStop))}."));
b.AppendLine(Text($"- Posizioni chiuse dallo stop obbligatorio della piattaforma: {Count(Positions(BasketReasons.MandatoryStop))}."));
b.AppendLine(Text($"- Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: {Count(Positions(BasketReasons.ClosedWithStop))} (in un paniere di una coppia gli altri livelli si chiudono all'esecuzione successiva: senza quel livello la scala delle mediazioni non regge più)."));
b.AppendLine();
var refusals = r.Notes.Where(n => n.Key is not (OrphanLeg or Liquidation or AccountStop or BasketReasons.MandatoryStop)).ToList();
var refusals = r.Notes.Where(n => n.Key is not (OrphanLeg or Liquidation or AccountStop or BasketReasons.MandatoryStop or BasketReasons.ClosedWithStop)).ToList();
b.AppendLine("**Ingressi e mediazioni fermati o annotati**").AppendLine();
if (refusals.Count == 0)
{
@@ -408,7 +407,7 @@ public static class BasketReport
b.AppendLine("| Motivo | Volte |").AppendLine("|---|---:|");
foreach (var (code, n) in refusals.OrderByDescending(x => x.Value).ThenBy(x => x.Key, StringComparer.Ordinal))
{
b.AppendLine(Text($"| {(Refusals.TryGetValue(code, out var label) ? label : "`" + code + "`")} | {n} |"));
b.AppendLine(Text($"| {(Refusals.TryGetValue(code, out var label) ? label : "`" + code + "`")} | {Count(n)} |"));
}
b.AppendLine();
@@ -422,13 +421,13 @@ public static class BasketReport
b.Append("- ").AppendLine(line);
}
var c = input.Costs;
b.AppendLine("- I prezzi sono i cambi di riferimento della BCE, uno al giorno: non si può negoziare a quei prezzi, e dentro la giornata il prezzo tocca livelli che i cambi non mostrano, stop compresi.");
b.AppendLine(Text($"- I costi sono quelli di {VenueName(c.Venue)} letti il {c.AsOf:dd/MM/yyyy}: differenziali, commissioni e finanziamenti cambiano nel tempo."));
// The engine's own lines already say that the account is not read and how the estimated financing is taken.
// The engine's own lines already speak of the ECB prices, of the costs, of the account that is not read and of the
// estimated financing: the report writes its own version only when there is no trial.
if (input.Trial is null)
{
var c = input.Costs;
b.AppendLine("- I prezzi sono i cambi di riferimento della BCE, uno al giorno: non si può negoziare a quei prezzi, e dentro la giornata il prezzo tocca livelli che i cambi non mostrano, stop compresi.");
b.AppendLine(Text($"- I costi sono quelli di {VenueName(c.Venue)} letti il {c.AsOf:dd/MM/yyyy}: differenziali, commissioni e finanziamenti cambiano nel tempo."));
b.AppendLine("- Il bot non legge il conto reale: margine, leva e chiusure d'ufficio seguono le regole della tabella dei costi, non il conto vero.");
b.AppendLine("- Il finanziamento delle coppie segnate come stimate usa il costo più alto tra quelli noti, non quello vero.");
}
@@ -459,7 +458,7 @@ public static class BasketReport
{
"percent" => Pct(v),
"money" => Money((decimal)v, currency),
"count" => v.ToString("0", It),
"count" => v.ToString("N0", It),
_ => Num(v),
};
@@ -475,6 +474,12 @@ public static class BasketReport
private static void Row(StringBuilder b, string label, string strategy, string zero) =>
b.Append("| ").Append(label).Append(" | ").Append(strategy).Append(" | ").Append(zero).AppendLine(" |");
/// <summary>The exit of a basket of the report: «end» for one still open at the end (an older report may leave it null).</summary>
private static string Exit(ReportBasket basket) => basket.ExitReason ?? BasketReasons.End;
/// <summary>A count the Italian way: 1.569.</summary>
private static string Count(int value) => value.ToString("N0", It);
private static string Short(string fingerprint) => fingerprint.Length > 12 ? fingerprint[..12] : fingerprint;
private static string Minus(double value) => value < 0 ? "−" : "";
+32 -17
View File
@@ -139,7 +139,11 @@ internal sealed class BasketSimulation
}
}
/// <summary>A mandatory stop: the position closes; the rest of its basket closes at the next execution.</summary>
/// <summary>
/// A mandatory stop: the position closes; the rest of its basket closes at the next execution. In a two-leg basket the other
/// leg is an orphan (<see cref="BasketReasons.OrphanLeg"/>); in a one-pair basket the other levels close with the stopped
/// one (<see cref="BasketReasons.ClosedWithStop"/>): the averaging ladder is broken. The basket's exit is the mandatory stop.
/// </summary>
private void Stopped(Position position, int t, decimal price, DateTimeOffset at, Field field)
{
var basket = position.Basket;
@@ -167,7 +171,7 @@ internal sealed class BasketSimulation
_notes.Add(new BacktestNote(_market.Day(t), rest.First(p => p.Pair != position.Pair).Pair.Name, BasketReasons.OrphanLeg));
}
_pending.Add(new Pending(PendingKind.Close, basket, 0m, basket.Exit));
_pending.Add(new Pending(PendingKind.Close, basket, 0m, orphan ? BasketReasons.OrphanLeg : BasketReasons.ClosedWithStop));
}
// ----- the close -----
@@ -266,7 +270,8 @@ internal sealed class BasketSimulation
var blocked = _live && RiskMonitor.EntriesBlocked(_risk, at);
var multiplier = _live ? RiskMonitor.Multiplier(_risk, _measures, at, RiskLimits.Default) : 1m;
var openLoss = _cash > 0m ? (_cash - Marks(t, mid: InPause(at)).Equity) / _cash : 0m;
var paused = _pausedUntil is { } until && _market.Clock[t] < until;
// The pause after the account stop, like every other gate, is read at the decision moment: the bar's close.
var paused = _pausedUntil is { } until && at < until;
var plan = new Plan();
var closedNow = new HashSet<int>();
@@ -315,19 +320,13 @@ internal sealed class BasketSimulation
: blocked ? BasketReasons.DailyLossBlock
: null;
var units = Math.Min(basket.FirstUnits, Size(unit, t, multiplier));
var exposed = false;
refusal ??= Limits(unit, basket.Direction, basket.Sign, units, t, equity, plan, out exposed);
refusal ??= Limits(unit, basket.Direction, basket.Sign, units, t, equity, plan, averaging: true, out _);
if (Refuse(unit, refusal, t, basket.Direction))
{
continue;
}
NoteHalf(unit, t, basket.Direction, multiplier);
if (exposed)
{
Note(unit, t, basket.Direction, BasketReasons.CurrencyExposure);
}
_events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Add, BasketEventKinds.Add, basket.Direction));
Place(new Pending(PendingKind.Add, basket, units, BasketEventKinds.Add), t, plan);
}
@@ -373,7 +372,7 @@ internal sealed class BasketSimulation
var units = Size(unit, t, multiplier);
var exposed = false;
refusal ??= Limits(unit, direction, sign, units, t, equity, plan, out exposed);
refusal ??= Limits(unit, direction, sign, units, t, equity, plan, averaging: false, out exposed);
if (Refuse(unit, refusal, t, direction))
{
continue;
@@ -447,10 +446,12 @@ internal sealed class BasketSimulation
/// <summary>
/// «Come dal vivo» only: a level below the venue minimum does not start; no position against one already held on the same
/// instrument; net exposure per currency at most two entries (Prudente refuses, Fedele notes: <paramref name="exposed"/>);
/// at most nine positions; the margin committed at most 40% of the equity. Null when the level may go.
/// instrument; for a new basket, net exposure per currency at most two entries (Prudente refuses, Fedele notes:
/// <paramref name="exposed"/>), never for an <paramref name="averaging"/> of a basket already open (plan, section 5: «il
/// candidato è scartato»; the research document, sections 4.9 and 4.10); at most nine positions; the margin committed at
/// most 40% of the equity. Null when the level may go.
/// </summary>
private string? Limits(Unit unit, int direction, int sign, decimal units, int t, decimal equity, Plan plan, out bool exposed)
private string? Limits(Unit unit, int direction, int sign, decimal units, int t, decimal equity, Plan plan, bool averaging, out bool exposed)
{
exposed = false;
if (!_live)
@@ -471,12 +472,14 @@ internal sealed class BasketSimulation
return BasketReasons.OppositePosition;
}
// Every leg, held, planned on this close or proposed, is valued at the current mid, the same price the entry it is
// compared with is valued at: the cap measures what the account would hold now, not what it paid.
var entry = exposures.Max();
var all = _positions.Where(p => p.Open).Select(p => new ExposureLeg(p.Pair, p.Side, p.Units, p.EntryPrice))
var all = _positions.Where(p => p.Open).Select(p => new ExposureLeg(p.Pair, p.Side, p.Units, CurrentMid(p.Pair, t)))
.Concat(plan.Legs)
.Concat(legs.Select(l => new ExposureLeg(l.Pair, l.Side, units, Mid(l.Pair, t, Field.Close))));
var cap = _rules.Profile.MaxCurrencyExposure ?? 2m;
if (BasketMath.Exposure(all).Any(e => Math.Abs(e.Value * UsdPer(e.Key, t, Field.Close)) > cap * entry))
if (!averaging && BasketMath.Exposure(all).Any(e => Math.Abs(e.Value * UsdPer(e.Key, t, Field.Close)) > cap * entry))
{
if (_rules.Profile.MaxCurrencyExposure is not null)
{
@@ -677,6 +680,10 @@ internal sealed class BasketSimulation
foreach (var position in open)
{
ClosePosition(position, t, Exit(position, Quote(position.Pair, t, field)), at, field, order.Reason);
if (order.Reason == BasketReasons.ClosedWithStop)
{
_notes.Add(new BacktestNote(_market.Day(t), position.Pair.Name, BasketReasons.ClosedWithStop));
}
}
Done(basket);
@@ -872,6 +879,9 @@ internal sealed class BasketSimulation
return new BidAsk(bid - half, bid + half);
}
/// <summary>The mid of a pair at the close of bar t, or at its last close before when it has no bar there.</summary>
private decimal CurrentMid(FxPair pair, int t) => Mid(pair, _market.Has(pair.Name, t) ? t : LastBar(pair.Name, t), Field.Close);
private decimal Mid(FxPair pair, int t, Field field)
{
var bid = (decimal)Value(_market.Bid(pair.Name), t, field);
@@ -1042,7 +1052,12 @@ internal sealed class BasketSimulation
basket.Levels.Count, [.. basket.Unit.Data.Unit.Legs.Select(l => l.Name)], reason, result));
}
var run = new BacktestRun("USD", _engine.InitialCapital, _equity, _fills, trades, [], _notes) { Baskets = baskets };
// The financing of the positions still open has left the cash at every rollover, but no closing fill carries it.
var run = new BacktestRun("USD", _engine.InitialCapital, _equity, _fills, trades, [], _notes)
{
Baskets = baskets,
AccruedFees = _positions.Where(p => p.Open).Sum(p => p.Financing),
};
return new BasketRunResult(run, traces, _events, _commission, _financing);
}
+8 -1
View File
@@ -80,7 +80,14 @@ public sealed record BacktestRun(
public decimal NetResult => FinalEquity - InitialCapital;
public decimal Fees => Fills.Sum(f => f.Fee);
/// <summary>Every fee paid: those of the fills and <see cref="AccruedFees"/>.</summary>
public decimal Fees => Fills.Sum(f => f.Fee) + AccruedFees;
/// <summary>
/// Fees already taken from the cash that no fill carries: the financing of the positions still open at the end. Only the
/// basket engine has them; zero for the daily engine.
/// </summary>
public decimal AccruedFees { get; init; }
public decimal Dividends { get; init; }
+7
View File
@@ -328,6 +328,13 @@ public sealed partial class Laboratory : IDisposable
throw new InvalidOperationException("Il piano registrato non corrisponde più alla sua impronta: la prova non parte.");
}
// The basket family only does research and its trials run from the command line: one found here was left by a
// command that stopped before the end (Phase 14).
if (trial.Strategy == BasketReversionFamily.FamilyId)
{
throw new InvalidOperationException("Prova a panieri interrotta: si rilancia da riga di comando con «anubis backtest baskets».");
}
var family = Families(trial.Strategy) ?? throw new InvalidOperationException("Strategia non più disponibile: " + trial.Strategy);
if (family.Version != trial.StrategyVersion)
{
+4 -2
View File
@@ -299,7 +299,8 @@ internal static class TrialUnitOutcomes
IReadOnlyList<BacktestNote> Notes,
decimal Dividends,
decimal WrittenOff,
IReadOnlyList<BacktestBasket> Baskets);
IReadOnlyList<BacktestBasket> Baskets,
decimal AccruedFees = 0m);
private sealed record StoredControl(double Sharpe);
@@ -344,11 +345,12 @@ internal static class TrialUnitOutcomes
Dividends = run.Dividends,
WrittenOff = run.WrittenOff,
Baskets = run.Baskets,
AccruedFees = run.AccruedFees,
}, null);
}
private static StoredRun Stored(BacktestRun run) =>
new(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, run.Notes, run.Dividends, run.WrittenOff, run.Baskets);
new(run.Currency, run.InitialCapital, run.Equity, run.Fills, run.Trades, run.Notes, run.Dividends, run.WrittenOff, run.Baskets, run.AccruedFees);
}
/// <summary>States of a row of <c>tournament_units</c>.</summary>
+1
View File
@@ -108,6 +108,7 @@ public static class ReasonCatalog
["account_stop"] = "Perdita aperta pari o oltre il 9% del saldo: si chiude tutto e niente ingressi fino al cambio di giorno del server.",
["mandatory_stop"] = "Stop obbligatorio della piattaforma raggiunto: la posizione è chiusa.",
["orphan_leg"] = "Lo stop obbligatorio ha chiuso una gamba del paniere: l'altra, rimasta sola, si chiude all'esecuzione successiva.",
["closed_with_stop"] = "Chiuso insieme a un livello del paniere fermato dallo stop obbligatorio della piattaforma: senza quel livello la scala delle mediazioni non regge più.",
["liquidation"] = "Patrimonio sotto metà del margine iniziale delle posizioni aperte: la piattaforma chiude tutto.",
["end"] = "Ancora aperto alla fine dei dati: valutato agli ultimi prezzi.",
// Baskets (Phase 14): refusals and notes.
+79
View File
@@ -157,6 +157,85 @@ public sealed class BasketCommandTests
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnInterruptedBasketTrialIsRecordedAsFailedWithAnItalianReason()
{
// Ctrl+C or the stop of the container while the trial runs: the command's token is cancelled as soon as it says the
// trial is planned. The trial is recorded as failed with a reason the user can act on, no report is written, exit 1.
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
await using var engine = postgres;
var data = TempFolder.Create("baskets-stop");
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
try
{
var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
await using var db = Database.Open(config.Db!);
await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
Directory.CreateDirectory(config.Data.Research);
await File.WriteAllBytesAsync(Ecb.HistoryPath(config.Data.Research), EcbZip()).ConfigureAwait(false);
var outDir = Path.Combine(data, "out");
using var stop = new CancellationTokenSource();
using var output = new StopOnLine(stop, "Prova ");
var code = await BasketCommand.RunAsync(
["--offline", "--to", "2001-12-31", "--control", "1", "--out", outDir, "--platform", "docker", "--data-dir", data], output, env, new FakeHttp(), clock,
stop.Token).ConfigureAwait(false);
const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
Assert.AreEqual(1, code, output.ToString());
StringAssert.Contains(output.ToString(), "Non riuscito: " + Interrupted);
Assert.IsFalse(output.ToString().Contains(" at ", StringComparison.Ordinal), "no stack trace");
var trial = (await new TrialStore(db, clock).ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
Assert.AreEqual(TrialStatuses.Failed, trial.Status);
Assert.AreEqual(Interrupted, trial.Error);
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".md")), "an interrupted trial writes no report");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheLaboratoryFailsALeftoverBasketTrialWithAnAccurateReason()
{
// A basket trial left planned or running by a command that died is picked up by the laboratory at the next start. The
// family only runs from the command line: the trial fails with a reason that says so, not «no longer available».
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
var (plan, variants) = BasketProtocol.Plan(To, clock.UtcNow);
var left = await lab.Trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
await lab.ProcessAsync(left.Id, CancellationToken.None).ConfigureAwait(false);
var failed = (await lab.Trials.GetAsync(left.Id, CancellationToken.None).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Failed, failed.Status);
Assert.AreEqual("Prova a panieri interrotta: si rilancia da riga di comando con «anubis backtest baskets».", failed.Error);
}
/// <summary>Console output that cancels the command's token at the first line starting with <c>start</c>.</summary>
private sealed class StopOnLine(CancellationTokenSource stop, string start) : StringWriter(System.Globalization.CultureInfo.InvariantCulture)
{
public override void WriteLine(string? value)
{
base.WriteLine(value);
if (value is not null && value.StartsWith(start, StringComparison.Ordinal))
{
stop.Cancel();
}
}
public override Task WriteLineAsync(string? value)
{
WriteLine(value);
return Task.CompletedTask;
}
}
/// <summary>A trigger that changes every plan as soon as it is written: someone touching the register behind the command.</summary>
private static async Task TamperAsync(Database db, string set)
{
+89
View File
@@ -341,6 +341,95 @@ public sealed class BasketEngineTests
Assert.AreEqual(VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_098.5m, 5), result.Financing);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnDailyBarsTheAccountStopPausesOnlyUntilTheServerDateChanges()
{
// Daily fixings at 00:00 UTC from Monday 5 January 2026, no spread and no cost. 100,000 EURUSD bought at 1.0000 on
// Tuesday 20 (bar 11); Wednesday's bar (12) closes at 0.9910, on Thursday 22 at 00:00 UTC: open loss 900 / 10,000 = 9%,
// the account stop fires. That moment is Wednesday 19:00 in New York, already server day Thursday, so the pause lasts
// until Thursday 17:00 New York, 22:00 UTC. Thursday's bar (13) is decided at its close, Friday 00:00 UTC, after the
// change: its signal (0.9800, z = −2.57) opens.
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0001, 10), 0.9990, 1.0000, 0.9910, 0.9800, 0.9800];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m }, VenueCosts.None);
var stop = result.Events.Single(x => x.Reason == BasketReasons.AccountStop);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 22)), stop.At, "at the close of Wednesday's bar");
Assert.AreEqual(new DateTimeOffset(2026, 1, 22, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(stop.At));
Assert.IsFalse(result.Events.Any(x => x.Reason == BasketReasons.PausedUntilNextDay), "Thursday's decision comes after the change");
var reopened = result.Events.Single(x => x.Kind == BasketEventKinds.Open && x.At > stop.At);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 23)), reopened.At, "Thursday's signal opens at its close");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AMandatoryStopOnOneLevelOfASinglePairBasketClosesTheOtherLevelsWithTheirOwnReason()
{
// EURUSD (spread 0.1 pip) signals on Monday 19 January 2026 and is bought on Tuesday at the ask 0.998505; Wednesday
// closes at 0.9900, 86 pips under it with z = −2.78: an averaging, bought on Thursday at 0.989005. The venue's stops
// at leverage 5 sit 10% under each entry: 0.8986545 and 0.8901045. Friday fixes at 0.8950, bid 0.894995: level 0's
// stop is gone through at the open, level 1's is not. The basket's exit is the mandatory stop; level 1 closes at the
// next execution as closed with it, not as a stop of its own, and nothing is an orphan leg (one pair).
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, 0.9900, 0.9890, 0.8950, 0.8950, 0.8950];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument) with { Distance = 50m }, VenueCosts.Etoro);
var trace = result.Traces.Single();
Assert.AreEqual(2, trace.Levels);
Assert.AreEqual(BasketReasons.MandatoryStop, trace.ExitReason);
Assert.AreEqual(BasketReasons.MandatoryStop, result.Run.Baskets.Single().ExitReason);
CollectionAssert.AreEqual(new[] { BasketReasons.MandatoryStop, BasketReasons.ClosedWithStop }, trace.Positions.Select(p => p.ExitReason).ToArray());
CollectionAssert.AreEqual(new int?[] { 14, 15 }, trace.Positions.Select(p => p.ExitBar).ToArray());
Assert.AreEqual(0.894995m, trace.Positions[0].ExitPrice, "the bid of Friday's open");
Assert.AreEqual(1, result.Run.Fills.Count(f => f.Reason == BasketReasons.ClosedWithStop));
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.MandatoryStop));
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.ClosedWithStop));
Assert.AreEqual(0, result.Run.Notes.Count(n => n.Reason == BasketReasons.OrphanLeg));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFeesOfARunIncludeTheFinancingOfPositionsStillOpen()
{
// EURUSD bought on Tuesday 20 January 2026 at 1.098505 and never sold: still open at the end. Its financing has left the
// cash at every rollover, so it is in the fees of the run although no closing fill carries it.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), .. Enumerable.Repeat(1.0985, 10)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument), VenueCosts.Etoro);
Assert.AreEqual(BasketReasons.End, result.Run.Baskets.Single().ExitReason);
Assert.IsTrue(result.Financing > 0m, $"financing {result.Financing}");
Assert.AreEqual(result.Commission + result.Financing, result.Run.Fees);
Assert.AreEqual(result.Run.Fills.Sum(f => f.Fee) + result.Financing, result.Run.Fees, "one opening fill: its commission, plus the financing");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveTheCurrencyCapStopsNewBasketsNotTheAveragingsOfAnOpenOne()
{
// 10,000 EURUSD (100,000 of capital) bought at 0.9985, then three averagings 15 pips apart or more, each with z ≤ −2:
// at 0.9960 (z −2.47), 0.9930 (−2.12) and 0.9860 (−2.26). Long EURUSD alone is long euro and short dollar, two entries
// and more once averaged: the cap of two entries per currency is for a new basket (plan, section 5), never for the
// levels of one already open. Prudente makes its three averagings; Fedele writes no note about them.
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, 0.9960, 0.9960, 0.9930, 0.9930, 0.9860, 0.9860, 0.9860];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
foreach (var profile in BasketProfiles.All)
{
var result = Run(data, SingleRules(EurUsd, BasketMode.AsLive) with { Distance = 15m, Profile = profile }, VenueCosts.None, 100_000m);
var trace = result.Traces.Single();
Assert.AreEqual(4, trace.Levels, profile.Name);
CollectionAssert.AreEqual(new[] { 11, 13, 15, 17 }, trace.Positions.Select(p => p.EntryBar).ToArray(), profile.Name);
Assert.AreEqual(0, result.Events.Count(x => x.Reason == BasketReasons.CurrencyExposure), profile.Name);
Assert.AreEqual(0, result.Run.Notes.Count(n => n.Reason == BasketReasons.CurrencyExposure), profile.Name);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheRollingRvolEqualsTheReference()
+54 -8
View File
@@ -127,29 +127,54 @@ public sealed class BasketReportTests
new("EURUSD-USDCHF", opened.AddDays(3), opened.AddDays(4), 1_000m, 2, ["EURUSD", "USDCHF"], "orphan_leg", -12m),
new("AUDNZD", opened.AddDays(5), opened.AddDays(9), 1_000m, 1, ["AUDNZD"], "target", 9m),
new("AUDNZD", opened.AddDays(10), opened.AddDays(12), 1_000m, 1, ["AUDNZD"], "target", 8m),
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], null, -3m),
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], BasketReasons.End, -3m),
];
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
{
["orphan_leg"] = 2,
["closed_with_stop"] = 3,
["gate_open_loss"] = 5,
["weird_code"] = 1,
};
var two = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes, Baskets = baskets } })), "## Prova del motore a panieri");
StringAssert.Contains(two, "Gambe rimaste sole: 2");
StringAssert.Contains(two, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 3 (");
StringAssert.Contains(two, "| stop obbligatorio della piattaforma | 1 |");
StringAssert.Contains(two, "| gamba rimasta sola dopo uno stop obbligatorio | 1 |");
StringAssert.Contains(two, "| obiettivo raggiunto | 2 |");
StringAssert.Contains(two, "| ancora aperto alla fine | 1 |");
StringAssert.Contains(two, "| ancora aperto alla fine (valutato agli ultimi prezzi) | 1 |");
StringAssert.Contains(two, "Panieri della variante giudicata: 5.");
StringAssert.Contains(two, "perdita aperta oltre il 2%");
StringAssert.Contains(two, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 5 |");
StringAssert.Contains(two, "| `weird_code` | 1 |");
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0%");
Assert.IsFalse(two.Contains("`closed_with_stop`", StringComparison.Ordinal), "closes, not refusals");
Assert.IsFalse(two.Contains("fine del periodo", StringComparison.Ordinal), "a basket open at the end was not closed");
// Two at the target out of the four closed: the one still open at the end is not counted among the closed.
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0% dei panieri chiusi");
var none = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = new Dictionary<string, int>(), Baskets = [] } })), "## Prova del motore a panieri");
StringAssert.Contains(none, "Gambe rimaste sole: 0");
StringAssert.Contains(none, "Chiusure d'ufficio per margine insufficiente: 0");
StringAssert.Contains(none, "Stop sul valore del conto: 0");
StringAssert.Contains(none, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 0 (");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLimitsAreWrittenOnce()
{
// With a trial, the engine's own limitations already speak of the ECB prices and of the costs: the report does not
// repeat its own version of them. Without one, it writes them.
const string Prices = "- I prezzi sono i cambi di riferimento della BCE, uno al giorno";
const string Costs = "- I costi sono quelli di eToro letti il 02/12/2026";
var withTrial = Section(BasketReport.Markdown(Input(_trial.Value)), "## Cosa il backtest non rappresenta");
var without = Section(BasketReport.Markdown(Input(null, "Nessuna prova.")), "## Cosa il backtest non rappresenta");
StringAssert.Contains(withTrial, "- Motore finto della prova.");
Assert.AreEqual(0, Count(withTrial, Prices), withTrial);
Assert.AreEqual(0, Count(withTrial, Costs), withTrial);
Assert.AreEqual(1, Count(without, Prices), without);
Assert.AreEqual(1, Count(without, Costs), without);
}
[TestMethod]
@@ -174,14 +199,33 @@ public sealed class BasketReportTests
[BasketReasons.RvolFilter] = 1,
[BasketReasons.CorrelationLow] = 1,
[BasketReasons.SwitchTripped] = 1,
[BasketReasons.MaxOpenBaskets] = 1,
[BasketReasons.MaxOpenBaskets] = 1_569,
};
var text = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes } })), "## Prova del motore a panieri");
StringAssert.Contains(text, "| troppe posizioni aperte per la piattaforma | 3 |");
var report = trial.Report with
{
Notes = notes,
LookAhead = trial.Report.LookAhead with { Decisions = 4_817 },
Overfitting = new ReportOverfitting(16, 12_870, 4, 0.25),
};
var text = Section(BasketReport.Markdown(Input(trial with { Report = report })), "## Prova del motore a panieri");
// Each label says what the engine does (BasketSimulation, ReasonCatalog).
StringAssert.Contains(text, "| si supererebbero 9 posizioni aperte (conto Demo condiviso) | 3 |");
StringAssert.Contains(text, "| fuori dalla finestra oraria | 4 |");
StringAssert.Contains(text, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 1 |");
StringAssert.Contains(text, "| volatilità recente oltre il doppio del normale, o non ancora nota | 1 |");
StringAssert.Contains(text, "| perdita del giorno pari o oltre il 2%: niente ingressi né mediazioni per 24 ore | 1 |");
StringAssert.Contains(text, "| correlazione tra le gambe sotto 0,6 sul segno atteso, o non ancora nota | 1 |");
StringAssert.Contains(text, "| esposizione netta su una valuta oltre due ingressi (solo panieri nuovi) | 1 |");
StringAssert.Contains(text, "| dimensione ridotta a metà o a un quarto (perdita della settimana o calo dal massimo) | 1 |");
StringAssert.Contains(text, "Posizioni chiuse dallo stop obbligatorio della piattaforma: 6.");
var refusals = text[text.IndexOf("**Ingressi e mediazioni fermati o annotati**", StringComparison.Ordinal)..];
Assert.IsFalse(refusals.Contains('`', StringComparison.Ordinal), "a code without a label: " + refusals);
// Counts are grouped the Italian way, like every other number of the report.
StringAssert.Contains(text, "| già aperto il numero massimo di panieri | 1.569 |");
StringAssert.Contains(text, "4.817 decisioni");
StringAssert.Contains(text, "su 12.870 combinazioni");
}
[TestMethod]
@@ -193,7 +237,9 @@ public sealed class BasketReportTests
StringAssert.Contains(text, "zero (nessuna operazione)");
Assert.IsFalse(text.Contains("comprare e tenere", StringComparison.OrdinalIgnoreCase));
Assert.IsFalse(text.Contains("buy and hold", StringComparison.OrdinalIgnoreCase));
StringAssert.Contains(text, "**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)");
StringAssert.Contains(text, "**Sensibilità ai costi** (differenziale, commissioni e finanziamento a carico moltiplicati insieme; gli accrediti di finanziamento restano uguali)");
StringAssert.Contains(text, "| Commissioni e finanziamento pagati (il differenziale è già nei prezzi) | ");
Assert.IsFalse(text.Contains("| Costi pagati |", StringComparison.Ordinal));
StringAssert.Contains(text, "| ×2 |");
StringAssert.Contains(text, "| ×3 |");
}
@@ -189,6 +189,42 @@ public sealed class BasketTrialEngineTests
Assert.AreEqual(engine.Sessions, surrogate.Run(StrategyParameters.Of(BasketReversionFamily.Instance, "generation=2;signal=2;units=2;target=2.5;distance=4;exit=2")).Equity.Count);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void WithBidAndAskTheSurrogateKeepsTheSizeOfEveryMidChange()
{
// 15-minute EURUSD quotes two pips wide around a walking mid, from Tuesday 13 January 2026 20:00 UTC over four server
// days whose signs alternate. The engine reads the mid: in the surrogate every change of the mid keeps its size and
// the spread stays around it. Chained on the bid, the mid would jump by a whole spread at each change of sign.
var first = new DateTimeOffset(2026, 1, 13, 20, 0, 0, TimeSpan.Zero);
var walk = BasketSynthetic.Walk(200, 7, 0, 0.0004);
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
{
["EURUSD"] = [.. walk.Select(x => BasketSynthetic.Mid(Math.Round(1.1m * (decimal)Math.Exp(x), 5), 0.0002m))],
});
var market = BasketMarket.Of(data);
var days = market.Day(market.Count - 1).DayNumber - market.Day(0).DayNumber + 1;
Assert.IsTrue(days >= 3, $"{days} server days");
var signs = new DaySigns(market.Day(0), [.. Enumerable.Range(0, days).Select(i => i % 2 == 0 ? 1 : -1)]);
var surrogate = market.Surrogate(signs, centred: false);
var before = market.Reference("EURUSD");
var after = surrogate.Reference("EURUSD");
var (bid, ask) = (surrogate.Bid("EURUSD").Close, surrogate.Ask("EURUSD")!.Close);
var (bid0, ask0) = (market.Bid("EURUSD").Close, market.Ask("EURUSD")!.Close);
var turned = 0;
for (var t = 1; t < before.Count; t++)
{
Assert.AreEqual(Math.Abs(Math.Log(before[t] / before[t - 1])), Math.Abs(Math.Log(after[t] / after[t - 1])), 1e-7, $"bar {t}");
Assert.IsTrue(bid[t] < ask[t], $"bar {t}");
Assert.AreEqual((ask0[t] - bid0[t]) / before[t], (ask[t] - bid[t]) / after[t], 1e-6, $"bar {t}: the spread stays around the mid");
turned += market.Day(t) != market.Day(t - 1) ? 1 : 0;
}
Assert.IsTrue(turned >= 2, $"{turned} changes of sign");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFamilyHasOneIdForEverySubVariant()
+5 -2
View File
@@ -65,8 +65,11 @@ public sealed class VenueCostsTests
("EURCHF", -0.33m, 1.04m),
];
// Table 6.5, maximum stop distance in pips at leverage 30, 20, 10, 5, 2 (null: the leverage is above the pair's), with the
// 1 December price every cell of the row implies: the one four-decimal price at which all five cells round to the table.
// Table 6.5, maximum stop distance in pips at leverage 30, 20, 10, 5, 2 (null: the leverage is above the pair's), with a
// four-decimal price worked back from the table, at which all five cells of the row round to the document's values. It is
// not an independent 1 December price and not the only one that fits (each row has two to four such prices, e.g. EURUSD
// 1.0858 and 1.0859); the units of appendix A give slightly different prices (EURUSD 1,000 / 921 = 1.08578, which gives
// 2,714 pips at leverage 2, not 2,715). What the test checks is the formula 0.5 / leverage × price / pip on every cell.
private static readonly (string Pair, decimal Price, int?[] Pips)[] Table65 =
[
("EURUSD", 1.0859m, [181, 271, 543, 1086, 2715]),