9 Commits
Author SHA1 Message Date
Alby96andClaude Opus 5.5 ff9046f849 Record the choices, proofs and state of Phase 14
ci / test (postgres) (push) Successful in 7m31s
ci / test (sqlite) (push) Successful in 6m2s
ci / test (postgres) (pull_request) Successful in 8m8s
ci / test (sqlite) (pull_request) Successful in 6m42s
ci / image (push) Successful in 1m47s
ci / image (pull_request) Successful in 1m4s
ADR 0030 writes down what the basket engine had to decide where the plan
and the research document are silent: the appendix G conventions found
by the prototype, the orphan-leg and broken-ladder closes, the estimated
financing, the modes, the reason codes, the trial grid and how the
command checks its plan. ROADMAP ticks the phase with the tests that
prove each criterion, STATE records the first verdict on the basket
family (not passed) and the review, and the manual explains the new
"backtest baskets" command.

refs #132

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:26:42 +01:00
Alby96andClaude Opus 5.5 a8defde572 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>
2026-12-04 19:26:24 +01:00
Alby96andClaude Opus 5.5 3bee136c74 Add the backtest baskets command and the basket family's report
`anubis backtest baskets` reruns the replica of appendix G on the 28 ECB
crosses up to the research document's end, the G.5 control against
chance, and a trial of the basket engine "come dal vivo" with the eToro
costs on 20,000 USD, from 1999 to the chosen day on a grid fixed in
BasketProtocol (generation A/B x distance 4/10 sigma). The plan is
written to the trial register before the run, read back and run only if
it is still the plan just written (a changed or re-hashed plan fails the
trial), judged with every earlier basket_reversion trial counted, and
recorded. --offline reads only the cached ECB zip and stops in Italian
when it is missing. The report is written whatever the verdict; there is
no outcome file.

The report now labels max_positions and clock_window, reads its codes
from BasketReasons and BasketModes, counts positions closed by the
mandatory stop instead of listing them among refused entries, and no
longer repeats the engine's own limitations. The generated report is
committed: 13 of 13 binding replica rows inside the band, verdict not
passed (net at double costs and DSR).

refs #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 18:40:49 +01:00
Alby96andClaude Opus 5.5 d1ae650043 Add the Italian report of the basket family
basket_reversion.md has to be written whatever the verdict and must show
what the phase measures: the replica of appendix G against the document's
15 totals with the binding rows counted, the control against chance of
G.5, and the trial of the basket engine with its exit reasons, orphan legs
(counted, also when zero), liquidations, account stops and refusals. The
comparison is zero (no trading), never buy and hold (ADR 0026 point 5),
and the share of baskets closed at the target is shown, never judged.
The report reads only BacktestReport, so it does not depend on the engine
being written in parallel; there is no outcome file for baskets yet.

A test checks the report and this source never contain the name of the
product the research document describes, through a hash of the name.

refs #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 18:17:13 +01:00
Alby96andClaude Opus 5.5 acc9efe39d Add the basket_reversion family and its trial engine
The trial machinery of Phase 13 judges a family through an ITrialEngine;
the baskets need one so their variants go through the same judge, cost
stress, control and look-ahead check as the daily families.

BasketReversionFamily ("Rientro tra strumenti") has one identifier for
every sub-variant: generation A (the five documented spreads) or B (ten
single symbols), signal, target, distance, growth, averagings, window,
entry threshold, exit rule, profile, open baskets and lot. The choice
axes are decimal codes marked as choices, so the plan never treats them
as a range to explore. Rules() turns parameters into BasketRules and
refuses a combination the family does not accept.

BasketTrialEngine runs the basket engine on the plan's data with the
plan's mode (come_dal_vivo by default) and venue costs (eToro by
default): one equity point a day on the same days for every variant,
260 points a year, zero as the comparison (the account is not long
anything), a surrogate that flips each day's changes for the control,
and a look-ahead check that compares the decisions taken before each
cut with those taken on the cut data. Its fingerprint carries the
market, the engine version, the costs and the mode.

refs #129

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 18:17:13 +01:00
Alby96andClaude Opus 5.5 44639e3f49 Add the basket engine: a margin account that trades the document's baskets
Phase 14 needs an engine that simulates the research document's baskets
with the frictions of the venue, so the trial judge can say whether they
earn anything once those frictions are paid.

BasketEngine walks a BasketMarket (the bars of a BarDataset without the
moments no symbol trades) bar by bar: decisions on the closed bar,
execution at the next open, buys at the ask and sells at the bid (bid and
ask rebuilt from the venue spread when the source gives one price, as the
ECB fixings do). Every leg of every level is its own position with the
venue's mandatory stop; a stop that leaves one leg of a two-leg basket
alone closes the rest at the next execution as an orphan leg. Commission
on both sides, financing at every rollover crossed (Wednesday triple, from
the VenueCosts calendar), liquidation below half the initial margin.

On top, the document's account rules (9% stop on the open loss over the
balance, on mid prices in the daily pause, entries back at the next server
day; 2% gate on new baskets only; open baskets, Rvol, correlation, three
costs) and, «come dal vivo», SPEC 9.2 through RiskMonitor (day, week, fall
from the high, trip with the seven-day restart), the 40% margin limit,
nine positions, no opposite positions, net exposure per currency and the
Prudente basket stops. One equity point a day for every variant.

Signals come from the replica's RollingZ and RollingSigma on each unit's
compressed series; a rolling Rvol joins them, equal to BasketIndex.Rvol.
The comparison configuration (same close, no cost, no protection) makes
the replica's baskets on 200 seeded series and its total to 1e-9; on the
ECB fixture it gives the replica's 535.54 targets over 1,259 baskets.
TrialPlan gains optional Mode and Costs, left out when null, so the plans
of the daily families keep their hashes.

refs #127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 18:17:13 +01:00
Alby96andClaude Opus 5.5 63bd5b9635 Add the stylised replica of appendix G and the shared rolling signals
Phase 14 must reproduce the 15 "Forex 1999-2026" totals of table G.4 and
check the basket engine against a yardstick that follows G.3 to the
letter. StylisedReplica runs generation B on each series of ln(close),
entry and exit on the same close, no costs, with the conventions a numpy
prototype found to reproduce every row: z over the last 100 values with
the sample deviation, sigma as the population deviation of the 99
differences inside them, stop before target (per position against the
mean of entries) before averaging, no reopening on the closing bar, open
baskets valued at the last close. On the ECB history up to 2 Dec 2026 it
gives the prototype's totals, positions and baskets on all 15 rows; the
13 binding totals are within their band (largest gap 3.4 targets).

BasketIndex.RollingZ and RollingSigma compute the signals in one pass
with anchored sliding sums rebuilt every window, so the replica and the
engine can read the same bits; they equal the exact two-pass values to
1e-9 and refuse a series with a gap. The control of G.5 flips the first
differences of all series with one sign per bar (not centred) and
measures the share of replicas whose break-even is equal or better.

refs #130

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 17:04:38 +01:00
Alby96andClaude Opus 5.5 47e08d6778 Add venue costs and the financing calendar for the basket engine
The basket engine needs the costs and margin rules of the venue it
simulates, dated and sourced, so a basket trial can copy them into its
plan and its fingerprint changes when any value does.

VenueCosts holds, per pair, the eToro values of the research document
(appendix A and section 6.3, 1-2 December 2026): instrument id, real
account leverage, bid/ask in normal hours and in the daily pause,
commission per side (0.005%, 0.002% on USDJPY) and overnight financing
in USD per 100,000 USD a night. The twelve legs of section 6.3 are
stored as the document's pips x pip value per 1,000 USD x 100 (EURUSD
buy 8.096, the 8.10 USD of section 6.7); the sixteen pairs without a
rate pay the largest known charge on both sides and are marked
estimated. Venue-wide: minimum 1,000 USD, default leverage 5, allowed
leverages, mandatory stop at 50% of the margin, account liquidation
at 50% of the initial margin. VenueCosts.None is the comparison
configuration: no costs, no mandatory stop, no liquidation.

Scaled(m) multiplies spread, pause spread, commission and financing
charges only; credits stay. Margin, stop distance (none for a buy at
leverage 1, as section 6.5 says) and a leverage check that refuses, in
Italian, a leverage the venue or the pair does not allow. The JSON
uses the plan's options and the fingerprint is its SHA-256.

FinancingCalendar counts the rollovers at 17:00 New York (the server
day change) on Monday to Friday, Wednesday triple, in closed form: a
position held from Tuesday to Friday pays five nights.

refs #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 17:04:38 +01:00
Alby96andClaude Opus 5.5 19a9a049f4 Add the ECB history of the research document as test data
The reference rates of the seven currencies against the euro from
1999-01-04 to 2026-12-02 (7,149 fixings), cut from the ECB history
downloaded on 2026-12-04. These are the data behind the "Forex
1999-2026" column of appendix G that Phase 14 must reproduce; no test
uses the network. SHA-256 f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8.

refs #130

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:29:51 +01:00
32 changed files with 14076 additions and 22 deletions

No files matched your search

+6
View File
@@ -310,6 +310,12 @@ docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data ecb
docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data fx /data/import/DAT_ASCII_EURUSD_M1_2024.csv
```
**Prova a panieri.** `backtest baskets` usa gli stessi cambi della BCE e fa tre cose: rifà i conti dell'appendice G del documento di ricerca, li confronta con le serie rimescolate a caso e prova il motore a panieri «come dal vivo», con i costi di eToro. La prova si registra nel database come ogni altra e conta per quelle dopo. Il rapporto `basket_reversion.md` si scrive qualunque sia il verdetto. È solo ricerca: nessun ordine, nemmeno finto. `--to AAAA-MM-GG` sceglie l'ultimo giorno (di solito è l'ultimo del mese scorso), `--offline` usa il file già scaricato, `--control N` sceglie quante serie rimescolate (150, come il documento).
```sh
docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll backtest baskets --out /data/backtests
```
Attenzione: il Laboratorio legge dallo storico di ricerca solo le serie giornaliere di Binance. I dati importati con `"venue": "import"` restano in archivio e il Laboratorio **non li usa**. Per usarli servono `"venue": "binance"`, `"timeframe": "1d"` e un simbolo di Binance come `BTCUSDT`: in quel caso le tue barre **sostituiscono** quelle già scaricate per gli stessi giorni, anche per la revisione trimestrale. Fallo solo se sei sicuro dei dati.
---
+24 -14
View File
@@ -416,27 +416,37 @@ Un secondo motore di prova che sa fare ciò che il primo non fa: barre più cort
**Lavori**
- [ ] [#127](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/127) Motore `Backtest/BasketEngine.cs`
- [ ] [#128](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/128) Costi `Backtest/VenueCosts.cs`, per sede
- [ ] [#129](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/129) Famiglia `basket_reversion` in `Strategies/BasketReversion.cs`, prima parte
- [ ] [#130](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/130) Riferimento
- [ ] [#131](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/131) Comando `anubis backtest baskets`
- [ ] [#132](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/132) Chiusura della fase, revisione indipendente e tag `fase-14` (dopo il sì dell'utente)
- [x] [#127](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/127) Motore `Backtest/BasketEngine.cs`
- [x] [#128](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/128) Costi `Backtest/VenueCosts.cs`, per sede
- [x] [#129](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/129) Famiglia `basket_reversion` in `Strategies/BasketReversion.cs`, prima parte
- [x] [#130](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/130) Riferimento
- [x] [#131](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/131) Comando `anubis backtest baskets`
- [x] [#132](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/132) Chiusura della fase, revisione indipendente e tag `fase-14` (dopo il sì dell'utente)
**Criteri di accettazione**
- [ ] Un paniere giocattolo a due gambe dà esattamente il risultato calcolato a mano.
- [ ] Margine per posizione e distanza dello stop obbligatorio delle tabelle 6.4 e 6.5; cinque notti pagate da martedì a venerdì; uno stop obbligatorio che lascia una gamba orfana viene contato nel rapporto.
- [ ] Stop sul valore del conto alla soglia esatta e ripresa al cambio di data del server; il cancello del 2% ferma i panieri nuovi e lascia passare le mediazioni; nel modo «come dal vivo» una giornata a −2% ferma anche quelle.
- [ ] **Appendice G.** Il file storico della BCE fino al 2 dicembre 2026, ridotto alle sette valute che servono, entra nei dati di prova con la sua impronta: nessun test usa la rete.
- [x] Un paniere giocattolo a due gambe dà esattamente il risultato calcolato a mano.
- [x] Margine per posizione e distanza dello stop obbligatorio delle tabelle 6.4 e 6.5; cinque notti pagate da martedì a venerdì; uno stop obbligatorio che lascia una gamba orfana viene contato nel rapporto.
- [x] Stop sul valore del conto alla soglia esatta e ripresa al cambio di data del server; il cancello del 2% ferma i panieri nuovi e lascia passare le mediazioni; nel modo «come dal vivo» una giornata a −2% ferma anche quelle.
- [x] **Appendice G.** Il file storico della BCE fino al 2 dicembre 2026, ridotto alle sette valute che servono, entra nei dati di prova con la sua impronta: nessun test usa la rete.
- *Vincolante:* il motore in configurazione di confronto coincide con `StylisedReplica` su 200 serie a seme fisso.
- *Vincolante:* sui cambi BCE, per i 13 totali della colonna «Forex 1999–2026» che superano 100 obiettivi in valore assoluto, `StylisedReplica` dà lo stesso segno e uno scarto entro il 5% o entro 25 obiettivi (il maggiore dei due).
- *Riportati, non vincolanti:* gli altri due totali (−98 e −45), troppo vicini a zero per un confronto in percentuale.
- I conti del documento non hanno un programma con cui confrontarli, e i totali comprendono i panieri ancora aperti all'ultimo giorno: dipendono dal giorno esatto di fine dati e da convenzioni che il documento non scrive. Se un totale vincolante resta fuori, l'ADR della fase elenca la convenzione sospetta e ti chiedo lo script o i dati con cui sono stati fatti quei conti: il criterio passa «in attesa dell'utente» e il programma prosegue, perché le fasi dopo dipendono dal motore e non da quei numeri.
- [ ] Sul processo costruito per rientrare, con dimezzamento a 50 barre, il costo di pareggio è circa 1,2 obiettivi (il documento dà 1,23); su un cammino casuale con deriva è negativo.
- [ ] Su 100 insiemi di cammini casuali la quota di serie rimescolate «pari o migliori» ha media tra 0,40 e 0,60, e meno di 10 insiemi scendono sotto 0,05; sul processo che rientra la quota sta sotto 0,05.
- [ ] Test contro lo sguardo in avanti del motore: una regola che legge la barra successiva viene scoperta.
- [ ] Una prova a panieri gira da riga di comando su SQLite e su PostgreSQL con il piano intatto.
- [x] Sul processo costruito per rientrare, con dimezzamento a 50 barre, il costo di pareggio è circa 1,2 obiettivi (il documento dà 1,23); su un cammino casuale con deriva è negativo.
- [x] Su 100 insiemi di cammini casuali la quota di serie rimescolate «pari o migliori» ha media tra 0,40 e 0,60, e meno di 10 insiemi scendono sotto 0,05; sul processo che rientra la quota sta sotto 0,05.
- [x] Test contro lo sguardo in avanti del motore: una regola che legge la barra successiva viene scoperta.
- [x] Una prova a panieri gira da riga di comando su SQLite e su PostgreSQL con il piano intatto.
Prove:
- `BasketEngineTests`: il paniere giocattolo a due gambe (EURUSD e USDCHF, barre a 15 minuti con denaro e lettera) dà 143,98 USD, calcolati a mano nel commento della prova; stop sul valore del conto al 9,00% sì e all'8,99% no, ripresa al primo giorno del server dopo, e durante la pausa giornaliera lo stop usa i prezzi medi; cancello del 2% «alla lettera» e giornata a −2% «come dal vivo»; metà e un quarto della dimensione (5.000 e 2.500 unità) e un livello sotto il minimo della sede che non parte; limite di margine, limite di posizioni, nessuna posizione opposta; chiusura d'ufficio sotto metà del margine; cinque notti di finanziamento da martedì a venerdì; il motore in configurazione di confronto coincide con `StylisedReplica` su 200 serie a seme fisso (oltre 5.000 panieri, totale uguale entro 1e-9).
- `BasketTrialEngineTests`: uno stop obbligatorio che lascia una gamba sola è contato nel rapporto; il lotto non cresce mai dentro un paniere; una regola che legge la barra dopo viene scoperta; un punto di patrimonio al giorno sugli stessi giorni per ogni variante; il giudice delle prove giudica una prova a panieri (termine di confronto zero, copia senza regolarità non centrata); un solo identificativo per tutte le sotto-varianti; assi a scelta segnati; il piano porta modo e costi.
- `VenueCostsTests`: margine e stop obbligatorio delle tabelle 6.4 e 6.5; cinque notti da martedì a venerdì; i moltiplicatori scalano commissione, differenziale e finanziamento pagato; la tabella di eToro copia l'appendice A; una leva sconosciuta è rifiutata in italiano; l'impronta cambia con ogni valore.
- `StylisedReplicaTests`: l'impronta dello storico BCE; i 13 totali vincolanti dell'appendice G dentro la tolleranza e i due non vincolanti con il segno giusto; il costo di pareggio sul processo che rientra (1,2) e sul cammino con deriva (negativo); la quota «pari o migliori» sui cammini casuali (media 0,51, 5 insiemi su 100 sotto 0,05) e sul processo che rientra (0,03); segnali mobili uguali al calcolo esatto; serie con un buco rifiutata.
- `BasketReportTests`: il rapporto si scrive qualunque sia il verdetto; la tabella della replica conta le righe vincolanti; le gambe rimaste sole sono contate, anche quando sono zero; il termine di confronto è zero, mai «comprare e tenere»; numeri in italiano e nessun nome del prodotto originale.
- `BasketCommandTests`: `ABasketTrialRunsFromTheCommandLineWithItsPlanIntact` fa girare `anubis backtest baskets` senza rete sullo storico di prova, su SQLite e (nella CI) su PostgreSQL: il piano registrato è identico a quello costruito, con modo, costi, versione del motore e capitale; una seconda prova conta la prima; un piano manomesso nel registro (impronta cambiata, o griglia cambiata con un'impronta coerente) è rifiutato e la prova segnata come fallita. Senza lo storico BCE e con `--offline` il comando si ferma con un messaggio in italiano.
Scelte nell'ADR 0030. Rapporto: [`docs/backtests/basket_reversion.md`](backtests/basket_reversion.md).
## Fase 15 — Campionato: concorrenti e classifica
+10 -2
View File
@@ -4,7 +4,7 @@ Aggiornato: 2026-12-04
## Fase corrente
**Fase 13 — Campionato: unità di lavoro, piano e statistica: completata** sul branch `fase-13`, con la pull request aperta: unione in `main` e tag `fase-13` aspettano il sì dell'utente. Il giudice del campionato è pronto prima dei concorrenti: ogni prova del Laboratorio è fatta di unità che si riprendono dopo un'interruzione e girano su più operai, un campionato ha un piano immutabile con impronta e un tratto finale di dati che si legge una volta sola, e ogni finalista deve battere almeno 190 copie su 200 dei suoi prezzi senza regolarità. È provato su serie costruite apposta: nessun concorrente vero ha ancora gareggiato (Fase 15). Le Fasi 11 e 12 sono unite con i loro tag. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
**Fase 14 — Motore a panieri: completata** sul branch `fase-14`, con la pull request aperta: unione in `main` e tag `fase-14` aspettano il sì dell'utente. C'è un secondo motore di prova che sa vendere, usare la leva e fare più ingressi sulla stessa posizione, con i costi di eToro con data e fonte. Rifà i conti dell'appendice G del documento sui cambi BCE: 13 totali vincolanti su 13 dentro la tolleranza. La prima prova «come dal vivo» sulle 28 coppie BCE dal 1999 **non è superata** (netto a costi doppi −1.580,16 USD, Sharpe corretto 0,17): è il primo verdetto, su prezzi di riferimento giornalieri, ed è negativo come le misure del documento. È solo ricerca: la famiglia `basket_reversion` non manda ordini, nemmeno finti. Le Fasi 11, 12 e 13 sono unite con i loro tag. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca.
**Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023, applicato dalla Fase 11 con l'ADR 0027): notizie, calendario e trimestrali si misurano in ombra. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale.
@@ -161,13 +161,20 @@ Aggiornato: 2026-12-04
- Piano e tempi del campionato (#123, #125): piano immutabile con impronta, scritto con le prove dei concorrenti prima di ogni risultato; finalisti uno per gruppo e mercato, al più 8; tratto finale aperto una volta sola, solo per i finalisti; sette controlli tutti necessari. Combinazioni e prove di stress sono già nel piano e si eseguono nella Fase 16.
- Revisione indipendente con verifica a contraddittorio: 4 problemi confermati e corretti (un errore nel giudizio di un campionato fermava la coda del Laboratorio, unità riprese su dati o programma diversi, piano di un concorrente cambiato non controllato, una frase delle Impostazioni), 8 respinti; un quinto, trovato correggendo, è chiuso anch'esso: dati di ricerca cambiati tra la prova di un concorrente e il giudizio. Le correzioni hanno ciascuna una prova che falliva prima.
- **Fase 14 — Motore a panieri** (#127–#131, ADR 0030, nessun pacchetto nuovo; solo ricerca, nessun conto):
- Costi per sede (#128, `Backtest/VenueCosts.cs`): differenziali, leva massima, commissione e finanziamento per notte delle 28 coppie su eToro, dall'appendice A e dalla sezione 6.3 del documento (1 e 2 dicembre 2026); 16 coppie hanno il finanziamento stimato al costo più alto noto. Margine e stop obbligatorio delle tabelle 6.4 e 6.5; calendario delle notti (mercoledì tre, fine settimana zero); moltiplicatori 2× e 3×. I costi entrano nel piano e nella sua impronta.
- Replica dell'appendice G (#130, `Baskets/StylisedReplica.cs`): lo storico BCE fino al 2 dicembre 2026 è nei dati di prova con la sua impronta. Le convenzioni che il documento non scrive sono state trovate provando (z con la deviazione standard campionaria, σ con quella di popolazione, nessuna riapertura nella barra di chiusura): i 13 totali vincolanti stanno nella tolleranza, i due vicini a zero hanno il segno giusto. Costo di pareggio 1,2 sul processo che rientra, negativo su un cammino con deriva; controllo G.5 con quote 27–36% contro il 32–37% del documento.
- Motore a panieri (#127, `Backtest/BasketEngine.cs`, versione `basket-1`): conto a margine di ricerca in dollari, acquisti alla lettera e vendite al denaro, esecuzione all'apertura della barra dopo, stop obbligatorio, gamba rimasta sola chiusa subito dopo, chiusura d'ufficio, finanziamento, stop al 9% e cancello al 2%; modo «come dal vivo» con i limiti di SPEC 9.2 e del margine, modo «alla lettera» per la replica. In configurazione di confronto coincide con la replica su 200 serie.
- Famiglia `basket_reversion` (#129): un solo identificativo per tutte le sotto-varianti, generazioni A e B, segnali in pip o in logaritmi, profili Fedele e Prudente; il giudice delle prove la giudica con termine di confronto zero. Generazione C, altri segnali e cross tra monete passano alla Fase 15.
- Comando `anubis backtest baskets` (#131): replica, controllo G.5 e una prova registrata nel database con il piano controllato; scrive [`docs/backtests/basket_reversion.md`](backtests/basket_reversion.md) qualunque sia il verdetto. Due prove registrate sullo stesso database (la seconda dopo le correzioni della revisione, e conta la prima): 4 varianti ciascuna, non superata.
- Revisione indipendente con verifica a contraddittorio: 11 problemi confermati e corretti, nessuno che cambi il verdetto: la pausa dopo lo stop al 9% letta all'apertura invece che alla decisione, il tetto per valuta applicato anche alle mediazioni, la copia senza regolarità che spostava il prezzo medio di un differenziale con denaro e lettera veri, i livelli chiusi insieme allo stop obbligatorio senza un motivo loro, il finanziamento delle posizioni ancora aperte fuori dai costi del rapporto, la quota all'obiettivo che contava i panieri ancora aperti, tre etichette, due righe ripetute, un comando interrotto che lasciava la prova «in corso», una frase dell'ADR e un commento di prova. 3 segnalazioni respinte; una di queste, i separatori delle migliaia nei conteggi, è corretta lo stesso. Le correzioni hanno la loro prova.
## In corso
Nulla.
## Prossimo passo
1. Il sì dell'utente per unire la pull request della Fase 13 e mettere il tag `fase-13`. Poi la **Fase 14 — Motore a panieri**, in una nuova sessione, sul branch `fase-14` da `main`. Letture: la riga della Fase 14 nella tabella dell'ADR 0021 (punto 3), la Fase 14 del piano e gli ADR 0028 e 0029.
1. Il sì dell'utente per unire la pull request della Fase 14 e mettere il tag `fase-14`. Poi la **Fase 15 — Campionato: concorrenti e classifica**, in una nuova sessione, sul branch `fase-15` da `main`. Letture: la riga della Fase 15 nella tabella dell'ADR 0021 (punto 3), la Fase 15 del piano e gli ADR 0026, 0029 e 0030.
2. L'utente decide se pubblicare l'immagine (prossimo tag `v*`) e prova il template su Unraid seguendo `docs/MANUALE.md`.
3. Il rapporto della prova di durata (#55): si raccoglie dal container sul server di casa (48 ore a `--memory=2g`), si analizza, si salva in `docs/diagnostica/` e si chiude #55.
4. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa.
@@ -175,6 +182,7 @@ Nulla.
## Cosa resta debole
- **Nessuna strategia ha superato il backtest.** `crypto_trend` no (calo massimo del 32,8% contro il 25%; probabilità di sovra-adattamento 0,835 contro 0,40 su BTC, ETH e SOL); le due azionarie non sono ancora provate; la candidata crypto non ha superato il protocollo. Oggi il bot osserva e basta.
- **La prima prova del rientro tra strumenti non è superata** (ADR 0030): sui cambi BCE dal 1999, con i costi di eToro, solo una variante su quattro guadagna a costi normali (+506,72 USD in 28 anni su 20.000) e perde a costi doppi. I cambi BCE sono prezzi di riferimento: il verdetto che conta, a 15 minuti con denaro e lettera, aspetta i file a un minuto delle valute. Il finanziamento di 16 coppie su 28 è stimato.
- **I conti reali non esistono nel codice** e nessuna fase li prevede: creazione, chiavi, guardia e avvio sono da scrivere e provare.
- **Gli adapter non hanno mai parlato con un conto di prova vero**: la batteria di conformità passa solo sulle risposte d'esempio della documentazione. Ordini, stop, ricostruzione dopo un ripristino e codici di una chiave rifiutata vanno verificati dal vivo.
- **Crypto sempre nel simulatore interno**: manca la scelta per strategia tra simulatore e conto di prova (SPEC 7.1), quindi lo scostamento vero delle crypto non si può misurare.
+83
View File
@@ -0,0 +1,83 @@
# 0030 — Scelte della Fase 14 (motore a panieri, solo ricerca)
Data: 2026-12-04 · Stato: accettata · Applica gli ADR 0024, 0025 e 0026 al motore di prova · Precisa SPEC 12.1 e 12.2 · Nessun pacchetto nuovo
## Contesto
La Fase 14 costruisce il secondo motore di prova, quello che sa fare ciò che il primo non fa: vendite, leva, più ingressi sulla stessa posizione, panieri a una e a due gambe. È solo ricerca: nessun conto, nessun ordine, nemmeno finto. La prova che il motore funziona è che rifà i conti dell'appendice G del documento di ricerca. Il motore giornaliero (`BacktestEngine`, versione «2») non cambia, e le impronte dei piani di prova che esistono già non cambiano.
Il documento non dice tutto ciò che serve per rifare i suoi conti, e non dà il programma con cui li ha fatti. Le scelte qui sotto sono quelle che il codice ha dovuto fare. Dove una scelta è stata trovata provando, lo diciamo.
## Decisione
### Dati di prova (#130)
1. **Lo storico della BCE fino al 2 dicembre 2026** entra nei dati di prova, ridotto alle sette valute che servono (USD, JPY, GBP, CHF, AUD, CAD, NZD): `tests/Anubis.Tests/Fixtures/free/ecb-hist-1999-2026-12-02.csv`, 7.149 giorni dal 4 gennaio 1999, impronta SHA-256 `f298c1dc…b03fd8`. Un test controlla l'impronta. Nessun test usa la rete. Il file è stato scaricato una volta, con il tuo permesso, dal sito della BCE.
### Costi per sede (#128)
2. **Costi con data e fonte, copiati nel piano.** `VenueCosts` tiene per ogni coppia: differenziale nelle ore normali e nella pausa giornaliera, leva massima del conto reale, commissione per lato, finanziamento per notte in acquisto e in vendita. Per eToro i valori vengono dall'appendice A e dalla sezione 6.3 del documento (1 e 2 dicembre 2026). Il piano di una prova ne porta una copia, e la sua impronta entra nell'impronta del motore: se i costi cambiano, la prova è un'altra.
3. **Finanziamento delle coppie senza un valore nel documento**: 16 coppie su 28 usano, in acquisto e in vendita, il costo più alto tra quelli conosciuti, e sono segnate come «stimate». È la scelta prudente: il rapporto lo dice.
4. **Moltiplicatori 2× e 3×**: scalano insieme commissione, differenziale e finanziamento pagato. Un finanziamento a credito non cresce.
5. **Calendario del finanziamento**: una notte a ogni cambio di data del server (le 17 di New York) dal lunedì al venerdì; quella del mercoledì conta tre; il sabato e la domenica nessuna. Una posizione aperta il martedì e chiusa il venerdì paga cinque notti.
6. **Stop obbligatorio della sede**: al più a metà del margine della posizione (tabella 6.5). Un acquisto a leva 1 non ha stop obbligatorio, perché la posizione non può perdere più di quanto vale.
### Replica dell'appendice G (#130)
7. **`StylisedReplica` rifà il metodo G.3 alla lettera**: logaritmi dei prezzi di chiusura, ingresso e uscita sulla stessa chiusura, nessun costo, nessuna protezione del conto. Non è il motore e non dà verdetti: serve solo a confrontare i numeri.
8. **Convenzioni trovate provando.** Il documento non dice quale deviazione standard usa. Un prototipo ha provato le letture possibili; solo questa rifà tutti e quindici i totali della colonna «Forex 1999–2026», le altre ne sbagliano da 3 a 12:
- finestra di 100 barre che comprende la barra di oggi;
- lo z-score usa la deviazione standard campionaria (divisa per n − 1);
- σ è la deviazione standard di popolazione (divisa per n) delle 99 differenze dentro la stessa finestra, ed è fissata all'apertura del paniere;
- in ogni barra: se non c'è un paniere aperto e |z| ≥ 2 si apre contro lo scarto; altrimenti, la prima regola che vale tra stop, obiettivo (sulla media degli ingressi) e mediazione;
- nessuna riapertura nella barra in cui un paniere chiude;
- i panieri ancora aperti all'ultimo giorno valgono all'ultima chiusura.
9. **Risultato.** I 13 totali vincolanti stanno tutti nella loro tolleranza (stesso segno, scarto entro il 5% o entro 25 obiettivi). I due non vincolanti (−98 e −45 nel documento) hanno il segno giusto e uno scarto sotto i 3 obiettivi. Il criterio «in attesa dell'utente» del piano non serve.
10. **Costo di pareggio** sul processo costruito per rientrare (dimezzamento a 50 barre): circa 1,2 obiettivi (il documento dà 1,23). Su un cammino casuale con deriva è fortemente negativo.
11. **Controllo contro il caso (G.5)**: un segno per giorno, lo stesso per tutte le serie, non centrato (le vendite ci sono). Sui cammini casuali la quota «pari o migliori» ha media circa 0,5; sul processo che rientra sta sotto 0,05.
12. **Segnali mobili comuni.** `RollingZ` e `RollingSigma` (in `BasketIndex`) sono usati sia dalla replica sia dal motore, così i due coincidono al bit. Una serie con un buco è rifiutata.
### Motore a panieri (#127)
13. **Un conto a margine di ricerca, in dollari.** Posizioni indipendenti, una per gamba e per livello; acquisti alla lettera, vendite al denaro; margine = esposizione / leva; leva = la minore tra quella del piano (5) e quella della coppia. Il lotto si fissa sul capitale iniziale e non cresce mai dentro un paniere. Decisione sulla barra chiusa, esecuzione all'apertura della barra dopo. Con i cambi BCE (un prezzo al giorno) vuol dire: si decide sul prezzo di oggi e si esegue su quello di domani, con il differenziale della tabella dei costi attorno al prezzo di riferimento.
14. **Regole della sede.** Stop obbligatorio su ogni posizione alla distanza massima; se il prezzo lo salta, si chiude all'apertura. **Gamba rimasta sola**: quando lo stop obbligatorio chiude una gamba di un paniere a due gambe, il resto del paniere si chiude all'esecuzione dopo, con il motivo `orphan_leg`. Il documento non lo dice: è la via prudente, e il rapporto conta queste gambe. In un paniere a un solo simbolo, quando lo stop obbligatorio ferma un livello, anche gli altri livelli si chiudono all'esecuzione dopo, con il motivo `closed_with_stop`: la scala delle mediazioni è rotta, e tenerli aperti lascerebbe un paniere che nessuna regola ha previsto. **Chiusura d'ufficio** di tutto quando il valore del conto scende sotto la metà del margine iniziale delle posizioni aperte. Finanziamento a ogni notte attraversata, sull'esposizione d'ingresso, addebitato subito alla cassa; commissione su apertura e chiusura.
15. **Regole del documento, in tutti e due i modi**: stop sul valore del conto al 9% (si chiude tutto all'esecuzione dopo, e niente panieri nuovi né mediazioni fino al cambio di data del server, confrontato con il momento della decisione: sulle barre giornaliere la decisione del giorno dopo è già nel giorno nuovo); cancello del 2% (niente panieri nuovi, le mediazioni proseguono); massimo di panieri aperti; filtro `Rvol` (sopra 2 niente ingressi; sulle barre giornaliere 16 barre contro 20); correlazione almeno 0,6 nel verso atteso per le unità a due gambe. Sulle barre di un giorno o più le finestre orarie (fine settimana, sessione, pausa giornaliera) non valgono.
16. **Modo «come dal vivo»** (`come_dal_vivo`), l'unico che dà verdetti: in più i limiti di SPEC 9.2 sull'indice del patrimonio a prezzi di mercato (−2% in un giorno: 24 ore senza panieri nuovi **e senza mediazioni**; −5% in una settimana e −10% dal massimo: metà dimensione ciascuno, un quarto insieme, e un livello sotto il minimo della sede non parte; −15%: interruttore, con ripartenza supposta dopo 7 giorni come nell'ADR 0011); margine impegnato al più 40% del patrimonio; al più 9 posizioni aperte (conto Demo condiviso, piano §9); mai posizioni opposte sullo stesso strumento; esposizione netta per valuta al più 2 ingressi, controllata solo sui panieri nuovi e mai sulle mediazioni di un paniere aperto (Prudente scarta, Fedele registra); stop di paniere del profilo Prudente. La base del giorno per il −2% è il punto di patrimonio precedente, cioè il giorno del motore. Le uscite continuano anche a interruttore scattato.
17. **Modo «alla lettera»** (`alla_lettera`): solo le regole del documento. Serve alla replica e agli esperimenti, non produce verdetti.
18. **Configurazione di confronto**: un simbolo solo, logaritmi, σ, uscita sulla media degli ingressi, esecuzione sulla stessa chiusura, nessun costo, nessuna protezione. Su 200 serie a seme fisso il motore così configurato dà gli stessi panieri della replica e lo stesso totale entro 1e-9. Serve solo a questa verifica.
19. **Un punto di patrimonio per giorno**, per ogni variante, sugli stessi giorni: la data UTC per le barre di un giorno, il giorno del server per le barre più corte. 260 punti per anno (calendario delle valute). Le posizioni aperte valgono ai prezzi di mercato: una perdita aperta si vede subito nei rendimenti.
20. **Codici motivo**: uscite `target`, `stop_basket`, `account_stop`, `mandatory_stop`, `orphan_leg`, `liquidation`, `end` (ancora aperto alla fine); rifiuti e note `gate_open_loss`, `paused_until_next_day`, `daily_loss_block`, `half_size`, `below_venue_minimum`, `margin_limit`, `max_positions`, `opposite_position`, `currency_exposure`, `cost_rule`, `rvol_filter`, `correlation_low`, `switch_tripped`, `max_open_baskets`, `clock_window`; chiusura di un livello insieme a quello fermato dallo stop obbligatorio, `closed_with_stop`. Ognuno ha la sua frase in italiano. Il limite di posizioni ha il codice `max_positions` e non `position_limit`, perché quel codice esiste già con la frase del motore giornaliero. Un rifiuto si scrive una volta per ogni periodo in cui dura lo stesso motivo, non a ogni barra.
21. **Versione `basket-1`**, scritta nel campo `Engine` del piano. L'impronta del motore comprende quella dei dati, la versione, l'impronta dei costi e il modo.
### Famiglia `basket_reversion` (#129)
22. **Un solo identificativo per tutte le sotto-varianti**, così il registro delle prove conta ogni tentativo. È solo una famiglia di ricerca: non è in `StrategyCatalog`, non ha un codice d'ordine.
23. **Assi della griglia**: generazione (A: i cinque spread documentati; B: i dieci simboli), segnale (somma dei pip o logaritmi), unità (pip o σ), obiettivo, distanza, crescita, mediazioni, finestra, z d'ingresso, regola d'uscita (somma dei pip o media degli ingressi), profilo (Fedele o Prudente), panieri aperti, lotto. Gli assi a scelta sono segnati come tali: la regola dell'altopiano non li media mai.
24. **Regola dei tre costi**: l'obiettivo deve valere almeno tre volte il costo di andata e ritorno del paniere. Prudente rifiuta l'ingresso, Fedele lo registra soltanto (ADR 0028 punto 15).
25. **Il cancello delle notizie del documento resta spento**: è una variante della Fase 17.
26. **Rimandato alla Fase 15**: la misura sui cross diretti tra monete contro l'inventario fermo, la generazione C e gli altri segnali. La Fase 15 porta il resto della famiglia con lo stesso identificativo.
### Comando e rapporto (#131)
27. **`anubis backtest baskets`** carica i sette cambi BCE (stessa copia e stessa regola di scaricamento di `anubis data ecb`), ne ricava le 28 coppie e fa tre cose: la replica dell'appendice G sui dati fino al 2 dicembre 2026; il controllo G.5 sulle quattro righe «Forex 1999–2026» del documento (le altre nove righe della tabella usano dati che qui non ci sono); una prova del motore «come dal vivo» con i costi di eToro, registrata e giudicata come ogni altra prova (piano con impronta, conteggio comune delle prove precedenti). Scrive `docs/backtests/basket_reversion.md` **qualunque sia il verdetto**.
28. **La griglia della prova**, scritta prima di ogni risultato: generazione A e B, distanza 4 e 10 σ, obiettivo 2,5 σ, 3 mediazioni, logaritmi, uscita sulla media degli ingressi, finestra 100, z d'ingresso 2, profilo Fedele, 2 panieri aperti, 0,01 lotti ogni 10.000, capitale virtuale 20.000 USD. Quattro varianti.
29. **Termine di confronto**: zero, cioè nessuna operazione (ADR 0026 punto 5). Mai «comprare e tenere».
30. **La quota di panieri chiusi all'obiettivo** è mostrata e non entra mai nel giudizio: la replica chiude all'obiettivo quasi tutti i panieri anche su serie senza alcuna tendenza a rientrare.
31. **Il piano si controlla prima di partire.** Il comando scrive il piano, lo rilegge e parte solo se il piano registrato dà ancora la sua impronta ed è quello appena scritto. Rifare la stessa prova è ammesso: è una prova nuova, e quelle prima contano nello Sharpe corretto. Una prova interrotta (Ctrl+C o arresto del container) o fallita è segnata come fallita con il motivo, e il rapporto di prima resta; il Laboratorio non la riprende.
32. **I costi del rapporto** sono commissioni e finanziamento pagati, compreso il finanziamento già addebitato alle posizioni ancora aperte alla fine. Il differenziale è già nei prezzi di acquisto e di vendita, e il rapporto lo dice.
33. **Nessun file d'esito** (`.outcome.json`) per i panieri in questa fase: il bot non deve leggere niente di questa famiglia, perché non ha ordini.
## Alternative scartate
- **Stessa deviazione standard per z e σ**: sbaglia 4 righe su 15 dell'appendice G. Le altre letture provate (stop sul conto, riapertura nella stessa barra, stop in unità di σ, σ corrente invece che fissata, z senza la barra di oggi) sbagliano di più.
- **Lasciare la gamba sola aperta finché non arriva il suo obiettivo**: il documento non lo dice, e una gamba sola è un'esposizione che nessuno ha deciso.
- **Finanziamento zero per le coppie senza valore**: farebbe sembrare migliori proprio le coppie che non conosciamo.
- **Dare verdetti anche dal modo «alla lettera»**: non ha i limiti che varrebbero dal vivo, quindi il suo risultato non è quello che si avrebbe.
- **Scrivere il motore dentro quello giornaliero**: è anche la funzione con cui il bot decide dal vivo, e i suoi esiti pubblicati portano la versione «2».
## Conseguenze
- I cambi BCE sono prezzi di riferimento, non prezzi a cui si negozia: la prova su di essi è una scrematura. Il verdetto che conta, a 15 minuti con denaro e lettera, aspetta i tuoi file a 1 minuto.
- I costi sono quelli del 1 e 2 dicembre 2026 e possono invecchiare: il bot non legge il conto reale.
- Le Fasi 15 e 16 trovano il motore pronto: il campionato può mettere in gara le varianti del rientro tra strumenti con le stesse regole e lo stesso giudice delle altre strategie.
- La Fase 18 riusa le regole della sede e i limiti scritti qui per il simulatore a margine dal vivo.
+212
View File
@@ -0,0 +1,212 @@
# 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,17, serve ≥ 0,9.
Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).
Calcolato il 2026-12-04 con la versione basket-1 del motore a panieri e la versione 1 della famiglia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.
Per rifarlo: `anubis backtest baskets --to 2026-11-30`.
## Dati
- Cambi di riferimento della BCE: 7 valute contro l'euro (GBP, AUD, NZD, USD, CAD, CHF, JPY), da cui 28 coppie incrociate. Fonte: Banca centrale europea, cambi di riferimento (eurofxref-hist.zip, conservato nella cartella di ricerca).
- Periodo: dal 04/01/1999 al 04/12/2026, 7.151 giorni con il cambio. Impronta dei dati `1c01c649c7af`.
- La replica dell'appendice G usa i dati fino al 02/12/2026, la fine del documento.
- I cambi della BCE sono prezzi di riferimento, uno al giorno: non sono prezzi a cui si possa comprare o vendere. La prova decide sul cambio di oggi ed esegue su quello di domani, con il differenziale della tabella dei costi.
- Costi: eToro, letti il 02/12/2026. Fonte: Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026
- Minimo 1.000 USD per posizione, leva 5 per posizione, mai oltre quella del conto reale.
- Il finanziamento notturno di 16 coppie su 28 non è nel documento: per prudenza pagano, su entrambi i lati, il costo più alto tra quelli noti. Sono segnate come stimate nella tabella.
**Tabella dei costi** (differenziale in pip; finanziamento in USD per 100.000 USD di esposizione a notte, positivo se si paga)
| Coppia | Differenziale | In pausa | Leva massima | Commissione per lato | Finanziamento acquisto | Finanziamento vendita | Finanziamento |
|---|---:|---:|---:|---:|---:|---:|---|
| EURGBP | 0,4 | 2,3 | 30 | 0,005% | +7,92 | −0,36 | dal documento |
| EURAUD | 1,1 | 8,3 | 20 | 0,005% | +10,37 | −2,745 | dal documento |
| EURNZD | 4,3 | 16,8 | 20 | 0,005% | +4,65 | +3,7 | dal documento |
| EURUSD | 0,1 | 2,2 | 30 | 0,005% | +8,096 | −0,46 | dal documento |
| EURCAD | 0,9 | 8,4 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| EURCHF | 0,2 | 7,5 | 30 | 0,005% | −3,597 | +11,336 | dal documento |
| EURJPY | 1,6 | 11,2 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| GBPAUD | 1,2 | 14,9 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| GBPNZD | 8,3 | 25 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| GBPUSD | 0,2 | 2,3 | 30 | 0,005% | +3,927 | +3,696 | dal documento |
| GBPCAD | 2 | 11 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| GBPCHF | 1 | 23,3 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| GBPJPY | 0,9 | 14,8 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| AUDNZD | 0,8 | 6,9 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| AUDUSD | 0,1 | 2,1 | 20 | 0,005% | +1,51 | +6,191 | dal documento |
| AUDCAD | 1 | 7,1 | 20 | 0,005% | −3,074 | +10,812 | dal documento |
| AUDCHF | 0,9 | 13,5 | 20 | 0,005% | −10,324 | +17,978 | dal documento |
| AUDJPY | 0,7 | 7 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| NZDUSD | 0,1 | 2,8 | 20 | 0,005% | +8,14 | +0,37 | dal documento |
| NZDCAD | 1,6 | 7,3 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| NZDCHF | 1 | 12,2 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| NZDJPY | 1,6 | 9,8 | 20 | 0,005% | +17,978 | +17,978 | stimato |
| USDCAD | 0,3 | 4,2 | 30 | 0,005% | −0,77 | +8,33 | dal documento |
| USDCHF | 0,1 | 11,2 | 30 | 0,005% | −7,788 | +15,458 | dal documento |
| USDJPY | 0,3 | 5,8 | 30 | 0,002% | +17,978 | +17,978 | stimato |
| CADCHF | 0,8 | 11,6 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| CADJPY | 0,8 | 10,7 | 30 | 0,005% | +17,978 | +17,978 | stimato |
| CHFJPY | 1,7 | 58,4 | 30 | 0,005% | +17,978 | +17,978 | stimato |
## Replica dell'appendice G
La replica segue alla lettera il metodo G.3 del documento di ricerca: ognuna delle coppie da sola, sui logaritmi dei prezzi, ingresso e uscita sulla stessa chiusura, nessun costo e nessuna regola del conto. Non è il motore a panieri e non dà nessun giudizio: dice solo se i numeri del documento si ritrovano sugli stessi dati. I risultati sono in obiettivi (un obiettivo è la distanza del take profit).
| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |
|---|---|---:|---:|---:|---:|---|---|
| 2,5 σ · 10 σ · 3 | nessuno | 534 | 535,5 | +1,5 | ±26,7 | sì | dentro |
| 2,5 σ · 10 σ · 3 | 90 obiettivi | 542 | 543,7 | +1,7 | ±27,1 | sì | dentro |
| 2,5 σ · 10 σ · 3 | 30 obiettivi | 255 | 257,2 | +2,2 | ±25 | sì | dentro |
| 2 σ · 8 σ · 3 | nessuno | 757 | 753,6 | −3,4 | ±37,9 | sì | dentro |
| 2 σ · 8 σ · 3 | 90 obiettivi | 1.032 | 1.029,1 | −2,9 | ±51,6 | sì | dentro |
| 2 σ · 8 σ · 3 | 30 obiettivi | −98 | −100,8 | −2,8 | ±25 | no | solo riportata |
| 3 σ · 12 σ · 3 | nessuno | 338 | 340,1 | +2,1 | ±25 | sì | dentro |
| 3 σ · 12 σ · 3 | 90 obiettivi | 534 | 536,3 | +2,3 | ±26,7 | sì | dentro |
| 3 σ · 12 σ · 3 | 30 obiettivi | 137 | 138,4 | +1,4 | ±25 | sì | dentro |
| 2,5 σ · 4 σ · 3 | nessuno | 649 | 647,1 | −1,9 | ±32,5 | sì | dentro |
| 2,5 σ · 4 σ · 3 | 90 obiettivi | 442 | 439,5 | −2,5 | ±25 | sì | dentro |
| 2,5 σ · 4 σ · 3 | 30 obiettivi | −45 | −47,4 | −2,4 | ±25 | no | solo riportata |
| 2,5 σ · 4 σ crescente · 4 | nessuno | 533 | 531,3 | −1,7 | ±26,7 | sì | dentro |
| 2,5 σ · 4 σ crescente · 4 | 90 obiettivi | 759 | 757,4 | −1,6 | ±38 | sì | dentro |
| 2,5 σ · 4 σ crescente · 4 | 30 obiettivi | 172 | 169,9 | −2,1 | ±25 | sì | dentro |
13 righe vincolanti su 13 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.
Solo riportate, perché vicine allo zero: 2 σ · 8 σ · 3 con stop di 30 obiettivi, documento −98, Anubis −100,8 (stesso segno); 2,5 σ · 4 σ · 3 con stop di 30 obiettivi, documento −45, Anubis −47,4 (stesso segno).
| Obiettivo · distanza · mediazioni | Stop | Pareggio del documento | Pareggio di Anubis | Posizioni | Panieri | Chiusi all'obiettivo |
|---|---|---:|---:|---:|---:|---:|
| 2,5 σ · 10 σ · 3 | nessuno | +0,32 | +0,32 | 1.675 | 1.259 | 97,9% |
| 2,5 σ · 10 σ · 3 | 90 obiettivi | +0,26 | +0,27 | 2.047 | 1.543 | 97,1% |
| 2,5 σ · 10 σ · 3 | 30 obiettivi | +0,11 | +0,11 | 2.390 | 1.788 | 94,6% |
| 2 σ · 8 σ · 3 | nessuno | +0,39 | +0,39 | 1.953 | 1.467 | 98,4% |
| 2 σ · 8 σ · 3 | 90 obiettivi | +0,40 | +0,40 | 2.583 | 1.929 | 97,8% |
| 2 σ · 8 σ · 3 | 30 obiettivi | −0,03 | −0,03 | 2.937 | 2.186 | 94,4% |
| 3 σ · 12 σ · 3 | nessuno | +0,24 | +0,24 | 1.424 | 1.066 | 97,5% |
| 3 σ · 12 σ · 3 | 90 obiettivi | +0,33 | +0,33 | 1.641 | 1.223 | 97,0% |
| 3 σ · 12 σ · 3 | 30 obiettivi | +0,07 | +0,07 | 1.936 | 1.447 | 94,3% |
| 2,5 σ · 4 σ · 3 | nessuno | +0,33 | +0,33 | 1.977 | 1.167 | 97,8% |
| 2,5 σ · 4 σ · 3 | 90 obiettivi | +0,16 | +0,16 | 2.702 | 1.590 | 96,9% |
| 2,5 σ · 4 σ · 3 | 30 obiettivi | −0,01 | −0,01 | 3.650 | 2.166 | 93,2% |
| 2,5 σ · 4 σ crescente · 4 | nessuno | +0,25 | +0,25 | 2.133 | 1.273 | 97,9% |
| 2,5 σ · 4 σ crescente · 4 | 90 obiettivi | +0,25 | +0,25 | 3.010 | 1.796 | 97,2% |
| 2,5 σ · 4 σ crescente · 4 | 30 obiettivi | +0,05 | +0,05 | 3.455 | 2.109 | 93,7% |
Il pareggio è il costo per posizione, in obiettivi, che porterebbe il totale a zero: totale diviso posizioni. La quota di panieri chiusi all'obiettivo è mostrata e mai giudicata: alta com'è, non prova nulla sul guadagno.
## Controllo contro il caso (G.5)
Ogni giorno le variazioni di tutte le coppie cambiano segno insieme con probabilità un mezzo: restano volatilità, code e legami tra le coppie, sparisce ogni tendenza a rientrare o a proseguire. Poi la replica gira di nuovo sulle serie ricostruite. Si conta quante volte il pareggio delle serie rimescolate è pari o migliore di quello osservato.
| Obiettivo · distanza · mediazioni | Stop | Ripetizioni | Seme | Pareggio osservato | Mediana rimescolate | 5°–95° percentile | Pari o migliori: Anubis | Pari o migliori: documento |
|---|---|---:|---:|---:|---:|---:|---:|---:|
| 2,5 σ · 10 σ · 3 | nessuno | 150 | 20261202 | +0,32 | +0,10 | −1,95; +0,81 | 36,0% | 37% |
| 2,5 σ · 10 σ · 3 | 90 obiettivi | 150 | 20261202 | +0,27 | +0,03 | −0,89; +0,65 | 26,7% | 33% |
| 2,5 σ · 4 σ · 3 | nessuno | 150 | 20261202 | +0,33 | −0,03 | −1,81; +0,77 | 34,7% | 33% |
| 2,5 σ · 4 σ · 3 | 90 obiettivi | 150 | 20261202 | +0,16 | +0,02 | −0,73; +0,56 | 31,3% | 32% |
Una quota alta vuol dire che il risultato osservato è uno dei tanti che il caso produce da solo. Il documento ha fatto 150 ripetizioni per riga, senza dire il seme.
## Prova del motore a panieri
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 `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,17 | 0,15 | non superata |
Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni né perdite.
| | Strategia | Zero (nessuna operazione) |
|---|---:|---:|
| Risultato netto | 506,72 USD | 0,00 USD |
| Rendimento totale | 2,5% | 0,0% |
| Rendimento annuo | 0,1% | 0,0% |
| Volatilità annua | 1,8% | 0,0% |
| Calo massimo | −12,0% | 0,0% |
| Sharpe annuo | 0,06 | 0,00 |
| Commissioni e finanziamento pagati (il differenziale è già nei prezzi) | 1.716,72 USD | 0,00 USD |
**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 |
|---|---:|---:|---:|---:|
| ×1 | 506,72 USD | 2,5% | 0,06 | −12,0% |
| ×2 | −1.580,16 USD | −7,9% | −0,20 | −13,5% |
| ×3 | −3.345,01 USD | −16,7% | −0,41 | −19,5% |
**Convalide**
- 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,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,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 |
**Varianti della griglia**
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo |
|---|---:|---:|---:|---:|
| `averagings=3;distance=4;entry_z=2;exit=2;generation=1;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | −0,25 | −0,29 | −2.595,52 USD | −14,9% |
| `averagings=3;distance=10;entry_z=2;exit=2;generation=1;growth=1;lot=0.01;max_open=2;profile=1;signal=2;target=2.5;units=2;window=100` | −0,34 | −0,34 | −2.512,22 USD | −13,9% |
| `averagings=3;distance=4;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,08 | −0,08 | −1.213,13 USD | −13,3% |
| `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` (scelta) | 0,06 | −0,01 | 506,72 USD | −12,0% |
**Panieri**
Panieri della variante giudicata: 266.
| Uscita | Panieri |
|---|---:|
| obiettivo raggiunto | 242 |
| stop obbligatorio della piattaforma | 22 |
| ancora aperto alla fine (valutato agli ultimi prezzi) | 2 |
Chiusi all'obiettivo: 91,7% dei panieri chiusi. La quota è mostrata e mai giudicata.
- 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**
Con il profilo Fedele la regola dei tre costi e il limite di esposizione per valuta sono solo annotati: l'ingresso si fa lo stesso. Una dimensione dimezzata è un ingresso fatto più piccolo.
| Motivo | Volte |
|---|---:|
| 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
- I prezzi della BCE sono cambi di riferimento, non prezzi a cui si compra o si vende: denaro e lettera sono ricostruiti attorno al cambio con il differenziale della tabella dei costi.
- Costi di eToro al 2 dicembre 2026: Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026.
- Il finanziamento notturno delle coppie che il documento non dà è stimato con prudenza: il costo più alto fra quelli noti, sui due lati.
- Si decide sul cambio di chiusura di un giorno e si esegue su quello del giorno dopo; le finestre orarie (fine settimana, sessione, pausa giornaliera) su barre giornaliere non valgono.
- Il conto non viene letto: margine, stop obbligatorio della piattaforma, chiusura d'ufficio sotto metà del margine e finanziamento con il mercoledì triplo sono simulati con le regole della sede.
- Modalità «come dal vivo»: regole del documento più i limiti di rischio (perdita del giorno, della settimana, calo dal massimo) e del margine; se scatta l'interruttore supponiamo che tu riparta dopo sette giorni.
- 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.
- Mancano ancora i dati a 15 minuti: il giudizio che conta richiede i file a 1 minuto forniti dall'utente.
+11 -3
View File
@@ -15,17 +15,25 @@ namespace Anubis.Server;
/// them to euro, runs the protocol of <c>crypto_trend</c> on both universes and writes reports and outcome files.
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
/// "anubis backtest candidates" does the same for the candidates of SPEC 8.4 and leaves the other files alone.
/// "anubis backtest baskets" is the basket family's: <see cref="BasketCommand"/>.
/// </summary>
internal static class BacktestCommand
{
private const string Usage =
"Uso: anubis backtest base|candidates [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]";
internal const string Usage =
"Uso: anubis backtest base|candidates|baskets [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--data-dir <cartella>, obbligatoria fuori dal container]\n" +
" baskets [--control 150] [--seed 20261202]: replica dell'appendice G, controllo contro il caso e prova del motore a panieri sui cambi BCE,\n" +
" registrata nel database (avvia prima il server una volta). Con --offline usa solo lo storico BCE già scaricato e si ferma se manca.";
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
HttpMessageHandler? handler = null)
{
output ??= Console.Out;
if (args.Length >= 1 && args[0] == "baskets")
{
return await BasketCommand.RunAsync(args[1..], output, environment, handler).ConfigureAwait(false);
}
if (args.Length < 1 || args[0] is not ("base" or "candidates"))
{
await output.WriteLineAsync(Usage).ConfigureAwait(false);
+254
View File
@@ -0,0 +1,254 @@
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Strategies;
namespace Anubis.Server;
/// <summary>
/// "anubis backtest baskets" (Phase 14, issue #131): the replica of appendix G of the research document on the 28 ECB
/// crosses, the control against chance of G.5 and the trial of the basket engine «come dal vivo» with the eToro costs
/// (<see cref="BasketProtocol"/>). The trial is planned in the configured database before it runs, read back and run only if
/// its stored plan is the one just written, judged with every earlier trial of the family counted, and recorded. The report
/// <c>basket_reversion.md</c> is written whatever the verdict; there is no outcome file for the family.
/// </summary>
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, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(output);
clock ??= new SystemClock();
var rest = args.ToList();
var offline = rest.Remove("--offline");
var own = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var name in new[] { "--to", "--out", "--control", "--seed" })
{
var index = rest.IndexOf(name);
if (index < 0)
{
continue;
}
if (index == rest.Count - 1)
{
return await UsageAsync(output, $"Manca il valore di {name}.").ConfigureAwait(false);
}
own[name] = rest[index + 1];
rest.RemoveRange(index, 2);
}
var now = clock.UtcNow;
DateOnly to;
if (own.TryGetValue("--to", out var t))
{
if (!DateOnly.TryParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out to))
{
return await UsageAsync(output, "--to vuole una data AAAA-MM-GG.").ConfigureAwait(false);
}
}
else
{
to = new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last day of the previous month.
}
var repetitions = BasketProtocol.ControlRepetitions;
if (own.TryGetValue("--control", out var c) && (!int.TryParse(c, NumberStyles.None, CultureInfo.InvariantCulture, out repetitions) || repetitions < 1))
{
return await UsageAsync(output, "--control vuole un numero intero di ripetizioni, almeno 1.").ConfigureAwait(false);
}
var seed = BasketProtocol.ControlSeed;
if (own.TryGetValue("--seed", out var s) && !int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out seed))
{
return await UsageAsync(output, "--seed vuole un numero intero.").ConfigureAwait(false);
}
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 outDir = Path.GetFullPath(own.GetValueOrDefault("--out") ?? Path.Combine("docs", "backtests"));
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false);
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);
db = Database.Open(config.Db!, allowCreate: false);
config.Data.Ensure();
Directory.CreateDirectory(outDir);
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,
$"Cambi BCE: {EcbCrosses.Rates.Count} valute, {notes.Pairs} coppie, {notes.Days} giorni, dal {notes.First:yyyy-MM-dd} al {notes.Last:yyyy-MM-dd}.")).ConfigureAwait(false);
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}%)"))}."))
.ConfigureAwait(false);
var (plan, variants) = BasketProtocol.Plan(to, now);
var data = BasketProtocol.Dataset(crosses, to);
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))
{
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, 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())
? "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."
: null;
if (refusal is not null)
{
return await RefuseAsync(refusal).ConfigureAwait(false);
}
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)), 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 (OperationCanceledException) when (interrupted.IsCancellationRequested)
{
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, CancellationToken cancellationToken)
{
if (offline && !File.Exists(Ecb.HistoryPath(research)))
{
throw new InvalidOperationException($"Manca lo storico dei cambi BCE già scaricato ({Ecb.HistoryPath(research)}): togli --offline o esegui prima «anubis data ecb».");
}
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).ConfigureAwait(false);
if (rates.Count == 0)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
}
await output.WriteLineAsync(offline ? "Storico BCE letto dalla copia già scaricata." : "Storico BCE scaricato di nuovo.").ConfigureAwait(false);
return rates;
}
private static DateOnly Earlier(DateOnly a, DateOnly b) => a < b ? a : b;
private static async Task<int> UsageAsync(TextWriter output, string problem)
{
await output.WriteLineAsync(problem).ConfigureAwait(false);
await output.WriteLineAsync(BacktestCommand.Usage).ConfigureAwait(false);
return 2;
}
}
+165
View File
@@ -0,0 +1,165 @@
using System.Collections.Concurrent;
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// Why a basket closed and why a decision was refused or noted (<see cref="BacktestNote.Reason"/>,
/// <see cref="BacktestBasket.ExitReason"/>, <see cref="BasketEvent.Reason"/>): the report counts them.
/// </summary>
public static class BasketReasons
{
// Exits.
public const string Target = "target";
/// <summary>The Prudente basket stop, or the replica's stop in targets in the comparison configuration.</summary>
public const string StopBasket = "stop_basket";
/// <summary>The 9% stop on the open loss over the balance: everything closes.</summary>
public const string AccountStop = "account_stop";
/// <summary>The venue's stop on one position, at most at half its margin.</summary>
public const string MandatoryStop = "mandatory_stop";
/// <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";
/// <summary>Still open at the end of the data, valued at the last marks.</summary>
public const string End = "end";
// Refusals and notes.
public const string GateOpenLoss = "gate_open_loss";
public const string PausedUntilNextDay = "paused_until_next_day";
public const string DailyLossBlock = "daily_loss_block";
public const string HalfSize = "half_size";
public const string BelowVenueMinimum = "below_venue_minimum";
public const string MarginLimit = "margin_limit";
/// <summary>Nine positions open on the account (plan, section 9): not the daily engine's position_limit, a weight cap.</summary>
public const string PositionLimit = "max_positions";
public const string OppositePosition = "opposite_position";
public const string CurrencyExposure = "currency_exposure";
public const string CostRule = "cost_rule";
public const string RvolFilter = "rvol_filter";
public const string CorrelationLow = "correlation_low";
public const string SwitchTripped = "switch_tripped";
public const string MaxOpenBaskets = "max_open_baskets";
/// <summary>The weekend, the daily pause or the hourly window, on bars shorter than a day.</summary>
public const string ClockWindow = "clock_window";
}
/// <summary>The kinds of <see cref="BasketEvent"/>.</summary>
public static class BasketEventKinds
{
public const string Open = "open";
public const string Add = "add";
public const string Close = "close";
public const string Refused = "refused";
/// <summary>Something written down without changing the decision (Fedele's cost rule, a halved size).</summary>
public const string Note = "note";
}
/// <summary>
/// A decision of the engine on a closed bar: an opening, an averaging, a close and why, a refusal and why. Only what the data
/// up to <see cref="At"/> allows: the look-ahead check compares them on cut data.
/// </summary>
public sealed record BasketEvent(DateTimeOffset At, DateOnly Day, string Unit, string Kind, string Reason, int Direction);
/// <summary>
/// One position of a basket from its fill to its exit: the level (0 the first), pair, side, units, the market bar, moment and
/// price of the fill and of the exit (the last mark for one still open), why it closed, commission and financing paid (USD,
/// negative financing a credit) and the result net of both.
/// </summary>
public sealed record BasketPositionTrace(
int Level,
string Pair,
Direction Side,
decimal Units,
int EntryBar,
DateTimeOffset EntryAt,
decimal EntryPrice,
int? ExitBar,
DateTimeOffset? ExitAt,
decimal? ExitPrice,
string ExitReason,
decimal Commission,
decimal Financing,
decimal Result);
/// <summary>
/// The trace of one basket: unit, direction (+1 bought, −1 sold), the σ of the index frozen at the opening (in the index's
/// units: pips, or basis points of the log index), every position, the bar of the last exit (null when still open at the end)
/// and the reason. A test computes the basket's result from it, fill by fill.
/// </summary>
public sealed record BasketTrace(int Id, string Unit, int Direction, double Sigma, IReadOnlyList<BasketPositionTrace> Positions, int? ExitBar, string ExitReason)
{
public int Levels => Positions.Select(p => p.Level).Distinct().Count();
}
/// <summary>
/// A run of the basket engine: the run the judge reads, the trace of every basket, the decisions, and the commission and
/// financing paid in USD (financing net of credits).
/// </summary>
public sealed record BasketRunResult(BacktestRun Run, IReadOnlyList<BasketTrace> Traces, IReadOnlyList<BasketEvent> Events, decimal Commission, decimal Financing);
/// <summary>
/// The basket engine of Phase 14 (issue #127): a research margin account in USD with independent positions, one per leg and
/// per level, on the bars of a <see cref="BasketMarket"/>. A decision is taken on a closed bar and executed at the next bar's
/// open, buying at the ask and selling at the bid; every position has the venue's mandatory stop, pays commission on both
/// sides and financing at every rollover crossed (Wednesday's counts three); the venue liquidates the account below half the
/// initial margin. On top, the document's rules (9% account stop on mid prices in the daily pause, 2% gate, open baskets,
/// Rvol, correlation, three-costs rule) and, «come dal vivo», SPEC 9.2 and the margin table of the plan. One equity point a
/// day. Pure: no database, no clock, no input or output; one instance may run many rules at once.
/// </summary>
public sealed class BasketEngine
{
/// <summary>Changes when the engine computes differently: basket plans record it in their <c>engine</c> field.</summary>
public const string Version = "basket-1";
/// <summary>The symbol of the notes about the whole account (account stop, liquidation).</summary>
public const string AccountSymbol = "conto";
private readonly ConcurrentDictionary<string, Lazy<object>> _cache = new(StringComparer.Ordinal);
public BasketEngine(BasketMarket market, VenueCosts costs, decimal initialCapital)
{
ArgumentNullException.ThrowIfNull(market);
ArgumentNullException.ThrowIfNull(costs);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(initialCapital);
Market = market;
Costs = costs;
InitialCapital = initialCapital;
}
public BasketMarket Market { get; }
public VenueCosts Costs { get; }
public decimal InitialCapital { get; }
/// <summary>
/// One run of <paramref name="rules"/> with costs multiplied by <paramref name="costMultiplier"/> (spread, commission and
/// financing paid), trading and measuring the days from <paramref name="from"/> to <paramref name="to"/> (both included;
/// null: the whole market). Bars before <paramref name="from"/> only warm the signals up.
/// </summary>
public BasketRunResult Run(BasketRules rules, decimal costMultiplier = 1m, DateOnly? from = null, DateOnly? to = null)
{
ArgumentNullException.ThrowIfNull(rules);
rules.Validate();
return new BasketSimulation(this, rules, costMultiplier, from, to).Run();
}
/// <summary>A value computed once per engine and key (the signals of a unit): immutable, shared by every run.</summary>
internal T Cached<T>(string key, Func<T> compute)
where T : class => (T)_cache.GetOrAdd(key, _ => new Lazy<object>(() => compute())).Value;
}
+255
View File
@@ -0,0 +1,255 @@
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Backtest;
/// <summary>Open, high, low and close of one side of a series on the market clock: not a number where it has no bar.</summary>
internal sealed class PriceColumns(double[] open, double[] high, double[] low, double[] close)
{
public double[] Open { get; } = open;
public double[] High { get; } = high;
public double[] Low { get; } = low;
public double[] Close { get; } = close;
public PriceColumns Slice(int count) => new(Open[..count], High[..count], Low[..count], Close[..count]);
}
/// <summary>
/// The prices the basket engine trades on (Phase 14): the bars of a <see cref="BarDataset"/> without the moments where no
/// symbol has a bar, the bid of every symbol and its ask when the source gives one. Each bar belongs to a day, the day of its
/// equity point: the UTC date for bars of a day or longer, the server day (17:00 New York to 17:00 New York) of its close
/// otherwise. Built once and never changed.
/// </summary>
public sealed class BasketMarket
{
private readonly DateTimeOffset[] _clock;
private readonly DateOnly[] _days;
private readonly Dictionary<string, PriceColumns> _bids;
private readonly Dictionary<string, PriceColumns> _asks;
private BasketMarket(string timeframe, DateTimeOffset[] clock, Dictionary<string, PriceColumns> bids, Dictionary<string, PriceColumns> asks, string fingerprint)
{
Timeframe = timeframe;
Length = Timeframes.Length(timeframe);
_clock = clock;
_bids = bids;
_asks = asks;
Fingerprint = fingerprint;
Symbols = [.. bids.Keys.Order(StringComparer.Ordinal)];
_days = [.. clock.Select(DayOf)];
}
public string Timeframe { get; }
public TimeSpan Length { get; }
/// <summary>Bars of a day or longer: the time-of-day windows of the document do not apply to them.</summary>
public bool Daily => Length >= TimeSpan.FromDays(1);
/// <summary>The opening moments of the bars, oldest first, in UTC.</summary>
public IReadOnlyList<DateTimeOffset> Clock => _clock;
public int Count => _clock.Length;
/// <summary>The symbols, in ordinal order.</summary>
public IReadOnlyList<string> Symbols { get; }
/// <summary>The fingerprint of the data the market was built from (<see cref="BarDataset.Fingerprint"/>), marked when cut or flipped.</summary>
public string Fingerprint { get; }
/// <summary>The market of a dataset: the moments where no symbol has a bar are left out.</summary>
public static BasketMarket Of(BarDataset data)
{
ArgumentNullException.ThrowIfNull(data);
var kept = Enumerable.Range(0, data.Clock.Count).Where(t => data.Symbols.Any(s => data.Has(s, t))).ToArray();
PriceColumns Columns(BarColumns columns) => new(
[.. kept.Select(t => columns.Open[t])],
[.. kept.Select(t => columns.High[t])],
[.. kept.Select(t => columns.Low[t])],
[.. kept.Select(t => columns.Close[t])]);
var bids = data.Symbols.ToDictionary(s => s, s => Columns(data.Bars(s)), StringComparer.Ordinal);
var asks = new Dictionary<string, PriceColumns>(StringComparer.Ordinal);
foreach (var symbol in data.Symbols)
{
if (data.Ask(symbol) is { } ask)
{
asks[symbol] = Columns(ask);
}
}
return new BasketMarket(data.Timeframe, [.. kept.Select(t => data.Clock[t])], bids, asks, data.Fingerprint());
}
public bool Has(string symbol) => _bids.ContainsKey(symbol);
/// <summary>Whether the symbol has a bar at position <paramref name="t"/>.</summary>
public bool Has(string symbol, int t) => _bids.TryGetValue(symbol, out var columns) && !double.IsNaN(columns.Close[t]);
/// <summary>Whether the source gives the ask of the symbol: otherwise bid and ask are built around one reference price.</summary>
public bool HasAsk(string symbol) => _asks.ContainsKey(symbol);
/// <summary>When the bar at <paramref name="t"/> closes.</summary>
public DateTimeOffset ClosesAt(int t) => _clock[t] + Length;
/// <summary>The day of the equity point the bar at <paramref name="t"/> belongs to.</summary>
public DateOnly Day(int t) => _days[t];
/// <summary>
/// The reference closes of a symbol: the mid between bid and ask when both exist, the single price otherwise. Not a number
/// where the symbol has no bar.
/// </summary>
public IReadOnlyList<double> Reference(string symbol)
{
var bid = Bid(symbol);
if (Ask(symbol) is not { } ask)
{
return bid.Close;
}
return [.. bid.Close.Select((b, t) => (b + ask.Close[t]) / 2)];
}
/// <summary>The bars that have closed by <paramref name="moment"/>: what a decision taken then could know.</summary>
public BasketMarket Through(DateTimeOffset moment)
{
var count = 0;
while (count < _clock.Length && ClosesAt(count) <= moment)
{
count++;
}
return new BasketMarket(
Timeframe,
_clock[..count],
_bids.ToDictionary(p => p.Key, p => p.Value.Slice(count), StringComparer.Ordinal),
_asks.ToDictionary(p => p.Key, p => p.Value.Slice(count), StringComparer.Ordinal),
$"{Fingerprint}|through:{moment.UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}");
}
/// <summary>
/// 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)
{
ArgumentNullException.ThrowIfNull(signs);
var bids = new Dictionary<string, PriceColumns>(StringComparer.Ordinal);
var asks = new Dictionary<string, PriceColumns>(StringComparer.Ordinal);
foreach (var symbol in Symbols)
{
var (bid, ask) = Flip(Bid(symbol), Ask(symbol), Reference(symbol), signs, centred);
bids[symbol] = bid;
if (ask is not null)
{
asks[symbol] = ask;
}
}
return new BasketMarket(Timeframe, _clock, bids, asks, $"{Fingerprint}|surrogate");
}
internal PriceColumns Bid(string symbol) =>
_bids.TryGetValue(symbol, out var columns) ? columns : throw new KeyNotFoundException($"{symbol} non è nei dati.");
internal PriceColumns? Ask(string symbol) => _asks.GetValueOrDefault(symbol);
private DateOnly DayOf(DateTimeOffset opensAt) => Length >= TimeSpan.FromDays(1)
? DateOnly.FromDateTime(opensAt.UtcDateTime)
: ServerClock.Day(opensAt + Length - TimeSpan.FromTicks(1));
// 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 mean = 0d;
if (centred)
{
var (sum, count, previous) = (0d, 0, double.NaN);
foreach (var close in reference.Where(c => !double.IsNaN(c)))
{
if (!double.IsNaN(previous))
{
sum += Math.Log(close / previous);
count++;
}
previous = close;
}
mean = count > 0 ? sum / count : 0;
}
PriceColumns Empty() => new(Nan(n), Nan(n), Nan(n), Nan(n));
var newBid = Empty();
var newAsk = ask is null ? null : Empty();
var before = double.NaN;
var made = double.NaN;
for (var t = 0; t < n; t++)
{
if (double.IsNaN(reference[t]))
{
continue;
}
if (double.IsNaN(before))
{
Copy(bid, newBid, t);
if (ask is not null)
{
Copy(ask, newAsk!, t);
}
before = reference[t];
made = reference[t];
continue;
}
var sign = signs[_days[t]];
double Price(double p) => made * Math.Exp(centred ? mean + (sign * (Math.Log(p / before) - mean)) : sign * Math.Log(p / before));
void Set(PriceColumns from, PriceColumns to)
{
to.Open[t] = Price(from.Open[t]);
to.Close[t] = Price(from.Close[t]);
(to.High[t], to.Low[t]) = sign > 0 ? (Price(from.High[t]), Price(from.Low[t])) : (Price(from.Low[t]), Price(from.High[t]));
}
if (ask is null || sign > 0)
{
Set(bid, newBid);
if (ask is not null)
{
Set(ask, newAsk!);
}
}
else
{
Set(ask, newBid);
Set(bid, newAsk!);
}
made = Price(reference[t]);
before = reference[t];
}
return (newBid, newAsk);
}
private static void Copy(PriceColumns from, PriceColumns to, int t) =>
(to.Open[t], to.High[t], to.Low[t], to.Close[t]) = (from.Open[t], from.High[t], from.Low[t], from.Close[t]);
private static double[] Nan(int n)
{
var values = new double[n];
Array.Fill(values, double.NaN);
return values;
}
}
+119
View File
@@ -0,0 +1,119 @@
using Anubis.Baskets;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>
/// What <c>anubis backtest baskets</c> computes (Phase 14, issue #131), fixed here before any result: the replica of
/// appendix G of the research document on the 28 ECB crosses up to the document's end, the control against chance of G.5,
/// and the plan of the trial of the basket engine. The trial runs «come dal vivo» with the eToro costs on a virtual register
/// of 20,000 USD (plan, section 5) from the first ECB fixing to the chosen day, on a small grid in σ: generation A and B,
/// averaging distance 4 and 10 σ, everything else as the document's base case of G.4.
/// </summary>
public static class BasketProtocol
{
/// <summary>The first ECB fixing: the trial starts here.</summary>
public static readonly DateOnly From = new(1999, 1, 4);
/// <summary>The end of the research document: the replica never reads past it, whatever the data hold.</summary>
public static readonly DateOnly ReplicaThrough = new(2026, 12, 2);
/// <summary>The virtual register of the forward test (plan, section 5), in USD.</summary>
public const decimal Capital = 20_000m;
/// <summary>The repetitions of the document's control (G.5).</summary>
public const int ControlRepetitions = 150;
/// <summary>The seed of the control when the command gives none: the document's date.</summary>
public const int ControlSeed = 20_261_202;
public const string Source = "Banca centrale europea, cambi di riferimento (eurofxref-hist.zip, conservato nella cartella di ricerca)";
/// <summary>What the trial is, in Italian, as the report names it.</summary>
public const string TrialName =
"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";
/// <summary>
/// The grid of the trial, written before any result: generation {A, B} × averaging distance {4, 10} σ; target 2.5 σ,
/// three averagings without growth, window 100, entry at z 2, profile Fedele, two baskets open, 0.01 lots per 10,000.
/// </summary>
public static IReadOnlyDictionary<string, IReadOnlyList<decimal>> Grid { get; } = new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal)
{
["generation"] = [1m, 2m],
["signal"] = [2m],
["units"] = [2m],
["target"] = [2.5m],
["distance"] = [4m, 10m],
["growth"] = [1m],
["averagings"] = [3m],
["window"] = [100m],
["entry_z"] = [2m],
["exit"] = [2m],
["profile"] = [1m],
["max_open"] = [2m],
["lot"] = [0.01m],
};
/// <summary>The plan of the trial up to <paramref name="to"/>, written at <paramref name="now"/>, and its variants.</summary>
public static (TrialPlan Plan, int Variants) Plan(DateOnly to, DateTimeOffset now)
{
if (to <= From)
{
throw new ArgumentException($"La prova a panieri parte dal {From:dd/MM/yyyy}: la data di fine deve venire dopo.", nameof(to));
}
var family = BasketReversionFamily.Instance;
var plan = new TrialPlan(
family.Id,
family.Version,
Grid,
new TrialData(TrialSources.Research, EcbCrosses.Venue, [.. FxPairs.All.Select(p => p.Name)], From, to),
Capital,
[1m, 2m, 3m],
TrialValidation.Default,
TrialThresholds.Default,
BasketEngine.Version,
now)
{
Mode = BasketModes.AsLive,
Costs = VenueCosts.Etoro,
};
return (plan, ParameterGrid.Of(family, plan.Grid).Count);
}
/// <summary>The daily bars of the crosses from their first day to <paramref name="through"/> included, on the currency calendar.</summary>
public static BarDataset Dataset(IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> crosses, DateOnly through)
{
ArgumentNullException.ThrowIfNull(crosses);
var first = crosses.Values.Where(b => b.Count > 0).Select(b => b[0].OpensAt).DefaultIfEmpty().Min();
if (first == default)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
}
return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, first, QualityChecks.Midnight(through).AddDays(1), crosses);
}
/// <summary>Where the data come from: source, fingerprint of every bar, period, days, pairs and the replica's cut.</summary>
public static BasketDataNotes Notes(IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> crosses)
{
ArgumentNullException.ThrowIfNull(crosses);
var days = crosses.Values.SelectMany(b => b).Select(b => DateOnly.FromDateTime(b.OpensAt.UtcDateTime)).Distinct().Order().ToList();
if (days.Count == 0)
{
throw new InvalidOperationException("BCE: lo storico non contiene i cambi delle sette valute.");
}
var fingerprint = Dataset(crosses, days[^1]).Fingerprint();
return new BasketDataNotes(Source, fingerprint, days[0], days[^1], days.Count, crosses.Count(c => c.Value.Count > 0), ReplicaThrough);
}
/// <summary>The 15 rows of table G.4 on the crosses up to the document's end.</summary>
public static IReadOnlyList<BasketReplicaRow> Replica(IReadOnlyList<IReadOnlyList<double>> series) =>
[.. ReplicaSettings.DocumentCases.Select(c => new BasketReplicaRow(c, StylisedReplica.Run(series, c.Settings)))];
/// <summary>The four rows of table G.5, each with <paramref name="repetitions"/> shuffles from <paramref name="seed"/>.</summary>
public static IReadOnlyList<BasketControlRow> Control(IReadOnlyList<IReadOnlyList<double>> series, int repetitions, int seed) =>
[.. BasketReport.DocumentControl.Select(d => new BasketControlRow(d.Case, StylisedReplica.Control(series, d.Case.Settings, repetitions, seed), repetitions, seed, d.Share))];
}
+510
View File
@@ -0,0 +1,510 @@
using System.Globalization;
using System.Text;
using Anubis.Baskets;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>Where the data of the basket report come from: the ECB file, its fingerprint, its period and the replica's cut.</summary>
/// <param name="Source">The source, in Italian, as the report shows it.</param>
/// <param name="Fingerprint">SHA-256 of the data (the report shows the first 12 characters).</param>
/// <param name="First">The first day with a fixing.</param>
/// <param name="Last">The last day with a fixing.</param>
/// <param name="Days">The days with a fixing.</param>
/// <param name="Pairs">The crosses built from the rates.</param>
/// <param name="ReplicaThrough">The last day the replica of appendix G uses: the end of the research document.</param>
public sealed record BasketDataNotes(string Source, string Fingerprint, DateOnly First, DateOnly Last, int Days, int Pairs, DateOnly ReplicaThrough);
/// <summary>One row of table G.4 and what the replica gave on it.</summary>
public sealed record BasketReplicaRow(ReplicaCase Case, ReplicaResult Result);
/// <summary>One row of the control against chance (G.5): our control, how it ran, and the document's share «pari o migliori».</summary>
public sealed record BasketControlRow(ReplicaCase Case, ReplicaControl Control, int Repetitions, int Seed, double DocumentShare);
/// <summary>A row of the document's table G.5 for «Forex 1999–2026»: the case, its observed break-even, its share and repetitions.</summary>
public sealed record BasketDocumentControl(ReplicaCase Case, double Observed, double Share, int Repetitions);
/// <summary>The trial of the basket engine shown in the report: its name, plan, plan hash, report and mode.</summary>
/// <param name="Mode"><see cref="BasketReport.LikeLive"/> or <see cref="BasketReport.ToTheLetter"/>.</param>
public sealed record BasketTrialSection(string Name, TrialPlan Plan, string PlanHash, BacktestReport Report, string Mode);
/// <summary>
/// Everything the basket report shows. <paramref name="Trial"/> is null when the trial of the engine did not run, and
/// <paramref name="TrialMissing"/> then says why, in Italian.
/// </summary>
public sealed record BasketReportInput(
string Command,
DateTimeOffset ComputedAt,
BasketDataNotes Data,
VenueCosts Costs,
IReadOnlyList<BasketReplicaRow> Replica,
IReadOnlyList<BasketControlRow> Control,
BasketTrialSection? Trial,
string? TrialMissing);
/// <summary>
/// The report of the basket family, <c>docs/backtests/basket_reversion.md</c> (Phase 14, issue #131), in plain Italian and
/// written whatever the verdict: the data and the costs, the replica of appendix G of the research document against its
/// 15 totals, the control against chance of G.5, the trial of the basket engine with its baskets, exit reasons, orphan legs
/// and refusals, and what the backtest does not model. The comparison is zero, no trading at all (ADR 0026 point 5), never
/// buy and hold; the share of baskets closed at the target is shown and never judged. The family only does research: there
/// is no outcome file for it in this phase.
/// </summary>
public static class BasketReport
{
/// <summary>The trial-registry id of the family (ADR 0026 point 10).</summary>
public const string Strategy = BasketReversionFamily.FamilyId;
public const string ReportPath = "docs/backtests/" + Strategy + ".md";
/// <summary>The mode with the account limits of the bot: the one that gives verdicts (ADR 0026).</summary>
public const string LikeLive = BasketModes.AsLive;
/// <summary>The mode with the document's rules only: replication and experiments, no verdict.</summary>
public const string ToTheLetter = BasketModes.AsDocument;
/// <summary>Note reason of a leg left alone when a mandatory stop closed the other one.</summary>
public const string OrphanLeg = BasketReasons.OrphanLeg;
/// <summary>Note reason of a liquidation for want of margin.</summary>
public const string Liquidation = BasketReasons.Liquidation;
/// <summary>Note reason of the 9% stop on the account value.</summary>
public const string AccountStop = BasketReasons.AccountStop;
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
/// <summary>The exits of a basket, in the order the report lists them, with their Italian labels.</summary>
private static readonly (string Code, string Label)[] Exits =
[
(BasketReasons.Target, "obiettivo raggiunto"),
(BasketReasons.StopBasket, "stop del paniere"),
(AccountStop, "stop sul valore del conto (9%)"),
(BasketReasons.MandatoryStop, "stop obbligatorio della piattaforma"),
(OrphanLeg, "gamba rimasta sola dopo uno stop obbligatorio"),
(Liquidation, "chiusura d'ufficio per margine insufficiente"),
(BasketReasons.End, "ancora aperto alla fine (valutato agli ultimi prezzi)"),
];
/// <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 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% del patrimonio",
[BasketReasons.PositionLimit] = "si supererebbero 9 posizioni aperte (conto Demo condiviso)",
[BasketReasons.OppositePosition] = "posizione opposta sullo stesso strumento",
[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, 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",
};
/// <summary>
/// The four «Forex 1999–2026» rows of table G.5: 2,5·10·3 and 2,5·4·3, without stop and with a stop of 90 targets; the
/// observed break-even per position, the share of shuffled series equal or better, 150 repetitions each.
/// </summary>
public static IReadOnlyList<BasketDocumentControl> DocumentControl { get; } = Array.AsReadOnly(
[
new BasketDocumentControl(ReplicaSettings.DocumentCases[0], 0.32, 0.37, 150),
new BasketDocumentControl(ReplicaSettings.DocumentCases[1], 0.26, 0.33, 150),
new BasketDocumentControl(ReplicaSettings.DocumentCases[9], 0.33, 0.33, 150),
new BasketDocumentControl(ReplicaSettings.DocumentCases[10], 0.16, 0.32, 150),
]);
/// <summary>The Markdown of the report.</summary>
public static string Markdown(BasketReportInput input)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(input.Data);
ArgumentNullException.ThrowIfNull(input.Costs);
ArgumentNullException.ThrowIfNull(input.Replica);
ArgumentNullException.ThrowIfNull(input.Control);
var b = new StringBuilder();
var trial = input.Trial;
b.Append("# Backtest di `").Append(Strategy).AppendLine("` (Rientro tra strumenti)").AppendLine();
if (trial is null)
{
b.Append("**Esito: in attesa.** ").AppendLine(input.TrialMissing ?? "La prova del motore a panieri non è stata fatta.");
}
else
{
b.Append("**Esito: ").Append(trial.Report.Passed ? "superato" : "non superato").Append(".** ").AppendLine(Verdict(trial));
}
b.AppendLine().AppendLine("Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).").AppendLine();
b.AppendLine(trial is null
? Text($"Calcolato il {input.ComputedAt:yyyy-MM-dd}: replica e controllo contro il caso, senza la prova del motore a panieri.")
: Text($"Calcolato il {input.ComputedAt:yyyy-MM-dd} con la versione {trial.Plan.Engine} del motore a panieri e la versione {trial.Plan.StrategyVersion} della famiglia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo."))
.AppendLine();
b.Append("Per rifarlo: `").Append(input.Command).AppendLine("`.").AppendLine();
DataSection(b, input);
ReplicaSection(b, input);
ControlSection(b, input);
if (trial is not null)
{
TrialSection(b, trial, input.Costs);
}
LimitsSection(b, input);
return b.ToString();
}
/// <summary>The verdict of a judged trial in one Italian sentence: what the report and the console say.</summary>
public static string Verdict(BasketTrialSection trial)
{
ArgumentNullException.ThrowIfNull(trial);
var mode = ModeName(trial.Mode);
if (trial.Report.Passed)
{
return $"La prova {mode} supera tutte le soglie fissate prima del calcolo.";
}
var failed = trial.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, trial.Report.Currency)).ToList();
return failed.Count == 0
? $"La prova {mode} non supera le soglie fissate prima del calcolo."
: $"La prova {mode} non supera: {string.Join("; ", failed)}.";
}
private static void DataSection(StringBuilder b, BasketReportInput input)
{
var d = input.Data;
var c = input.Costs;
b.AppendLine("## Dati").AppendLine();
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}.")
: Text($"- La replica dell'appendice G usa i dati fino al {d.ReplicaThrough:dd/MM/yyyy}, la fine del documento."));
b.AppendLine("- I cambi della BCE sono prezzi di riferimento, uno al giorno: non sono prezzi a cui si possa comprare o vendere. La prova decide sul cambio di oggi ed esegue su quello di domani, con il differenziale della tabella dei costi.");
b.AppendLine(Text($"- Costi: {VenueName(c.Venue)}, letti il {c.AsOf:dd/MM/yyyy}. Fonte: {c.Source}"));
b.AppendLine(Text($"- Minimo {Amount(c.MinimumUsd)} USD per posizione, leva {c.DefaultLeverage} per posizione, mai oltre quella del conto reale."));
var estimated = c.Pairs.Where(p => p.FinancingEstimated).Select(p => p.Pair).ToList();
if (estimated.Count > 0)
{
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();
b.AppendLine("**Tabella dei costi** (differenziale in pip; finanziamento in USD per 100.000 USD di esposizione a notte, positivo se si paga)").AppendLine();
b.AppendLine("| Coppia | Differenziale | In pausa | Leva massima | Commissione per lato | Finanziamento acquisto | Finanziamento vendita | Finanziamento |");
b.AppendLine("|---|---:|---:|---:|---:|---:|---:|---|");
foreach (var p in c.Pairs)
{
b.AppendLine(Text($"| {p.Pair} | {Amount(p.Spread)} | {Amount(p.PauseSpread)} | {p.MaxLeverage} | {Amount(p.CommissionPerSide * 100m)}% | {Signed(p.FinancingBuy)} | {Signed(p.FinancingSell)} | {(p.FinancingEstimated ? "stimato" : "dal documento")} |"));
}
b.AppendLine();
}
private static void ReplicaSection(StringBuilder b, BasketReportInput input)
{
b.AppendLine("## Replica dell'appendice G").AppendLine();
b.AppendLine("La replica segue alla lettera il metodo G.3 del documento di ricerca: ognuna delle coppie da sola, sui logaritmi dei prezzi, ingresso e uscita sulla stessa chiusura, nessun costo e nessuna regola del conto. Non è il motore a panieri e non dà nessun giudizio: dice solo se i numeri del documento si ritrovano sugli stessi dati. I risultati sono in obiettivi (un obiettivo è la distanza del take profit).")
.AppendLine();
if (input.Replica.Count == 0)
{
b.AppendLine("Non calcolata in questa esecuzione.").AppendLine();
return;
}
b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |");
b.AppendLine("|---|---|---:|---:|---:|---:|---|---|");
foreach (var (c, r) in input.Replica)
{
var outcome = !c.Binding ? "solo riportata" : c.Passes(r.Total) ? "dentro" : "**fuori**";
b.AppendLine(Text($"| {c.Label} | {c.StopLabel} | {Targets(c.DocumentTotal)} | {Targets(r.Total)} | {SignedTargets(r.Total - c.DocumentTotal)} | ±{Targets(c.Tolerance)} | {(c.Binding ? "sì" : "no")} | {outcome} |"));
}
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($"{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)
{
b.AppendLine();
b.AppendLine("Solo riportate, perché vicine allo zero: " + string.Join("; ", reported.Select(r =>
Text($"{r.Case.Label} {StopWords(r.Case.StopLabel)}, documento {Targets(r.Case.DocumentTotal)}, Anubis {Targets(r.Result.Total)} ({(Math.Sign(r.Result.Total) == Math.Sign(r.Case.DocumentTotal) ? "stesso segno" : "segno diverso")})"))) + ".");
}
b.AppendLine();
b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Pareggio del documento | Pareggio di Anubis | Posizioni | Panieri | Chiusi all'obiettivo |");
b.AppendLine("|---|---|---:|---:|---:|---:|---:|");
foreach (var (c, r) in input.Replica)
{
b.AppendLine(Text($"| {c.Label} | {c.StopLabel} | {Ratio(c.DocumentBreakEven)} | {Ratio(r.BreakEven)} | {r.Positions.ToString("#,0", It)} | {r.Baskets.ToString("#,0", It)} | {Share(r.AtTargetShare)} |"));
}
b.AppendLine();
b.AppendLine("Il pareggio è il costo per posizione, in obiettivi, che porterebbe il totale a zero: totale diviso posizioni. La quota di panieri chiusi all'obiettivo è mostrata e mai giudicata: alta com'è, non prova nulla sul guadagno.")
.AppendLine();
}
private static void ControlSection(StringBuilder b, BasketReportInput input)
{
b.AppendLine("## Controllo contro il caso (G.5)").AppendLine();
b.AppendLine("Ogni giorno le variazioni di tutte le coppie cambiano segno insieme con probabilità un mezzo: restano volatilità, code e legami tra le coppie, sparisce ogni tendenza a rientrare o a proseguire. Poi la replica gira di nuovo sulle serie ricostruite. Si conta quante volte il pareggio delle serie rimescolate è pari o migliore di quello osservato.")
.AppendLine();
if (input.Control.Count == 0)
{
b.AppendLine("Non calcolato in questa esecuzione.").AppendLine();
return;
}
b.AppendLine("| Obiettivo · distanza · mediazioni | Stop | Ripetizioni | Seme | Pareggio osservato | Mediana rimescolate | 5°–95° percentile | Pari o migliori: Anubis | Pari o migliori: documento |");
b.AppendLine("|---|---|---:|---:|---:|---:|---:|---:|---:|");
foreach (var row in input.Control)
{
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} | {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();
b.AppendLine("Una quota alta vuol dire che il risultato osservato è uno dei tanti che il caso produce da solo. Il documento ha fatto 150 ripetizioni per riga, senza dire il seme.")
.AppendLine();
}
private static void TrialSection(StringBuilder b, BasketTrialSection trial, VenueCosts costs)
{
var r = trial.Report;
var m = r.Metrics;
var h = r.Benchmark;
var annual = Math.Sqrt(r.PeriodsPerYear);
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}, {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 |");
b.AppendLine("|---|---:|---:|---:|---:|---:|---|");
var doubled = r.Costs.FirstOrDefault(c => c.Multiplier == 2m);
b.Append("| `").Append(r.Judged ?? r.Chosen).Append("` | ").Append(Pct(m.AnnualReturn)).Append(" | ").Append(Pct(-m.MaxDrawdown))
.Append(" | ").Append(doubled is null ? "—" : Money(doubled.NetResult, r.Currency)).Append(" | ").Append(Num(r.DeflatedSharpe.Value))
.Append(" | ").Append(r.Overfitting is { } o ? Num(o.Probability) : "—").Append(" | ").Append(r.Passed ? "superata" : "non superata").AppendLine(" |");
b.AppendLine();
b.AppendLine("Il confronto è con zero (nessuna operazione): il capitale fermo, senza guadagni né perdite.").AppendLine();
b.AppendLine("| | Strategia | Zero (nessuna operazione) |").AppendLine("|---|---:|---:|");
Row(b, "Risultato netto", Money(m.NetResult, r.Currency), Money(h.NetResult, r.Currency));
Row(b, "Rendimento totale", Pct(m.TotalReturn), Pct(h.TotalReturn));
Row(b, "Rendimento annuo", Pct(m.AnnualReturn), Pct(h.AnnualReturn));
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, "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** (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)
{
b.AppendLine(Text($"| ×{c.Multiplier:0} | {Money(c.NetResult, r.Currency)} | {Pct(c.TotalReturn)} | {Num(c.Sharpe)} | {Pct(-c.MaxDrawdown)} |"));
}
b.AppendLine();
b.AppendLine("**Convalide**").AppendLine();
if (r.WalkForward is { } wf)
{
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 ({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 {Count(r.TrialsCounted)} varianti provate in tutto."));
b.AppendLine(r.Overfitting is { } pbo
? 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: {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();
b.AppendLine("| Controllo | Valore | Soglia | Esito |").AppendLine("|---|---:|---:|---|");
foreach (var c in r.Checks)
{
b.AppendLine(Text($"| {c.Name} | {CheckValue(c, r.Currency)} | {c.Comparison} {CheckThreshold(c, r.Currency)} | {(c.Passed is null ? "non si applica" : c.Passed.Value ? "superato" : "**non superato**")} |"));
}
b.AppendLine();
b.AppendLine("**Varianti della griglia**").AppendLine();
b.AppendLine("| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo |").AppendLine("|---|---:|---:|---:|---:|");
foreach (var v in r.Variants)
{
b.AppendLine(Text($"| `{v.Parameters}`{(v.Chosen ? " (scelta)" : "")} | {Num(v.Sharpe * annual)} | {Num(v.PlateauScore * annual)} | {Money(v.NetResult, r.Currency)} | {Pct(-v.MaxDrawdown)} |"));
}
b.AppendLine();
BasketsSection(b, r);
}
private static void BasketsSection(StringBuilder b, BacktestReport r)
{
var baskets = r.Baskets ?? [];
b.AppendLine("**Panieri**").AppendLine();
b.AppendLine(baskets.Count >= TrialRunner.MaxTrades
? 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(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} | {Count(n)} |"));
}
}
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}` | {Count(n)} |"));
}
b.AppendLine();
// 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();
}
// 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);
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 or BasketReasons.ClosedWithStop)).ToList();
b.AppendLine("**Ingressi e mediazioni fermati o annotati**").AppendLine();
if (refusals.Count == 0)
{
b.AppendLine("Nessuno.").AppendLine();
return;
}
b.AppendLine("Con il profilo Fedele la regola dei tre costi e il limite di esposizione per valuta sono solo annotati: l'ingresso si fa lo stesso. Una dimensione dimezzata è un ingresso fatto più piccolo.")
.AppendLine();
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 + "`")} | {Count(n)} |"));
}
b.AppendLine();
}
private static void LimitsSection(StringBuilder b, BasketReportInput input)
{
b.AppendLine("## Cosa il backtest non rappresenta").AppendLine();
foreach (var line in input.Trial?.Report.Limitations ?? [])
{
b.Append("- ").AppendLine(line);
}
// 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.");
}
b.AppendLine("- Mancano ancora i dati a 15 minuti: il giudizio che conta richiede i file a 1 minuto forniti dall'utente.");
}
private static string ModeName(string mode) => mode switch
{
LikeLive => "«come dal vivo»",
ToTheLetter => "«alla lettera»",
_ => "«" + mode + "»",
};
private static string VenueName(string venue) => venue switch
{
"etoro" => "eToro",
"none" => "nessuna piattaforma (configurazione di confronto)",
_ => venue,
};
private static string StopWords(string stopLabel) => stopLabel == "nessuno" ? "senza stop" : "con stop di " + stopLabel;
private static string Describe(ReportCheck check, string currency) =>
$"{check.Name.ToLower(It)} {CheckValue(check, currency)}, serve {check.Comparison} {CheckThreshold(check, currency)}";
private static string CheckValue(ReportCheck c, string currency) => c.Value is not { } v ? "—" : c.Unit switch
{
"percent" => Pct(v),
"money" => Money((decimal)v, currency),
"count" => v.ToString("N0", It),
_ => Num(v),
};
private static string CheckThreshold(ReportCheck c, string currency) =>
c.Unit == "percent" ? Pct(c.Threshold, 0) : c.Unit == "money" ? Money((decimal)c.Threshold, currency) : c.Threshold.ToString("0.##", It);
private static double Median(double[] sorted) =>
sorted.Length == 0 ? double.NaN : sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[(sorted.Length / 2) - 1] + sorted[sorted.Length / 2]) / 2;
/// <summary>The value at rank ⌊p·(n − 1)⌋ of a sorted array, as <see cref="PathBootstrap"/> takes its percentiles.</summary>
private static double Rank(double[] sorted, double p) => sorted[(int)Math.Floor(p * (sorted.Length - 1))];
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 ? "−" : "";
/// <summary>A total in targets: 535,5; 1.032; −100,8.</summary>
private static string Targets(double value) => Minus(value) + Math.Abs(value).ToString("#,0.#", It);
private static string SignedTargets(double value) => (value > 0 ? "+" : "") + Targets(value);
/// <summary>A break-even or another ratio with its sign: +0,32, −0,03; a dash when not a number.</summary>
private static string Ratio(double value) => double.IsNaN(value) ? "—" : (value > 0 ? "+" : "") + Num(value);
private static string Share(double fraction) => double.IsNaN(fraction) ? "—" : Pct(fraction);
private static string Pct(double fraction, int decimals = 1) =>
Minus(fraction) + Math.Abs(fraction * 100).ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), It) + "%";
private static string Num(double value) => Minus(value) + Math.Abs(value).ToString("0.00", It);
private static string Amount(decimal value) => (value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.###", It);
private static string Signed(decimal value) => (value > 0 ? "+" : "") + Amount(value);
private static string Money(decimal value, string currency) =>
(value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.00", It) + " " + (currency == "EUR" ? "€" : currency);
private static string Text(FormattableString text) => text.ToString(It);
}
+233
View File
@@ -0,0 +1,233 @@
using System.Globalization;
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// The two ways the basket engine runs (plan, Phase 14): «alla lettera», the document's rules alone; «come dal vivo», the
/// same plus the limits of SPEC 9.2 and of the plan's margin table. Verdicts come only from «come dal vivo» (ADR 0026).
/// </summary>
public enum BasketMode
{
/// <summary>«alla lettera»: the rules of the research document only.</summary>
AsDocument,
/// <summary>«come dal vivo»: the document's rules and every limit the live bot would have.</summary>
AsLive,
}
/// <summary>The names of the modes in plans and reports.</summary>
public static class BasketModes
{
public const string AsDocument = "alla_lettera";
public const string AsLive = "come_dal_vivo";
public static string Name(BasketMode mode) => mode == BasketMode.AsDocument ? AsDocument : AsLive;
/// <summary>The mode a plan names; throws, in Italian, on an unknown name.</summary>
public static BasketMode Parse(string name) => name switch
{
AsDocument => BasketMode.AsDocument,
AsLive => BasketMode.AsLive,
_ => throw new ArgumentException($"Modalità sconosciuta: «{name}». Quelle possibili sono {AsDocument} e {AsLive}.", nameof(name)),
};
}
/// <summary>When a decision taken on a closed bar is executed.</summary>
public enum BasketExecution
{
/// <summary>At the next bar's open, buying at the ask and selling at the bid (the plan's convention).</summary>
NextOpen,
/// <summary>At the same close: only the comparison configuration with the replica of appendix G.</summary>
SameClose,
}
/// <summary>The index the z-score reads (sections 4.3 and 11.3).</summary>
public enum BasketSignal
{
/// <summary>The pip index X = A / pip(A) + s · B / pip(B).</summary>
ZScorePipSum,
/// <summary>The log index X = 10,000 · (ln A + s · ln B), in basis points.</summary>
ZScoreLog,
}
/// <summary>The unit of target and averaging distance: pips, or σ of the index frozen at the opening (section 11.3).</summary>
public enum BasketMeasure
{
Pips,
Sigma,
}
/// <summary>When a basket reaches its target.</summary>
public enum BasketExitRule
{
/// <summary>Section 4.5: the pips of every open order, added, reach the target.</summary>
PipSum,
/// <summary>Appendix G.3: the index is beyond the mean of the entries by the target.</summary>
MeanOfEntries,
}
/// <summary>
/// What a basket trades: one pair (generation B) or two legs (generation A), with the kind of their relation. The sign s of the
/// index is +1 for a chain, −1 for a ratio, −sign(ρ) for a disjoint couple, read when the basket opens.
/// </summary>
public sealed record BasketUnit(string Name, FxPair A, FxPair? B, RelationKind Kind)
{
public static BasketUnit OnePair(FxPair pair)
{
ArgumentNullException.ThrowIfNull(pair);
return new BasketUnit(pair.Name, pair, null, RelationKind.SingleSymbol);
}
public static BasketUnit Of(FxPair a, FxPair b)
{
var relation = Relations.Classify(a, b);
if (relation.Kind is not (RelationKind.Chain or RelationKind.Ratio or RelationKind.Disjoint))
{
throw new ArgumentException($"{a.Name}/{b.Name}: relazione non prevista dal motore a panieri.", nameof(b));
}
return new BasketUnit($"{a.Name}/{b.Name}", a, b, relation.Kind);
}
public bool TwoLegs => B is not null;
public IReadOnlyList<FxPair> Legs => B is null ? [A] : [A, B];
/// <summary>The fixed sign of the index, or null for a disjoint couple (its sign comes from the correlation).</summary>
public int? FixedSign => Kind switch
{
RelationKind.SingleSymbol => 1,
RelationKind.Disjoint => null,
_ => Relations.Sign(Kind, null),
};
}
/// <summary>
/// The rules of one run of the basket engine: what is traded, the signal, levels and exit, the profile, the size, the mode and
/// the protections. The defaults are the document's (section 4 and appendix E): Moderato, Fedele, 10 and 40 pips, leverage 5.
/// </summary>
public sealed record BasketRules(IReadOnlyList<BasketUnit> Units)
{
public BasketSignal Signal { get; init; } = BasketSignal.ZScorePipSum;
/// <summary>Bars of the z-score and σ window, bar t included.</summary>
public int Window { get; init; } = BasketIndex.DefaultWindow;
public double EntryZ { get; init; } = 2.0;
public BasketMeasure Measure { get; init; } = BasketMeasure.Pips;
/// <summary>The target, in pips or in σ.</summary>
public decimal Target { get; init; } = 10m;
/// <summary>The smallest averaging distance from the last level, in pips or in σ.</summary>
public decimal Distance { get; init; } = 40m;
/// <summary>The growth of the distance at each averaging (1.3 in the growing variant).</summary>
public decimal Growth { get; init; } = 1m;
public int MaxAveragings { get; init; } = 3;
public BasketExitRule Exit { get; init; } = BasketExitRule.PipSum;
public BasketProfile Profile { get; init; } = BasketProfiles.Fedele;
public int MaxOpenBaskets { get; init; } = 2;
/// <summary>Lots per 10,000 of initial capital, the same on every leg and every level.</summary>
public decimal LotPer10k { get; init; } = 0.01m;
/// <summary>The leverage of each position, never above the pair's on the real account.</summary>
public int Leverage { get; init; } = 5;
public BasketMode Mode { get; init; } = BasketMode.AsLive;
public BasketExecution Execution { get; init; } = BasketExecution.NextOpen;
/// <summary>The document's account rules (9% stop, 2% gate, open baskets, cost rule): off only for the comparison configuration.</summary>
public bool Protections { get; init; } = true;
/// <summary>The basket stop of the replica, in targets: comparison configuration only.</summary>
public double? StopTargets { get; init; }
/// <summary>The correlation a two-leg unit needs on its expected sign to open; null turns the check off.</summary>
public double? MinCorrelation { get; init; } = 0.6;
/// <summary>Above this Rvol no basket opens; null turns the filter and the distance factor off.</summary>
public double? MaxRvol { get; init; } = BasketIndex.DefaultMaxRvol;
/// <summary>A unit opens only if its target is at least this many times its round-trip cost (section 11.3).</summary>
public decimal CostMultiple { get; init; } = BasketMath.CostMultiple;
/// <summary>The hourly window 10:00–20:00 server time on bars shorter than a day (on in generation B).</summary>
public bool Session { get; init; }
/// <summary>The weekend, the daily pause and the hourly window on bars shorter than a day: on unless a test turns them off.</summary>
public bool ClockWindows { get; init; } = true;
/// <summary>Differences in the short window of Rvol.</summary>
public int ShortBars { get; init; } = BasketIndex.DefaultShortBars;
/// <summary>Bars of the Rvol baseline; null: 20 market days of the timeframe (20 bars on daily bars).</summary>
public int? BaselineBars { get; init; }
/// <summary>A test hook: the signal of bar t reads bar t + shift. Never set outside the look-ahead test.</summary>
internal int SignalShift { get; init; }
/// <summary>
/// The comparison configuration with the replica of appendix G (plan, Phase 14): generation B on one pair, z of the log
/// price, σ units, exit on the mean of the entries, the replica's stop in targets, decision and execution on the same
/// close, no protection, no filter, any number of baskets. Run it with <see cref="VenueCosts.None"/>.
/// </summary>
public static BasketRules Comparison(FxPair pair, ReplicaSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
settings.Validate();
return new BasketRules([BasketUnit.OnePair(pair)])
{
Signal = BasketSignal.ZScoreLog,
Window = settings.Window,
EntryZ = settings.EntryZ,
Measure = BasketMeasure.Sigma,
Target = (decimal)settings.TargetSigma,
Distance = (decimal)settings.DistanceSigma,
Growth = (decimal)settings.Growth,
MaxAveragings = settings.MaxAveragings,
Exit = BasketExitRule.MeanOfEntries,
MaxOpenBaskets = int.MaxValue,
Mode = BasketMode.AsDocument,
Execution = BasketExecution.SameClose,
Protections = false,
StopTargets = settings.StopTargets,
MinCorrelation = null,
MaxRvol = null,
ClockWindows = false,
};
}
/// <summary>Checks the values; the message is for the user.</summary>
public void Validate()
{
if (Units.Count == 0)
{
throw new ArgumentException("Le regole dei panieri non hanno nessuno strumento da seguire.");
}
if (Window < 3 || !(EntryZ > 0) || Target <= 0m || Distance < 0m || Growth <= 0m || MaxAveragings < 0 || MaxOpenBaskets < 1
|| LotPer10k <= 0m || Leverage < 1 || ShortBars < 2 || BaselineBars is < 1 || StopTargets is <= 0 || MinCorrelation is < -1 or > 1)
{
throw new ArgumentException(string.Create(CultureInfo.InvariantCulture,
$"Regole dei panieri non valide: finestra {Window}, ingresso {EntryZ}, obiettivo {Target}, distanza {Distance}, crescita {Growth}, mediazioni {MaxAveragings}, panieri {MaxOpenBaskets}, lotto {LotPer10k}, leva {Leverage}."));
}
if (Units.Select(u => u.Name).Distinct(StringComparer.Ordinal).Count() != Units.Count)
{
throw new ArgumentException("Le regole dei panieri nominano due volte lo stesso strumento.");
}
}
}
+100
View File
@@ -0,0 +1,100 @@
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// The compressed series of a unit (Phase 14): only the bars where every leg has a close, so a holiday of one pair never puts
/// a gap in a window. <see cref="Position"/> maps a bar of the market to its place in the series (−1 when a leg is missing).
/// The prices are the reference closes: mid when bid and ask exist, the single price otherwise.
/// </summary>
internal sealed class UnitData
{
public UnitData(BasketMarket market, BasketUnit unit)
{
Unit = unit;
var legs = unit.Legs.Select(l => l.Name).ToArray();
var position = new int[market.Count];
Array.Fill(position, -1);
var bars = new List<int>(market.Count);
for (var t = 0; t < market.Count; t++)
{
if (legs.All(l => market.Has(l, t)))
{
position[t] = bars.Count;
bars.Add(t);
}
}
Bars = [.. bars];
Position = position;
var a = market.Reference(unit.A.Name);
PricesA = [.. Bars.Select(t => a[t])];
if (unit.B is not null)
{
var b = market.Reference(unit.B.Name);
PricesB = [.. Bars.Select(t => b[t])];
}
}
public BasketUnit Unit { get; }
/// <summary>The market bar of each point of the series.</summary>
public int[] Bars { get; }
/// <summary>The point of the series of each market bar, −1 when a leg has no bar.</summary>
public int[] Position { get; }
public double[] PricesA { get; }
public double[]? PricesB { get; }
/// <summary>The index of the signal at prices <paramref name="a"/> and <paramref name="b"/> with sign <paramref name="sign"/>.</summary>
public double Index(BasketSignal signal, int sign, double a, double b) => (signal, Unit.B) switch
{
(BasketSignal.ZScorePipSum, null) => BasketIndex.Pips(a, Unit.A),
(BasketSignal.ZScorePipSum, { } legB) => BasketIndex.Pips(a, Unit.A, b, legB, sign),
(_, null) => BasketIndex.LogBp(a),
_ => BasketIndex.LogBp(a, b, -sign),
};
/// <summary>The pip index, whatever the signal: targets and distances in pips with the exit on the mean of the entries read it.</summary>
public double PipIndex(int sign, double a, double b) => Index(BasketSignal.ZScorePipSum, sign, a, b);
/// <summary>The correlation of the log returns of the two legs over the window ending at point <paramref name="c"/>; null for one leg.</summary>
public double? Correlation(int c, int window) => PricesB is null ? null : BasketIndex.Correlation(PricesA, PricesB, c, window);
}
/// <summary>
/// The signals of a unit with one index and one sign: the index, z and σ from the shared rolling functions of the replica
/// (<see cref="BasketIndex.RollingZ"/>, <see cref="BasketIndex.RollingSigma"/>), Rvol (<see cref="BasketIndex.RollingRvol"/>)
/// when the filter is on, and the pip index. One value per point of the compressed series.
/// </summary>
internal sealed class UnitSignal
{
public UnitSignal(UnitData data, BasketSignal signal, int sign, int window, int? baselineBars, int shortBars)
{
var n = data.Bars.Length;
Index = new double[n];
Pips = new double[n];
for (var c = 0; c < n; c++)
{
var b = data.PricesB?[c] ?? 0;
Index[c] = data.Index(signal, sign, data.PricesA[c], b);
Pips[c] = data.PipIndex(sign, data.PricesA[c], b);
}
Z = BasketIndex.RollingZ(Index, window);
Sigma = BasketIndex.RollingSigma(Index, window);
Rvol = baselineBars is { } baseline ? BasketIndex.RollingRvol(Index, baseline, shortBars) : null;
}
public double[] Index { get; }
public double[] Pips { get; }
public double[] Z { get; }
public double[] Sigma { get; }
public double[]? Rvol { get; }
}
File diff suppressed because it is too large. Load diff
+180
View File
@@ -0,0 +1,180 @@
using System.Globalization;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Backtest;
/// <summary>
/// The trial judge's engine for the basket family (Phase 14, ADR 0026): the <see cref="BasketEngine"/> on currency bars, in
/// the plan's mode and with the plan's venue costs («come dal vivo» and eToro when the plan names none). One equity point per
/// day of the window, 260 a year; the comparison is zero, capital that does not move, never buy and hold; the control
/// against chance turns each day's changes of every pair with the day's sign, both ways (the engine sells as well as it
/// buys). It holds no state between runs.
/// </summary>
public sealed class BasketTrialEngine : ITrialEngine
{
/// <summary>Equity points in a year: the weekdays of the currency calendar.</summary>
public const int PointsPerYear = 260;
private readonly TrialPlan _plan;
private readonly BasketReversionFamily _family;
private readonly BasketMode _mode;
private readonly VenueCosts _costs;
private readonly BasketEngine _engine;
private readonly Lazy<string> _fingerprint;
private readonly DateOnly[] _days;
public BasketTrialEngine(TrialPlan plan, BasketReversionFamily family, BarDataset data)
: this(plan, family, BasketMarket.Of(data ?? throw new ArgumentNullException(nameof(data))))
{
}
private BasketTrialEngine(TrialPlan plan, BasketReversionFamily family, BasketMarket market)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(family);
_plan = plan;
_family = family;
_mode = BasketModes.Parse(plan.Mode ?? BasketModes.AsLive);
_costs = plan.Costs ?? VenueCosts.Etoro;
Market = market;
_engine = new BasketEngine(market, _costs, plan.InitialCapital);
_fingerprint = new Lazy<string>(() =>
$"{market.Fingerprint}|basket:{BasketEngine.Version}|costs:{_costs.Fingerprint()}|mode:{BasketModes.Name(_mode)}");
_days = [.. Enumerable.Range(0, market.Count).Select(market.Day).Distinct().Where(d => d >= plan.Data.From && d <= plan.Data.To)];
}
/// <summary>The prices the runs read.</summary>
public BasketMarket Market { get; }
/// <summary>A test hook: changes the rules of every run (narrower units, a filter off, a rule that cheats).</summary>
internal Func<BasketRules, BasketRules>? Customize { get; init; }
public string Currency => "USD";
public int PeriodsPerYear => PointsPerYear;
/// <summary>The days of the window with at least one bar: one equity point each.</summary>
public int Sessions => _days.Length;
public string Fingerprint() => _fingerprint.Value;
public IReadOnlyList<ReportInstrument> Instruments() =>
[.. Market.Symbols.Select(symbol =>
{
var bars = Enumerable.Range(0, Market.Count).Where(t => Market.Has(symbol, t)).ToList();
return new ReportInstrument(symbol, _plan.Data.Venue, bars.Count > 0 ? Market.Day(bars[0]) : null, bars.Count > 0 ? Market.Day(bars[^1]) : null,
bars.Count, 0, _plan.Data.Source);
})];
/// <summary>The rules of a variant in the plan's mode.</summary>
public BasketRules Rules(StrategyParameters parameters)
{
var rules = _family.Rules(parameters, _mode, Market.Timeframe);
return Customize is null ? rules : Customize(rules);
}
/// <summary>A run with its traces and decisions, not only what the judge reads.</summary>
public BasketRunResult RunBaskets(StrategyParameters parameters, decimal costMultiplier = 1m) =>
_engine.Run(Rules(parameters), costMultiplier, _plan.Data.From, _plan.Data.To);
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) => RunBaskets(parameters, costMultiplier).Run;
/// <summary>Zero: the capital that does not trade, on the same days (ADR 0026 point 5).</summary>
public BacktestRun Benchmark() => new(
Currency, _plan.InitialCapital, [.. _days.Select(d => new EquityPoint(d, _plan.InitialCapital, _plan.InitialCapital, 0m))], [], [], [], []);
/// <summary>
/// The check of SPEC 12.2 point 2 for baskets: the whole data and the data cut after a few days of the window (only the
/// bars closed by the end of that day), every decision up to the cut compared, moment by moment. A basket still open at
/// the cut, valued at the end, is not a decision.
/// </summary>
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
var rules = Rules(parameters);
var cutoffs = Enumerable.Range(1, cuts)
.Select(k => (int)((long)(_days.Length - 1) * k / (cuts + 1)))
.Where(i => i > 0)
.Distinct()
.Select(i => _days[i])
.ToList();
var full = _engine.Run(rules, 1m, _plan.Data.From, _plan.Data.To);
var mismatches = new List<LookAheadMismatch>();
var compared = 0;
foreach (var cutoff in cutoffs)
{
var lastBar = Enumerable.Range(0, Market.Count).Last(t => Market.Day(t) <= cutoff);
var moment = Market.ClosesAt(lastBar);
var cut = new BasketEngine(Market.Through(moment), _costs, _plan.InitialCapital).Run(rules, 1m, _plan.Data.From, _plan.Data.To);
var before = Decisions(full.Events, moment);
var after = Decisions(cut.Events, moment);
foreach (var at in before.Keys.Union(after.Keys).Order())
{
compared++;
var inFull = before.TryGetValue(at, out var x);
var inCut = after.TryGetValue(at, out var y);
var a = inFull ? x.Text : "-";
var b = inCut ? y.Text : "-";
if (a != b)
{
mismatches.Add(new LookAheadMismatch(cutoff, inFull ? x.Day : y.Day, a, b));
}
}
}
return new LookAheadResult(cutoffs, compared, mismatches);
}
public IReadOnlyList<string> Limitations()
{
var italian = CultureInfo.GetCultureInfo("it-IT");
var result = new List<string>();
if (Market.Symbols.Any(s => !Market.HasAsk(s)))
{
result.Add("I prezzi della BCE sono cambi di riferimento, non prezzi a cui si compra o si vende: denaro e lettera sono ricostruiti "
+ "attorno al cambio con il differenziale della tabella dei costi.");
}
result.Add(string.Create(italian, $"Costi di {(_costs.Venue == "etoro" ? "eToro" : _costs.Venue)} al {_costs.AsOf:d MMMM yyyy}: {_costs.Source}."));
if (_costs.Pairs.Any(p => p.FinancingEstimated))
{
result.Add("Il finanziamento notturno delle coppie che il documento non dà è stimato con prudenza: il costo più alto fra quelli noti, sui due lati.");
}
result.Add(Market.Daily
? "Si decide sul cambio di chiusura di un giorno e si esegue su quello del giorno dopo; le finestre orarie (fine settimana, sessione, pausa giornaliera) su barre giornaliere non valgono."
: "Si decide sulla chiusura della barra e si esegue all'apertura della barra dopo; lo stop sul conto usa i prezzi medi durante la pausa giornaliera.");
result.Add("Il conto non viene letto: margine, stop obbligatorio della piattaforma, chiusura d'ufficio sotto metà del margine e finanziamento con il mercoledì triplo sono simulati con le regole della sede.");
result.Add(_mode == BasketMode.AsLive
? "Modalità «come dal vivo»: regole del documento più i limiti di rischio (perdita del giorno, della settimana, calo dal massimo) e del margine; se scatta l'interruttore supponiamo che tu riparta dopo sette giorni."
: "Modalità «alla lettera»: solo le regole del documento. Il giudizio vale solo per la modalità «come dal vivo».");
result.Add("Nessuna notizia e nessun calendario economico: il filtro delle notizie è spento.");
result.Add("Il confronto è con zero, cioè il capitale fermo, non con comprare e tenere.");
result.Add("Sharpe e volatilità sono calcolati senza tasso privo di rischio.");
return result;
}
public TrialExpectations Expected(BacktestRun run, double[] returns)
{
ArgumentNullException.ThrowIfNull(run);
ArgumentNullException.ThrowIfNull(returns);
return new TrialExpectations(null,
[.. PathBootstrap.Percentile(returns, PointsPerYear, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed).Select(x => Math.Round(x, 4))]);
}
/// <summary>Baskets buy and sell: the control flips the signs without centring them (ADR 0026 point 4).</summary>
public bool LongOnly => false;
/// <summary>The same engine on the surrogate market: every day of every pair takes the sign of <paramref name="signs"/>.</summary>
public ITrialEngine Surrogate(DaySigns signs, bool centred) =>
new BasketTrialEngine(_plan, _family, Market.Surrogate(signs, centred)) { Customize = Customize };
private static Dictionary<DateTimeOffset, (DateOnly Day, string Text)> Decisions(IReadOnlyList<BasketEvent> events, DateTimeOffset through) =>
events
.Where(e => e.At <= through && e.Reason != BasketReasons.End)
.GroupBy(e => e.At)
.ToDictionary(
g => g.Key,
g => (g.First().Day, string.Join(" | ", g.Select(e => string.Create(CultureInfo.InvariantCulture,
$"{e.At.UtcDateTime:yyyy-MM-dd HH:mm} {e.Unit} {e.Kind} {e.Reason} {e.Direction}")))));
}
+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>
+9
View File
@@ -85,6 +85,15 @@ public sealed record TrialPlan(
/// </summary>
public string? Judged { get; init; }
/// <summary>
/// The mode of a basket trial (<see cref="BasketModes"/>): «come_dal_vivo», the only one a verdict comes from, or
/// «alla_lettera». Null for the daily families, so their plans and hashes stay as they were.
/// </summary>
public string? Mode { get; init; }
/// <summary>The venue's costs a basket trial runs with, with their date and source; null for the daily families.</summary>
public VenueCosts? Costs { get; init; }
public static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
+359
View File
@@ -0,0 +1,359 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// The costs of one pair at a venue (research document, appendix A and section 6.3). Spreads are in pips; the commission is
/// a fraction of the exposure paid on each side (0.00005 = 0.005%); financing is in USD per 100,000 USD of exposure per
/// night, positive a charge and negative a credit. <see cref="FinancingEstimated"/> marks a rate the document does not give:
/// the prudent stand-in is the largest known charge, on both sides.
/// </summary>
/// <param name="Pair">The market name: EURUSD.</param>
/// <param name="InstrumentId">The venue's instrument id, when known.</param>
/// <param name="Spread">Bid/ask in pips in normal hours (appendix A, 23:03 UTC).</param>
/// <param name="PauseSpread">Bid/ask in pips inside the daily pause (appendix A, 22:31 UTC).</param>
/// <param name="MaxLeverage">The real account's highest leverage on the pair.</param>
/// <param name="CommissionPerSide">Commission on each side, as a fraction of the exposure.</param>
/// <param name="FinancingBuy">Overnight financing of a buy, USD per 100,000 USD per night.</param>
/// <param name="FinancingSell">Overnight financing of a sale, USD per 100,000 USD per night.</param>
/// <param name="FinancingEstimated">True when the financing is the prudent stand-in, not the document's rate.</param>
public sealed record PairCost(
string Pair,
int? InstrumentId,
decimal Spread,
decimal PauseSpread,
int MaxLeverage,
decimal CommissionPerSide,
decimal FinancingBuy,
decimal FinancingSell,
bool FinancingEstimated)
{
/// <summary>The pip of the pair: 0.01 when the quote is the yen, 0.0001 otherwise.</summary>
public decimal Pip() => FxPairs.Get(Pair).Pip;
/// <summary>The bid/ask in pips, inside the daily pause or out of it.</summary>
public decimal SpreadPips(bool inPause) => inPause ? PauseSpread : Spread;
/// <summary>The commission of one side in pips at a price: rate × price / pip (appendix A).</summary>
public decimal CommissionPips(decimal price) => CommissionPerSide * price / Pip();
/// <summary>The financing rate of a side, USD per 100,000 USD per night; positive is a charge.</summary>
public decimal FinancingRate(Direction side) => side == Direction.Buy ? FinancingBuy : FinancingSell;
}
/// <summary>
/// The costs and margin rules of a venue, with their date and source, copied into the plan of a basket trial (plan, Phase 14,
/// point 2) so that a trial says which costs it ran with and its fingerprint changes with any of them. It serialises like
/// <see cref="TrialPlan"/>: snake_case, null fields left out.
/// </summary>
/// <param name="Venue">The venue: etoro, or none for the comparison configuration.</param>
/// <param name="AsOf">The day the values were read.</param>
/// <param name="Source">Where the values come from, in Italian: the report shows it.</param>
/// <param name="MinimumUsd">The smallest exposure of a position, in USD (section 6.4).</param>
/// <param name="DefaultLeverage">The leverage per position when the plan names none (section 6.5).</param>
/// <param name="Leverages">The leverages the venue allows (section 6.4).</param>
/// <param name="StopMarginShare">
/// The mandatory stop sits at most at this share of the position's margin (section 6.5); null when the venue imposes none.
/// </param>
/// <param name="LiquidationLevel">
/// Every position closes when the equity falls below this share of the initial margin of all open positions (section 6.10,
/// account-level); null when the venue has no such rule.
/// </param>
/// <param name="Pairs">The pairs, in the order of appendix A.</param>
public sealed record VenueCosts(
string Venue,
DateOnly AsOf,
string Source,
decimal MinimumUsd,
int DefaultLeverage,
IReadOnlyList<int> Leverages,
decimal? StopMarginShare,
decimal? LiquidationLevel,
IReadOnlyList<PairCost> Pairs)
{
/// <summary>The exposure the financing rates are quoted on, in USD.</summary>
public const decimal FinancingExposure = 100_000m;
/// <summary>
/// eToro on 1 and 2 December 2026 (research document, appendix A and section 6.3): the 28 pairs with id, real-account
/// leverage, the two bid/ask snapshots, 0.005% commission per side (0.002% on USDJPY, from the fee page) and the Demo
/// cost preview's overnight financing for the twelve legs of section 6.3. Those are stored in USD per 100,000 USD:
/// the document's pips per night × the pip value per 1,000 USD of appendix A × 100 (EURUSD buy 0.88 × 0.092 × 100 =
/// 8.096, the 8.10 USD of section 6.7). The other sixteen pairs pay, on both sides, the largest known charge (AUDCHF's
/// sale, 17.978) and are marked estimated.
/// </summary>
public static VenueCosts Etoro { get; } = BuildEtoro();
/// <summary>
/// The comparison configuration: the same pairs and leverages, no spread, commission or financing, no mandatory stop and
/// no liquidation.
/// </summary>
public static VenueCosts None { get; } = Etoro with
{
Venue = "none",
Source = "Configurazione di confronto: nessun costo, nessuno stop obbligatorio, nessuna chiusura d'ufficio.",
StopMarginShare = null,
LiquidationLevel = null,
Pairs = [.. Etoro.Pairs.Select(p => p with
{
InstrumentId = null,
Spread = 0m,
PauseSpread = 0m,
CommissionPerSide = 0m,
FinancingBuy = 0m,
FinancingSell = 0m,
FinancingEstimated = false,
})],
};
/// <summary>The costs of a pair, or null when the venue does not list it.</summary>
public PairCost? Find(string pair) => Pairs.FirstOrDefault(p => string.Equals(p.Pair, pair, StringComparison.Ordinal));
/// <summary>The costs of a pair; throws, in Italian, when the venue does not list it.</summary>
public PairCost Pair(string pair) =>
Find(pair) ?? throw new ArgumentException($"{pair}: nessun costo per questa coppia nella tabella di {Venue}.", nameof(pair));
/// <summary>
/// The costs at <paramref name="multiplier"/> times (SPEC 12.2, step 3): spread, pause spread, commission and the financing
/// charges grow; financing credits stay as they are, so a larger multiplier never pays more. 1 returns this instance.
/// </summary>
public VenueCosts Scaled(decimal multiplier)
{
ArgumentOutOfRangeException.ThrowIfNegative(multiplier);
if (multiplier == 1m)
{
return this;
}
return this with
{
Pairs = [.. Pairs.Select(p => p with
{
Spread = p.Spread * multiplier,
PauseSpread = p.PauseSpread * multiplier,
CommissionPerSide = p.CommissionPerSide * multiplier,
FinancingBuy = Charge(p.FinancingBuy, multiplier),
FinancingSell = Charge(p.FinancingSell, multiplier),
})],
};
}
/// <summary>Refuses, in Italian, a leverage the venue does not allow or one above the pair's; returns it otherwise.</summary>
public int CheckLeverage(string pair, int leverage)
{
CheckLeverage(leverage);
var cost = Pair(pair);
if (leverage > cost.MaxLeverage)
{
throw new ArgumentException(
string.Create(CultureInfo.InvariantCulture, $"La leva {leverage} è oltre quella del conto reale su {pair}: al massimo {cost.MaxLeverage}."),
nameof(leverage));
}
return leverage;
}
/// <summary>The margin of a position (appendix C): exposure / leverage, in the exposure's currency.</summary>
public decimal Margin(decimal exposureUsd, int leverage)
{
CheckLeverage(leverage);
return exposureUsd / leverage;
}
/// <summary>
/// The farthest the mandatory stop can sit from the entry, in price units (section 6.5, appendix C): share of the margin /
/// leverage × price, so 0.5 / leverage × price. Null when the venue imposes no stop.
/// </summary>
public decimal? StopDistance(decimal price, int leverage)
{
CheckLeverage(leverage);
return StopMarginShare is { } share ? share / leverage * price : null;
}
/// <summary>
/// The farthest stop of one position (section 6.5): the stop is required on every order above leverage 1 and on every
/// sale, so a buy at leverage 1 has none (null; the venue would let it go to 100% of the price, 95% on USDCHF). Refuses a
/// leverage above the pair's.
/// </summary>
public decimal? StopDistance(string pair, Direction side, decimal price, int leverage)
{
CheckLeverage(pair, leverage);
return side == Direction.Buy && leverage == 1 ? null : StopDistance(price, leverage);
}
/// <summary>The farthest stop of one position in pips (table 6.5); null when there is none.</summary>
public decimal? StopDistancePips(string pair, Direction side, decimal price, int leverage) =>
StopDistance(pair, side, price, leverage) is { } distance ? distance / Pair(pair).Pip() : null;
/// <summary>The commission of one side on an exposure, in the exposure's currency.</summary>
public decimal Commission(string pair, decimal exposureUsd) => exposureUsd * Pair(pair).CommissionPerSide;
/// <summary>
/// The overnight financing of a position over <paramref name="nights"/> charged nights (<see cref="FinancingCalendar"/>):
/// exposure / 100,000 × rate × nights, in USD; positive is paid, negative received.
/// </summary>
public decimal Financing(string pair, Direction side, decimal exposureUsd, int nights)
{
ArgumentOutOfRangeException.ThrowIfNegative(nights);
return exposureUsd / FinancingExposure * Pair(pair).FinancingRate(side) * nights;
}
/// <summary>The table as the plan stores it.</summary>
public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json);
public static VenueCosts FromJson(string text) =>
JsonSerializer.Deserialize<VenueCosts>(text, TrialPlan.Json) ?? throw new JsonException("Tabella dei costi vuota");
/// <summary>SHA-256 of <see cref="ToJson"/>: any value changed changes it.</summary>
public string Fingerprint() => TrialPlan.Hash(ToJson());
/// <summary>Equal when every value is: the lists are compared item by item.</summary>
public bool Equals(VenueCosts? other) =>
other is not null
&& string.Equals(Venue, other.Venue, StringComparison.Ordinal)
&& AsOf == other.AsOf
&& string.Equals(Source, other.Source, StringComparison.Ordinal)
&& MinimumUsd == other.MinimumUsd
&& DefaultLeverage == other.DefaultLeverage
&& Leverages.SequenceEqual(other.Leverages)
&& StopMarginShare == other.StopMarginShare
&& LiquidationLevel == other.LiquidationLevel
&& Pairs.SequenceEqual(other.Pairs);
public override int GetHashCode() => HashCode.Combine(Venue, AsOf, MinimumUsd, DefaultLeverage, StopMarginShare, LiquidationLevel, Pairs.Count);
private void CheckLeverage(int leverage)
{
if (!Leverages.Contains(leverage))
{
throw new ArgumentException(
string.Create(CultureInfo.InvariantCulture, $"La leva {leverage} non è ammessa su {Venue}: le leve possibili sono {string.Join(", ", Leverages)}."),
nameof(leverage));
}
}
private static decimal Charge(decimal rate, decimal multiplier) => rate > 0m ? rate * multiplier : rate;
private static VenueCosts BuildEtoro()
{
// Section 6.3, USD per 100,000 USD per night (buy, sell): pips × pip value per 1,000 USD × 100.
var financing = new Dictionary<string, (decimal Buy, decimal Sell)>(StringComparer.Ordinal)
{
["EURUSD"] = (8.096m, -0.46m), // 0.88, −0.05 pip × 0.092
["USDCHF"] = (-7.788m, 15.458m), // −0.66, 1.31 × 0.118
["AUDUSD"] = (1.51m, 6.191m), // 0.10, 0.41 × 0.151
["USDCAD"] = (-0.77m, 8.33m), // −0.11, 1.19 × 0.070
["NZDUSD"] = (8.14m, 0.37m), // 0.44, 0.02 × 0.185
["EURNZD"] = (4.65m, 3.7m), // 0.93, 0.74 × 0.050
["EURAUD"] = (10.37m, -2.745m), // 1.70, −0.45 × 0.061
["AUDCAD"] = (-3.074m, 10.812m), // −0.29, 1.02 × 0.106
["GBPUSD"] = (3.927m, 3.696m), // 0.51, 0.48 × 0.077
["EURGBP"] = (7.92m, -0.36m), // 0.66, −0.03 × 0.120
["AUDCHF"] = (-10.324m, 17.978m), // −0.58, 1.01 × 0.178
["EURCHF"] = (-3.597m, 11.336m), // −0.33, 1.04 × 0.109
};
var largest = financing.Values.Max(f => Math.Max(f.Buy, f.Sell));
// Appendix A: pair, eToro id, real-account leverage, bid/ask at 23:03 UTC and at 22:31 UTC (in the pause), in pips.
(string Pair, int Id, int Leverage, decimal Spread, decimal Pause)[] rows =
[
("EURGBP", 8, 30, 0.4m, 2.3m),
("EURAUD", 12, 20, 1.1m, 8.3m),
("EURNZD", 49, 20, 4.3m, 16.8m),
("EURUSD", 1, 30, 0.1m, 2.2m),
("EURCAD", 13, 30, 0.9m, 8.4m),
("EURCHF", 9, 30, 0.2m, 7.5m),
("EURJPY", 10, 30, 1.6m, 11.2m),
("GBPAUD", 50, 20, 1.2m, 14.9m),
("GBPNZD", 52, 20, 8.3m, 25.0m),
("GBPUSD", 2, 30, 0.2m, 2.3m),
("GBPCAD", 65, 30, 2.0m, 11.0m),
("GBPCHF", 51, 20, 1.0m, 23.3m),
("GBPJPY", 11, 30, 0.9m, 14.8m),
("AUDNZD", 48, 20, 0.8m, 6.9m),
("AUDUSD", 7, 20, 0.1m, 2.1m),
("AUDCAD", 47, 20, 1.0m, 7.1m),
("AUDCHF", 46, 20, 0.9m, 13.5m),
("AUDJPY", 14, 20, 0.7m, 7.0m),
("NZDUSD", 3, 20, 0.1m, 2.8m),
("NZDCAD", 53, 20, 1.6m, 7.3m),
("NZDCHF", 54, 20, 1.0m, 12.2m),
("NZDJPY", 55, 20, 1.6m, 9.8m),
("USDCAD", 4, 30, 0.3m, 4.2m),
("USDCHF", 6, 30, 0.1m, 11.2m),
("USDJPY", 5, 30, 0.3m, 5.8m),
("CADCHF", 56, 30, 0.8m, 11.6m),
("CADJPY", 15, 30, 0.8m, 10.7m),
("CHFJPY", 16, 30, 1.7m, 58.4m),
];
var pairs = rows.Select(r =>
{
var known = financing.TryGetValue(r.Pair, out var rate);
return new PairCost(
r.Pair,
r.Id,
r.Spread,
r.Pause,
r.Leverage,
r.Pair == "USDJPY" ? 0.00002m : 0.00005m,
known ? rate.Buy : largest,
known ? rate.Sell : largest,
!known);
}).ToArray();
return new VenueCosts(
"etoro",
new DateOnly(2026, 12, 2),
"Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026",
BasketMath.VenueMinimumUsd,
5,
[1, 2, 5, 10, 20, 30],
0.5m,
0.5m,
pairs);
}
}
/// <summary>
/// The nights a position pays financing for (section 6.3, «il mercoledì conta triplo»): one rollover at every server day
/// change, 17:00 New York (<see cref="ServerClock"/>), whose New York weekday is Monday to Friday; Wednesday's counts three
/// and there is none on Saturday and Sunday, seven a week. A position opened on a Tuesday before 17:00 and closed on the
/// Friday before 17:00 crosses Tuesday's, Wednesday's and Thursday's: five nights.
/// </summary>
public static class FinancingCalendar
{
/// <summary>The nights charged by the rollover at 17:00 New York of a New York day: 3 on Wednesday, 0 on the weekend, 1 otherwise.</summary>
public static int Units(DateOnly newYorkDay) => newYorkDay.DayOfWeek switch
{
DayOfWeek.Saturday or DayOfWeek.Sunday => 0,
DayOfWeek.Wednesday => 3,
_ => 1,
};
/// <summary>The moment of a New York day's rollover: 17:00 New York, the start of the next server day.</summary>
public static DateTimeOffset Rollover(DateOnly newYorkDay) => ServerClock.DayStart(newYorkDay.AddDays(1));
/// <summary>The nights of the rollovers r with <paramref name="from"/> &lt; r ≤ <paramref name="to"/>; 0 when to is not after from.</summary>
public static int Nights(DateTimeOffset from, DateTimeOffset to)
{
if (to <= from)
{
return 0;
}
// The rollover of New York day d starts server day d + 1, so from < r ≤ to exactly when Day(from) ≤ d < Day(to).
var first = ServerClock.Day(from);
var days = ServerClock.Day(to).DayNumber - first.DayNumber;
var weeks = days / 7;
var nights = weeks * 7;
for (var day = first.AddDays(weeks * 7); day.DayNumber < first.DayNumber + days; day = day.AddDays(1))
{
nights += Units(day);
}
return nights;
}
}
+231
View File
@@ -72,6 +72,165 @@ public static class BasketIndex
return deviation is > 0 ? (index[t] - mean) / deviation : null;
}
/// <summary>
/// The z-score of every bar of a series in one pass (Phase 14): at bar t, (x(t) − mean) / sample standard deviation
/// (n − 1) of the last <paramref name="window"/> values, bar t included — the same value as <see cref="ZScore"/>, to
/// about 1e-12. Not a number before the window is full and where the window is flat. The replica of appendix G and the
/// basket engine both read their signals here, so the two decide on the same bits.
/// </summary>
/// <remarks>
/// Sums of the values minus an anchor slide one bar at a time; every <paramref name="window"/> bars they are computed
/// again from scratch around the exact mean of the window, so the rounding never piles up and far-from-zero levels lose
/// no digits. The series must be compressed: a missing value is an error, not a gap to skip.
/// </remarks>
public static double[] RollingZ(IReadOnlyList<double> x, int window = DefaultWindow)
{
ArgumentNullException.ThrowIfNull(x);
ArgumentOutOfRangeException.ThrowIfLessThan(window, 2);
var values = Compressed(x, nameof(x));
var n = values.Length;
var z = new double[n];
Array.Fill(z, double.NaN);
var sums = new SlidingSums(window);
var equal = 0;
for (var t = 0; t < n; t++)
{
equal = t > 0 && values[t] == values[t - 1] ? equal + 1 : 1;
if (t < window - 1)
{
continue;
}
sums.Advance(values, t);
// A window whose values are all equal is flat by definition (as in ZScore): no z.
var variance = sums.CentredSquares() / (window - 1);
if (equal < window && variance > 0)
{
z[t] = sums.FromMean(values[t]) / Math.Sqrt(variance);
}
}
return z;
}
/// <summary>
/// σ of appendix G.3 at every bar: the population standard deviation (n) of the <paramref name="window"/> − 1 first
/// differences inside the last <paramref name="window"/> values, bar t included. Not a number before the window is
/// full; exactly zero when all those differences are equal. Same sliding sums as <see cref="RollingZ"/>.
/// </summary>
public static double[] RollingSigma(IReadOnlyList<double> x, int window = DefaultWindow)
{
ArgumentNullException.ThrowIfNull(x);
ArgumentOutOfRangeException.ThrowIfLessThan(window, 2);
var values = Compressed(x, nameof(x));
var n = values.Length;
var sigma = new double[n];
Array.Fill(sigma, double.NaN);
if (n < 2)
{
return sigma;
}
var differences = new double[n - 1];
for (var i = 1; i < n; i++)
{
differences[i - 1] = values[i] - values[i - 1];
}
var m = window - 1;
var sums = new SlidingSums(m);
var equal = 0;
for (var i = 0; i < differences.Length; i++)
{
equal = i > 0 && differences[i] == differences[i - 1] ? equal + 1 : 1;
if (i < m - 1)
{
continue;
}
// The difference i ends at bar i + 1.
sums.Advance(differences, i);
sigma[i + 1] = equal >= m ? 0 : Math.Sqrt(Math.Max(sums.CentredSquares() / m, 0));
}
return sigma;
}
/// <summary>The refusal of a series with a missing or infinite value: rolling signals read compressed series only.</summary>
public static void RequireCompressed(IReadOnlyList<double> x, string parameter) => _ = Compressed(x, parameter);
/// <summary>The series as an array (itself when it is one), refused when a value is missing or infinite.</summary>
private static double[] Compressed(IReadOnlyList<double> x, string parameter)
{
ArgumentNullException.ThrowIfNull(x);
var values = x as double[] ?? [.. x];
for (var t = 0; t < values.Length; t++)
{
if (!double.IsFinite(values[t]))
{
throw new ArgumentException($"La serie ha un buco (un valore mancante o non finito) alla barra {t}: va compressa, senza buchi.", parameter);
}
}
return values;
}
/// <summary>
/// The sums Σ(x − a) and Σ(x − a)² over the last <c>count</c> values, a being the anchor. They slide by one value at
/// every bar and are rebuilt exactly, around the exact mean of the window, every <c>count</c> bars.
/// </summary>
private sealed class SlidingSums(int count)
{
private double _anchor;
private double _sum;
private double _squares;
private int _sinceRebuild = -1;
/// <summary>Moves the window so that it ends at <paramref name="t"/>; the first call (and every count-th) rebuilds.</summary>
public void Advance(double[] values, int t)
{
if (_sinceRebuild < 0 || _sinceRebuild == count - 1)
{
Rebuild(values, t);
return;
}
var added = values[t] - _anchor;
var removed = values[t - count] - _anchor;
_sum += added - removed;
_squares += (added * added) - (removed * removed);
_sinceRebuild++;
}
/// <summary>Σ(x − mean)² of the window.</summary>
public double CentredSquares() => _squares - (_sum * _sum / count);
/// <summary>x − mean of the window.</summary>
public double FromMean(double value) => value - _anchor - (_sum / count);
private void Rebuild(double[] values, int t)
{
var from = t - count + 1;
var total = 0d;
for (var i = from; i <= t; i++)
{
total += values[i];
}
_anchor = total / count;
_sum = 0;
_squares = 0;
for (var i = from; i <= t; i++)
{
var d = values[i] - _anchor;
_sum += d;
_squares += d * d;
}
_sinceRebuild = 0;
}
}
/// <summary>
/// σ_short at bar <paramref name="t"/>: the sample standard deviation of the last <paramref name="shortBars"/> first
/// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter.
@@ -130,6 +289,78 @@ public static class BasketIndex
return baseline > 0 ? current / baseline : null;
}
/// <summary>
/// <see cref="Rvol"/> at every bar in one pass (Phase 14, as ADR 0028 asked): σ_short of every bar once, then the median of
/// the last <paramref name="baselineBars"/> of them from a window kept sorted, so each bar costs a binary search and a
/// shift instead of a sort. The same numbers as <see cref="Rvol"/>, bit for bit; not a number where it is null.
/// </summary>
public static double[] RollingRvol(IReadOnlyList<double> index, int baselineBars = DefaultBaselineBars, int shortBars = DefaultShortBars)
{
ArgumentNullException.ThrowIfNull(index);
ArgumentOutOfRangeException.ThrowIfLessThan(baselineBars, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(shortBars, 2);
var n = index.Count;
var rvol = new double[n];
Array.Fill(rvol, double.NaN);
var sigmas = new double[n];
for (var t = 0; t < n; t++)
{
sigmas[t] = ShortSigma(index, t, shortBars) ?? double.NaN;
}
// The window holds σ_short of bars t − baseline + 1 … t, sorted; a missing one makes the whole window unknown.
var window = new double[baselineBars];
var count = 0;
var missing = 0;
for (var t = 0; t < n; t++)
{
if (t >= baselineBars)
{
Remove(sigmas[t - baselineBars]);
}
Insert(sigmas[t]);
if (t + 1 < baselineBars || missing > 0)
{
continue;
}
var middle = baselineBars / 2;
var baseline = baselineBars % 2 == 1 ? window[middle] : (window[middle - 1] + window[middle]) / 2;
rvol[t] = baseline > 0 ? sigmas[t] / baseline : double.NaN;
}
return rvol;
void Insert(double value)
{
if (double.IsNaN(value))
{
missing++;
return;
}
var at = Array.BinarySearch(window, 0, count, value);
at = at < 0 ? ~at : at;
Array.Copy(window, at, window, at + 1, count - at);
window[at] = value;
count++;
}
void Remove(double value)
{
if (double.IsNaN(value))
{
missing--;
return;
}
var at = Array.BinarySearch(window, 0, count, value);
Array.Copy(window, at + 1, window, at, count - at - 1);
count--;
}
}
/// <summary>The volatility filter: a new entry only with a known Rvol no higher than <paramref name="max"/>.</summary>
public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max;
+378
View File
@@ -0,0 +1,378 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Data;
namespace Anubis.Baskets;
/// <summary>
/// The parameters of the stylised replica of appendix G.3: target and averaging distance in σ of the series, the most
/// averagings, the growth of the distance, the basket stop in targets (none when null), the window of the z-score and of
/// σ, the entry threshold.
/// </summary>
public sealed record ReplicaSettings(
double TargetSigma,
double DistanceSigma,
int MaxAveragings,
double Growth = 1,
double? StopTargets = null,
int Window = BasketIndex.DefaultWindow,
double EntryZ = 2)
{
/// <summary>
/// The 15 cases of the «Forex 1999–2026» column of table G.4, in the document's order: five parameter sets, each with no
/// stop, a stop of 90 and one of 30 targets.
/// </summary>
public static IReadOnlyList<ReplicaCase> DocumentCases { get; } = Array.AsReadOnly(BuildCases());
/// <summary>Checks the values; the message is for the user.</summary>
public void Validate()
{
if (!(TargetSigma > 0) || !(DistanceSigma >= 0) || MaxAveragings < 0 || !(Growth > 0) || Window < 3 || !(EntryZ > 0)
|| (StopTargets is { } stop && !(stop > 0)))
{
throw new ArgumentException(string.Create(CultureInfo.InvariantCulture,
$"Parametri della replica non validi: obiettivo {TargetSigma}σ, distanza {DistanceSigma}σ, mediazioni {MaxAveragings}, crescita {Growth}, arresto {StopTargets}, finestra {Window}, ingresso {EntryZ}."));
}
}
private static ReplicaCase[] BuildCases()
{
(string Label, double Target, double Distance, int Averagings, double Growth)[] sets =
[
("2,5 σ · 10 σ · 3", 2.5, 10, 3, 1),
("2 σ · 8 σ · 3", 2, 8, 3, 1),
("3 σ · 12 σ · 3", 3, 12, 3, 1),
("2,5 σ · 4 σ · 3", 2.5, 4, 3, 1),
("2,5 σ · 4 σ crescente · 4", 2.5, 4, 4, 1.3),
];
(string Label, double? Targets)[] stops = [("nessuno", null), ("90 obiettivi", 90), ("30 obiettivi", 30)];
double[] totals = [534, 542, 255, 757, 1_032, -98, 338, 534, 137, 649, 442, -45, 533, 759, 172];
double[] breakEvens = [0.32, 0.26, 0.11, 0.39, 0.40, -0.03, 0.24, 0.33, 0.07, 0.33, 0.16, -0.01, 0.25, 0.25, 0.05];
var cases = new List<ReplicaCase>();
foreach (var set in sets)
{
foreach (var stop in stops)
{
var i = cases.Count;
cases.Add(new ReplicaCase(set.Label, stop.Label,
new ReplicaSettings(set.Target, set.Distance, set.Averagings, set.Growth, stop.Targets), totals[i], breakEvens[i]));
}
}
return [.. cases];
}
}
/// <summary>
/// One row of table G.4: the parameters, the labels as the document writes them, its total in targets and its break-even
/// per position. A row is binding when |total| &gt; 100 targets: ours must have the same sign and stay within the larger of
/// 25 targets and 5% of the document's total.
/// </summary>
public sealed record ReplicaCase(string Label, string StopLabel, ReplicaSettings Settings, double DocumentTotal, double DocumentBreakEven)
{
/// <summary>The largest |total| of a row that is only reported.</summary>
public const double BindingAbove = 100;
public bool Binding => Math.Abs(DocumentTotal) > BindingAbove;
/// <summary>The allowed distance from the document's total: the larger of 25 targets and 5%.</summary>
public double Tolerance => Math.Max(25, 0.05 * Math.Abs(DocumentTotal));
/// <summary>Whether <paramref name="total"/> has the document's sign and stays within <see cref="Tolerance"/>.</summary>
public bool Passes(double total) => Math.Sign(total) == Math.Sign(DocumentTotal) && Math.Abs(total - DocumentTotal) <= Tolerance;
}
/// <summary>How a basket of the replica ends.</summary>
public static class ReplicaExits
{
public const string Target = "target";
public const string Stop = "stop";
/// <summary>Still open on the last bar, valued at its close.</summary>
public const string Open = "open";
}
/// <summary>
/// One basket of the replica: the series, the direction (+1 long, −1 short), the bars and log prices of its entries, the σ
/// frozen at the opening, the bar of the close (null if still open), how it ended and its result in targets.
/// </summary>
public sealed record ReplicaBasket(
int Series,
int Direction,
IReadOnlyList<int> EntryBars,
IReadOnlyList<double> Entries,
double Sigma,
int? ClosedAt,
string Exit,
double Result);
/// <summary>
/// The result of the replica: the total in targets (open baskets at the last close included), the positions (every entry),
/// the baskets, those closed at the target and at the stop, and the baskets themselves.
/// </summary>
public sealed record ReplicaResult(double Total, int Positions, int Baskets, int AtTarget, int Stops, IReadOnlyList<ReplicaBasket> List)
{
public static ReplicaResult Empty { get; } = new(0, 0, 0, 0, 0, []);
/// <summary>The cost per position that would bring the total to zero: total ÷ positions (not a number without positions).</summary>
public double BreakEven => Positions == 0 ? double.NaN : Total / Positions;
/// <summary>The share of baskets closed at the target (not a number without baskets). Shown, never judged.</summary>
public double AtTargetShare => Baskets == 0 ? double.NaN : (double)AtTarget / Baskets;
/// <summary>The results of several series as one, in the order given.</summary>
public static ReplicaResult Combine(IEnumerable<ReplicaResult> results)
{
ArgumentNullException.ThrowIfNull(results);
var total = 0d;
int positions = 0, baskets = 0, atTarget = 0, stops = 0;
var list = new List<ReplicaBasket>();
foreach (var r in results)
{
total += r.Total;
positions += r.Positions;
baskets += r.Baskets;
atTarget += r.AtTarget;
stops += r.Stops;
list.AddRange(r.List);
}
return new ReplicaResult(total, positions, baskets, atTarget, stops, list);
}
}
/// <summary>The control against chance of the replica: the observed break-even, that of every replica, and the share of replicas equal or better.</summary>
public sealed record ReplicaControl(double Observed, IReadOnlyList<double> Replicas, double Share);
/// <summary>
/// The stylised replica of appendix G.3 of the research document of 2 December 2026 (Phase 14, issue #130): generation B on
/// each series alone, in logs, entry and exit on the same close, no costs, no account rules. It is the yardstick the basket
/// engine is checked against, and the way the 15 «Forex 1999–2026» totals of table G.4 are reproduced.
/// </summary>
/// <remarks>
/// <para>The conventions are those that reproduce all 15 totals (ADR of Phase 14). On every series s = ln(close): z and σ
/// come from <see cref="BasketIndex.RollingZ"/> (sample deviation of the last W values, bar t included) and
/// <see cref="BasketIndex.RollingSigma"/> (population deviation of the W − 1 differences inside them); the first bar with a
/// signal is W − 1. At each bar, in this order:</para>
/// <list type="number">
/// <item>No basket: with |z| ≥ entry z one position opens against the deviation at s(t) and σ is frozen. Nothing else
/// happens on that bar.</item>
/// <item>A basket open from an earlier bar, first match wins: the stop (when set) if the basket's loss is at least S
/// targets; the target if dir·(s(t) − mean of the entries) ≥ k_T·σ; an averaging if fewer than M were made, the last entry
/// is at least k_D·σ·g^(averagings made) away against the basket, and z is still beyond the threshold on the entry side.</item>
/// <item>No basket opens on the bar where one closes.</item>
/// </list>
/// <para>A position is worth dir·(s − entry) / (k_T·σ) targets. A basket still open on the last bar is valued at its close.
/// Series are independent; any number can be open together.</para>
/// </remarks>
public static class StylisedReplica
{
/// <summary>The replica on one series of log prices (series index 0).</summary>
public static ReplicaResult Run(IReadOnlyList<double> logs, ReplicaSettings settings) => Run(logs, settings, 0);
/// <summary>The replica on many series, each on its own; the result adds them in order.</summary>
public static ReplicaResult Run(IReadOnlyList<IReadOnlyList<double>> series, ReplicaSettings settings)
{
ArgumentNullException.ThrowIfNull(series);
return ReplicaResult.Combine(series.Select((s, i) => Run(s, settings, i)));
}
/// <summary>
/// The control of G.5: every bar the first differences of all the series change sign together with probability one
/// half (not centred: the replica trades both ways), the series are rebuilt from their first value and the replica runs
/// again. Signs from <see cref="TournamentStatistics.Signs"/> with seed <see cref="TournamentStatistics.ReplicaSeed"/>
/// (seed, k) for repetition k; the share is <see cref="TournamentStatistics.ControlShare"/> on the break-even. The
/// series must share one calendar: the same length, bar t the same moment in all. Repetitions run in parallel; the
/// result does not depend on it.
/// </summary>
public static ReplicaControl Control(IReadOnlyList<IReadOnlyList<double>> series, ReplicaSettings settings, int repetitions, int seed)
{
ArgumentNullException.ThrowIfNull(series);
ArgumentNullException.ThrowIfNull(settings);
ArgumentOutOfRangeException.ThrowIfLessThan(repetitions, 1);
if (series.Count == 0 || series.Any(s => s.Count != series[0].Count))
{
throw new ArgumentException("Il controllo contro il caso vuole serie della stessa lunghezza, sullo stesso calendario.", nameof(series));
}
foreach (var s in series)
{
BasketIndex.RequireCompressed(s, nameof(series));
}
var observed = Run(series, settings).BreakEven;
var length = series[0].Count;
var differences = series.Select(s =>
{
var d = new double[Math.Max(length - 1, 0)];
for (var t = 1; t < length; t++)
{
d[t - 1] = s[t] - s[t - 1];
}
return d;
}).ToList();
// The repetitions are independent and each writes its own slot: in parallel, with the same result as in order.
var replicas = new double[repetitions];
Parallel.For(0, repetitions, k =>
{
// One sign a bar; the difference that ends at bar t takes the sign of bar t (the sign of bar 0 is drawn, unused).
var signs = TournamentStatistics.Signs(length, TournamentStatistics.ReplicaSeed(seed, k));
var barSigns = new ArraySegment<int>(signs, Math.Min(1, length), Math.Max(length - 1, 0));
var rebuilt = new List<IReadOnlyList<double>>(series.Count);
for (var i = 0; i < series.Count; i++)
{
var flipped = Surrogates.Flip(differences[i], barSigns, centred: false);
var s = new double[length];
if (length > 0)
{
s[0] = series[i][0];
}
for (var t = 1; t < length; t++)
{
s[t] = s[t - 1] + flipped[t - 1];
}
rebuilt.Add(s);
}
replicas[k] = Run(rebuilt, settings).BreakEven;
});
return new ReplicaControl(observed, replicas, TournamentStatistics.ControlShare(observed, replicas));
}
/// <summary>
/// The 28 series of ln(close) of the ECB crosses, in the order of <see cref="FxPairs.All"/>, each up to
/// <paramref name="through"/> included. Days without a fixing are simply not there: each series is compressed.
/// </summary>
public static IReadOnlyList<IReadOnlyList<double>> EcbSeries(IReadOnlyDictionary<string, IReadOnlyList<ResearchBar>> crosses, DateOnly through)
{
ArgumentNullException.ThrowIfNull(crosses);
var result = new List<IReadOnlyList<double>>(FxPairs.All.Count);
foreach (var pair in FxPairs.All)
{
if (!crosses.TryGetValue(pair.Name, out var bars))
{
throw new ArgumentException($"Manca la coppia {pair.Name} tra i cambi incrociati della BCE.", nameof(crosses));
}
result.Add(bars
.Where(b => DateOnly.FromDateTime(b.OpensAt.UtcDateTime) <= through)
.OrderBy(b => b.OpensAt)
.Select(b => Math.Log((double)b.Close))
.ToArray());
}
return result;
}
private static ReplicaResult Run(IReadOnlyList<double> series, ReplicaSettings settings, int index)
{
ArgumentNullException.ThrowIfNull(series);
ArgumentNullException.ThrowIfNull(settings);
settings.Validate();
var logs = series as double[] ?? [.. series];
var z = BasketIndex.RollingZ(logs, settings.Window);
var sigma = BasketIndex.RollingSigma(logs, settings.Window);
var kT = settings.TargetSigma;
var entryZ = settings.EntryZ;
var list = new List<ReplicaBasket>();
var total = 0d;
int positions = 0, atTarget = 0, stops = 0;
List<int>? bars = null;
List<double>? entries = null;
int direction = 0, averagings = 0;
var frozen = 0d;
for (var t = 0; t < logs.Length; t++)
{
if (double.IsNaN(z[t]) || double.IsNaN(sigma[t]))
{
continue;
}
var s = logs[t];
if (entries is null)
{
if (Math.Abs(z[t]) >= entryZ && sigma[t] > 0)
{
direction = z[t] > 0 ? -1 : 1;
bars = [t];
entries = [s];
frozen = sigma[t];
averagings = 0;
positions++;
}
continue;
}
var result = Targets(entries, direction, s, kT * frozen);
string? exit = null;
if (settings.StopTargets is { } stop && -result >= stop)
{
exit = ReplicaExits.Stop;
stops++;
}
else if (direction * (s - Mean(entries)) >= kT * frozen)
{
exit = ReplicaExits.Target;
atTarget++;
}
else if (averagings < settings.MaxAveragings
&& direction * (entries[^1] - s) >= settings.DistanceSigma * frozen * Math.Pow(settings.Growth, averagings)
&& (direction == 1 ? z[t] <= -entryZ : z[t] >= entryZ))
{
bars!.Add(t);
entries.Add(s);
averagings++;
positions++;
}
if (exit is not null)
{
list.Add(new ReplicaBasket(index, direction, bars!, entries, frozen, t, exit, result));
total += result;
bars = null;
entries = null;
}
}
if (entries is not null)
{
var result = Targets(entries, direction, logs[^1], kT * frozen);
list.Add(new ReplicaBasket(index, direction, bars!, entries, frozen, null, ReplicaExits.Open, result));
total += result;
}
return new ReplicaResult(total, positions, list.Count, atTarget, stops, list);
}
/// <summary>The basket's value in targets at log price <paramref name="s"/>: Σ dir·(s − entry), over one target.</summary>
private static double Targets(List<double> entries, int direction, double s, double target)
{
var sum = 0d;
foreach (var e in entries)
{
sum += direction * (s - e);
}
return sum / target;
}
private static double Mean(List<double> entries)
{
var sum = 0d;
foreach (var e in entries)
{
sum += e;
}
return sum / entries.Count;
}
}
+98
View File
@@ -0,0 +1,98 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Strategies;
/// <summary>
/// The family «Rientro tra strumenti» of the research document of 2 December 2026 (Phase 14, issue #129): baskets that bet on
/// the return of a currency relation to its mean. One identifier for every sub-variant (generation, signal, units, exit,
/// profile), so every attempt counts in the deflated Sharpe of the next ones (<see cref="TrialStore.PriorAsync"/>). A research
/// family only, judged by the <see cref="BasketTrialEngine"/>: never an <see cref="IStrategyFamily"/>, never in the
/// catalogue the bot trades from. Choice axes are codes: generation 1 = A (two legs), 2 = B (one pair); signal 1 = z of the
/// pip sum, 2 = z of the log index; units 1 = pips, 2 = σ; exit 1 = pip sum (section 4.5), 2 = mean of the entries (G.3);
/// profile 1 = Fedele, 2 = Prudente.
/// </summary>
public sealed class BasketReversionFamily : IResearchFamily
{
public const string FamilyId = "basket_reversion";
public static BasketReversionFamily Instance { get; } = new();
/// <summary>Generation A: the five spreads of the five-spread edition (section 3.3), all chains.</summary>
public static IReadOnlyList<BasketUnit> GenerationA { get; } = [.. Relations.DocumentedSpreads.Take(5).Select(s => BasketUnit.Of(s.A, s.B))];
/// <summary>Generation B: the ten symbols of the ten-symbol edition (section 4.8), each on its own.</summary>
public static IReadOnlyList<BasketUnit> GenerationB { get; } =
[.. new[] { "EURUSD", "USDCHF", "AUDUSD", "USDCAD", "GBPUSD", "EURGBP", "NZDUSD", "AUDCHF", "EURCHF", "AUDCAD" }.Select(p => BasketUnit.OnePair(FxPairs.Get(p)))];
public string Id => FamilyId;
public string Version => "1";
public string Name => "Rientro tra strumenti";
public string Description =>
"Dal documento di ricerca del 2 dicembre 2026: quando l'indice di due cambi legati, o di un cambio solo, si allontana di due "
+ "deviazioni dalla sua media recente, apre un paniere contro lo scostamento; se il prezzo va ancora contro, aggiunge livelli "
+ "uguali al primo, mai più grandi; chiude tutto all'obiettivo. Solo ricerca: nessun ordine, nemmeno finto.";
public IReadOnlyList<ParameterSpec> Parameters { get; } =
[
new("generation", "Generazione (1 = due gambe, 2 = un cambio)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true },
new("signal", "Segnale (1 = somma dei pip, 2 = logaritmi)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true },
new("units", "Unità (1 = pip, 2 = σ)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true },
new("target", "Obiettivo (pip o σ)", 10m, [10m], 0.1m, 200m),
new("distance", "Distanza di mediazione (pip o σ)", 40m, [40m], 0m, 2_000m),
new("growth", "Crescita della distanza", 1m, [1m], 1m, 2m),
new("averagings", "Mediazioni al massimo", 3m, [3m], 0m, 4m, Whole: true),
new("window", "Finestra (barre)", 100m, [100m], 10m, 1_000m, Whole: true),
new("entry_z", "Soglia di ingresso (z)", 2m, [2m], 0.5m, 5m),
new("exit", "Uscita (1 = somma dei pip, 2 = media degli ingressi)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true },
new("profile", "Profilo (1 = Fedele, 2 = Prudente)", 1m, [1m], 1m, 2m, Whole: true) { Choices = true },
new("max_open", "Panieri aperti insieme", 2m, [2m], 1m, 10m, Whole: true),
new("lot", "Lotti per 10.000 di capitale", 0.01m, [0.01m], 0.001m, 1m),
];
/// <summary>Codes outside their choices, and four averagings without growth (the document allows four only with 1.3), make no sense.</summary>
public bool Accepts(StrategyParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
bool Code(string name) => parameters[name] is 1m or 2m;
return Code("generation") && Code("signal") && Code("units") && Code("exit") && Code("profile")
&& (parameters.Whole("averagings") <= 3 || parameters["growth"] > 1m);
}
/// <summary>
/// The rules of a variant for the engine: the document's filters on (Rvol 2, correlation 0.6 on the expected sign, three
/// costs, open baskets), leverage 5, decision on the close and execution at the next open. The hourly window is on for
/// generation B, as in the document; on bars of a day or longer no window of the day applies.
/// </summary>
public BasketRules Rules(StrategyParameters parameters, BasketMode mode, string timeframe)
{
ArgumentNullException.ThrowIfNull(parameters);
if (!Accepts(parameters))
{
throw new ArgumentException($"Variante non valida per {Name}: {parameters}.", nameof(parameters));
}
var generationB = parameters.Whole("generation") == 2;
return new BasketRules(generationB ? GenerationB : GenerationA)
{
Signal = parameters.Whole("signal") == 2 ? BasketSignal.ZScoreLog : BasketSignal.ZScorePipSum,
Measure = parameters.Whole("units") == 2 ? BasketMeasure.Sigma : BasketMeasure.Pips,
Target = parameters["target"],
Distance = parameters["distance"],
Growth = parameters["growth"],
MaxAveragings = parameters.Whole("averagings"),
Window = parameters.Whole("window"),
EntryZ = (double)parameters["entry_z"],
Exit = parameters.Whole("exit") == 2 ? BasketExitRule.MeanOfEntries : BasketExitRule.PipSum,
Profile = parameters.Whole("profile") == 2 ? BasketProfiles.Prudente : BasketProfiles.Fedele,
MaxOpenBaskets = parameters.Whole("max_open"),
LotPer10k = parameters["lot"],
Mode = mode,
Session = generationB && Timeframes.IsIntraday(timeframe),
};
}
}
+23
View File
@@ -102,6 +102,29 @@ public static class ReasonCatalog
["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.",
["protected_restart"] = "Deciso prima del ripristino: non parte, potrebbe essere già partito allora.",
["recovered"] = "Recuperato dopo un'assenza.",
// Baskets (Phase 14): exits.
["target"] = "Obiettivo raggiunto: il paniere si chiude tutto.",
["stop_basket"] = "Stop del paniere (profilo Prudente, o stop in obiettivi del confronto con la replica): il paniere si chiude.",
["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.
["gate_open_loss"] = "Perdita aperta pari o oltre il 2% del saldo: niente nuovi panieri, le mediazioni continuano.",
["paused_until_next_day"] = "Dopo lo stop sul conto niente ingressi fino al cambio di giorno del server, alle 17 di New York.",
["half_size"] = "Limiti di rischio: il livello parte a metà, o a un quarto, della misura.",
["below_venue_minimum"] = "Livello sotto il minimo della piattaforma, 1.000 dollari per posizione: non parte.",
["margin_limit"] = "Margine impegnato oltre il 40% del patrimonio: niente nuovi livelli.",
["max_positions"] = "Raggiunto il numero massimo di posizioni aperte, 9 sul conto Demo condiviso: niente nuovi livelli.",
["opposite_position"] = "C'è già una posizione opposta sullo stesso strumento: ingresso scartato.",
["currency_exposure"] = "Esposizione netta su una valuta oltre due ingressi.",
["cost_rule"] = "Obiettivo sotto tre volte il costo di andata e ritorno del paniere.",
["rvol_filter"] = "Volatilità recente oltre il doppio del solito, o non ancora nota: niente nuovi panieri.",
["correlation_low"] = "Correlazione tra le due gambe troppo bassa sul segno atteso: niente paniere.",
["max_open_baskets"] = "Già aperti tutti i panieri ammessi insieme.",
["clock_window"] = "Fuori dall'orario degli ingressi: fine settimana, pausa giornaliera o fascia oraria.",
};
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
+280
View File
@@ -0,0 +1,280 @@
using System.IO.Compression;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Server;
namespace Anubis.Tests;
/// <summary>
/// "anubis backtest baskets" (Phase 14, issue #131): from the command line, on the database of this run (SQLite here,
/// PostgreSQL in CI), with the ECB history of the research document already in the research folder and no network. The
/// plan is written before the trial, read back and run only when it is still the one written; every run counts the earlier
/// ones; the report is written whatever the verdict.
/// </summary>
[TestClass]
public sealed class BasketCommandTests
{
private const string EcbFile = "free/ecb-hist-1999-2026-12-02.csv";
private static readonly DateOnly To = new(2001, 12, 31);
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ABasketTrialRunsFromTheCommandLineWithItsPlanIntact()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
await using var engine = postgres;
var data = TempFolder.Create("baskets");
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");
var report = Path.Combine(outDir, BasketReport.Strategy + ".md");
var store = new TrialStore(db, clock);
var network = new FakeHttp();
string[] args = ["baskets", "--offline", "--to", "2001-12-31", "--control", "5", "--out", outDir, "--platform", "docker", "--data-dir", data];
async Task<(int Code, string Text)> RunAsync()
{
using var output = new StringWriter();
var code = await BasketCommand.RunAsync([.. args.Skip(1)], output, env, network, clock).ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(1));
return (code, output.ToString());
}
// The first run: replica, control and trial, the plan written and judged as it was written.
var written = BasketProtocol.Plan(To, clock.UtcNow).Plan;
var (code, text) = await RunAsync().ConfigureAwait(false);
Assert.AreEqual(0, code, text);
StringAssert.Contains(text, "13 su 13 righe vincolanti dentro la tolleranza");
StringAssert.Contains(text, "Esito: ");
StringAssert.Contains(text, "Rapporto scritto in " + report);
var markdown = await File.ReadAllTextAsync(report).ConfigureAwait(false);
StringAssert.Contains(markdown, "**Esito: ");
StringAssert.Contains(markdown, "13 righe vincolanti su 13 dentro la tolleranza.");
StringAssert.Contains(markdown, "`anubis backtest baskets --to 2001-12-31 --control 5`");
StringAssert.Contains(markdown, "| 5 | 20261202 |");
Assert.AreEqual(0, network.Requests.Count, "offline with the cached history: no request");
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".outcome.json")), "no outcome file for the basket family");
var first = (await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
Assert.AreEqual(TrialStatuses.Done, first.Status, first.Error);
Assert.IsTrue(first.PlanIntact);
Assert.AreEqual(TrialPlan.Hash(written.ToJson()), first.PlanHash);
Assert.AreEqual(written.ToJson(), first.Plan.ToJson());
Assert.AreEqual(BasketModes.AsLive, first.Plan.Mode);
Assert.AreEqual(VenueCosts.Etoro.Fingerprint(), first.Plan.Costs!.Fingerprint());
Assert.AreEqual(BasketEngine.Version, first.Plan.Engine);
Assert.AreEqual(BasketProtocol.Capital, first.Plan.InitialCapital);
Assert.AreEqual(4, first.Variants);
var judged = BacktestReport.FromJson((await store.ReportJsonAsync(first.Id, CancellationToken.None).ConfigureAwait(false))!);
Assert.AreEqual(first.PlanHash, judged.PlanHash);
Assert.AreEqual(4, judged.TrialsCounted);
StringAssert.Contains(markdown, "`" + first.PlanHash[..12] + "`");
// The same plan again: accepted, a trial of its own, and the first one counts in its deflated Sharpe.
(code, text) = await RunAsync().ConfigureAwait(false);
Assert.AreEqual(0, code, text);
StringAssert.Contains(text, "prove precedenti contate: 1");
var trials = await store.ListAsync(10, CancellationToken.None).ConfigureAwait(false);
Assert.HasCount(2, trials);
Assert.IsTrue(trials.All(t => t.Status == TrialStatuses.Done && t.PlanIntact));
Assert.AreEqual(8, BacktestReport.FromJson((await store.ReportJsonAsync(trials[0].Id, CancellationToken.None).ConfigureAwait(false))!).TrialsCounted);
var kept = await File.ReadAllTextAsync(report).ConfigureAwait(false);
// A plan changed in the register after it was written: refused, recorded as failed, the report left as it was. First
// its hash no longer matches; then the grid is changed and the hash written again to match.
string WiderGrid()
{
var grid = new SortedDictionary<string, IReadOnlyList<decimal>>(BasketProtocol.Grid.ToDictionary(), StringComparer.Ordinal) { ["distance"] = [4m, 12m] };
var json = (BasketProtocol.Plan(To, clock.UtcNow).Plan with { Grid = grid }).ToJson();
return $"SET plan = '{json.Replace("'", "''", StringComparison.Ordinal)}', plan_hash = '{TrialPlan.Hash(json)}'";
}
(Func<string> Sql, string Error)[] tampers =
[
(() => "SET plan_hash = '0'", "Il piano registrato non corrisponde più alla sua impronta: la prova non parte."),
(WiderGrid, "Il piano registrato non è quello appena scritto da questo comando: la prova non parte."),
];
foreach (var (sql, error) in tampers)
{
await TamperAsync(db, sql()).ConfigureAwait(false);
(code, text) = await RunAsync().ConfigureAwait(false);
await UntamperAsync(db).ConfigureAwait(false);
Assert.AreEqual(1, code, text);
StringAssert.Contains(text, "Non riuscito: " + error);
var refused = (await store.ListAsync(1, CancellationToken.None).ConfigureAwait(false))[0];
Assert.AreEqual(TrialStatuses.Failed, refused.Status);
Assert.AreEqual(error, refused.Error);
Assert.AreEqual(kept, await File.ReadAllTextAsync(report).ConfigureAwait(false), "a refused trial writes no report");
}
Assert.AreEqual(2, (await store.PriorAsync(BasketReport.Strategy, Guid.Empty, CancellationToken.None).ConfigureAwait(false)).Trials, "refused trials are not counted");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task OfflineWithoutTheEcbHistoryTheCommandStopsInItalian()
{
var data = TempFolder.Create("baskets-offline");
try
{
var env = ServerHarness.DockerSqlite();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
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);
}
var network = new FakeHttp();
using var output = new StringWriter();
Assert.AreEqual(1, await BasketCommand.RunAsync(["--offline", "--platform", "docker", "--data-dir", data], output, env, network, clock).ConfigureAwait(false));
StringAssert.Contains(output.ToString(), "Non riuscito: Manca lo storico dei cambi BCE già scaricato");
Assert.AreEqual(0, network.Requests.Count);
using var usage = new StringWriter();
Assert.AreEqual(2, await BacktestCommand.RunAsync(["baskets", "--control", "zero", "--platform", "docker", "--data-dir", data], usage, env).ConfigureAwait(false));
StringAssert.Contains(usage.ToString(), "base|candidates|baskets");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
[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)
{
if (db.Engine == Anubis.Platform.DbEngine.Postgres)
{
await db.WriteAsync(s => s.ExecuteAsync(
$"CREATE FUNCTION tamper_plan() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; RETURN NULL; END $$",
CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
await db.WriteAsync(s => s.ExecuteAsync("CREATE TRIGGER tamper AFTER INSERT ON backtest_trials FOR EACH ROW EXECUTE FUNCTION tamper_plan()", CancellationToken.None),
CancellationToken.None).ConfigureAwait(false);
return;
}
await db.WriteAsync(s => s.ExecuteAsync($"CREATE TRIGGER tamper AFTER INSERT ON backtest_trials BEGIN UPDATE backtest_trials {set} WHERE id = NEW.id; END",
CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
}
private static async Task UntamperAsync(Database db)
{
if (db.Engine == Anubis.Platform.DbEngine.Postgres)
{
await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper ON backtest_trials", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
await db.WriteAsync(s => s.ExecuteAsync("DROP FUNCTION tamper_plan()", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
return;
}
await db.WriteAsync(s => s.ExecuteAsync("DROP TRIGGER tamper", CancellationToken.None), CancellationToken.None).ConfigureAwait(false);
}
/// <summary>The fixture of the research document's ECB history, zipped as the ECB serves it and as the cache keeps it.</summary>
private static byte[] EcbZip()
{
using var zip = new MemoryStream();
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open()))
{
writer.Write(Fixture.Text(EcbFile));
}
return zip.ToArray();
}
}
+541
View File
@@ -0,0 +1,541 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The basket engine of Phase 14 (issue #127): a margin account with independent positions, bought at the ask and sold at the
/// bid, the venue's mandatory stop, liquidation, financing, the document's account rules (9% stop, 2% gate) and, «come dal
/// vivo», the limits of SPEC 9.2 and of the plan's margin table. Every money figure is computed by hand in the comment next
/// to it; the comparison configuration is checked against the stylised replica of appendix G.
/// </summary>
[TestClass]
public sealed class BasketEngineTests
{
private static readonly FxPair EurUsd = FxPairs.Get("EURUSD");
private static readonly FxPair UsdChf = FxPairs.Get("USDCHF");
private static readonly FxPair UsdJpy = FxPairs.Get("USDJPY");
private static readonly FxPair GbpUsd = FxPairs.Get("GBPUSD");
[TestMethod]
[TestCategory(Category.Unit)]
public void AToyTwoLegBasketGivesTheResultComputedByHand()
{
// Tuesday 10 March 2026 from 10:00 UTC (06:00 in New York): no pause, no weekend, no rollover (21:00 UTC).
// EURUSD bid/ask one pip wide, USDCHF two pips. Bars 0–9 alternate, so the chain index X = E/pip + C/pip alternates
// 19,000 / 19,004; bar 10 drops to 18,985: z = −2.67 over 10 bars, the spread is bought (both legs long, chain s = +1).
var first = new DateTimeOffset(2026, 3, 10, 10, 0, 0, TimeSpan.Zero);
decimal[] e = [.. Alt(1.1000m, 1.1002m, 10), 1.0990m, 1.0990m, 1.0997m, 1.0998m, 1.1000m];
decimal[] c = [.. Alt(0.8000m, 0.8002m, 10), 0.7995m, 0.7995m, 0.8000m, 0.8001m, 0.8003m];
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
{
["EURUSD"] = [.. e.Select(m => BasketSynthetic.Mid(m, 0.0001m))],
["USDCHF"] = [.. c.Select(m => BasketSynthetic.Mid(m, 0.0002m))],
});
var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
LotPer10k = 0.1m,
Mode = BasketMode.AsDocument,
MaxRvol = null,
MinCorrelation = null,
};
var result = Run(data, rules, VenueCosts.Etoro, 100_000m);
// Units: 0.1 × 100,000 / 10,000 × 100,000 = 100,000 on each leg (EUR 1.0990 and USD 1 both above 1,000 USD).
// Filled at bar 11's open: EURUSD bought at the ask 1.09905, USDCHF at the ask 0.7996.
// Bar 12 close: pips (1.09965 − 1.09905) + (0.7999 − 0.7996) = 6 + 3 = 9 < 10; bar 13: 7 + 4 = 11 ≥ 10: target.
// Sold at bar 14's open at the bid: EURUSD 1.09995, USDCHF 0.8002.
// EURUSD: 100,000 × 0.0009 = 90.00 USD. USDCHF: 100,000 × 0.0006 = 60 CHF ÷ 0.8003 (the mid at the exit) = 74.9719 USD.
// Commission 0.005% a side on the USD exposure at the mid: opening 109,900 → 5.495 and 100,000 → 5.00; closing
// 110,000 → 5.50 and 100,000 → 5.00; together 20.995. No rollover crossed: no financing.
// Result: 90 + 74.97188554 − 20.995 = 143.97688554 → 143.98 USD.
var basket = result.Run.Baskets.Single();
Assert.AreEqual(BasketReasons.Target, basket.ExitReason);
Assert.AreEqual(1, basket.Levels);
Assert.AreEqual(100_000m, basket.Units);
Assert.AreEqual(143.98m, Math.Round(basket.Result, 2));
Assert.AreEqual(143.98m, Math.Round(result.Run.NetResult, 2));
Assert.AreEqual(20.995m, result.Commission);
Assert.AreEqual(0m, result.Financing);
Assert.AreEqual(20.995m, result.Run.Fees);
var fills = result.Run.Fills;
Assert.AreEqual(4, fills.Count);
Assert.AreEqual(1.09905m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Buy).Price);
Assert.AreEqual(0.7996m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Buy).Price);
Assert.AreEqual(1.09995m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Sell).Price);
Assert.AreEqual(0.8002m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Sell).Price);
var trace = result.Traces.Single();
Assert.AreEqual(11, trace.Positions[0].EntryBar);
Assert.AreEqual(14, trace.Positions[0].ExitBar);
Assert.AreEqual(143.98m, Math.Round(trace.Positions.Sum(p => p.Result), 2));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheAccountStopFiresAtTheExactThresholdAndResumesAtTheServerDayChange()
{
// Tuesday 13 January 2026 from 13:00 UTC (08:00 New York); the server day changes at 17:00 New York, 22:00 UTC.
// 100,000 EURUSD bought at exactly 1.0000 on bar 11 (no spread, no cost): balance 10,000.
// Bar 11 closes at 0.99101: open loss 899 / 10,000 = 8.99%, nothing. Bar 12 closes at 0.9910: 9.00%, the stop fires.
var first = new DateTimeOffset(2026, 1, 13, 13, 0, 0, TimeSpan.Zero);
var rows = new List<(QuoteSide, QuoteSide)>();
rows.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
rows.Add(BasketSynthetic.Mid(0.9990m, 0m));
rows.Add(Same(new QuoteSide(1.0000m, 1.0000m, 0.99101m, 0.99101m)));
rows.Add(Same(new QuoteSide(0.99101m, 0.99101m, 0.9910m, 0.9910m)));
rows.AddRange(Alt(0.9910m, 0.9911m, 12).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 13–24
rows.Add(BasketSynthetic.Mid(0.9890m, 0m)); // bar 25, 19:15 UTC: a signal
rows.AddRange(Alt(0.9890m, 0.9891m, 10).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 26–35
rows.Add(BasketSynthetic.Mid(0.9870m, 0m)); // bar 36, 22:00 UTC: a signal
rows.Add(BasketSynthetic.Mid(0.9870m, 0m));
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]> { ["EURUSD"] = [.. rows] });
var rules = SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m, ClockWindows = false };
var result = Run(data, rules, VenueCosts.None);
var stops = result.Events.Where(x => x.Reason == BasketReasons.AccountStop).ToList();
Assert.AreEqual(1, stops.Count, "8.99% does not fire, 9.00% does");
var trigger = first.AddMinutes(15 * 13);
Assert.AreEqual(trigger, stops[0].At, "at the close of bar 12");
Assert.AreEqual(BasketReasons.AccountStop, result.Run.Baskets[0].ExitReason);
Assert.AreEqual(-900m, result.Run.Baskets[0].Result);
var resume = ServerClock.NextDayStart(trigger);
Assert.AreEqual(new DateTimeOffset(2026, 1, 13, 22, 0, 0, TimeSpan.Zero), resume);
var paused = result.Events.Single(x => x.Reason == BasketReasons.PausedUntilNextDay);
Assert.AreEqual(first.AddMinutes(15 * 26), paused.At, "the signal of bar 25 is refused");
Assert.IsFalse(result.Events.Any(x => x.Kind is BasketEventKinds.Open or BasketEventKinds.Add && x.At > trigger && x.At <= resume));
var reopened = result.Events.Where(x => x.Kind == BasketEventKinds.Open && x.At > trigger).ToList();
Assert.AreEqual(1, reopened.Count);
Assert.AreEqual(resume.AddMinutes(15), reopened[0].At, "the first bar of the next server day opens");
// During the daily pause the stop reads mid prices: a bid of 0.9900 and an ask of 1.0100 around a mid of 1.0000 would
// be a 10% loss at the bid, but the mid has not moved. The same quote outside the pause fires the stop.
Assert.AreEqual(0, PauseRun(wideAt: 16).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 16 closes at 17:15 New York: in the pause");
Assert.AreEqual(1, PauseRun(wideAt: 12).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 12 closes at 16:15 New York: outside");
static BasketRunResult PauseRun(int wideAt)
{
var start = new DateTimeOffset(2026, 1, 13, 18, 0, 0, TimeSpan.Zero);
var quotes = new List<(QuoteSide, QuoteSide)>();
quotes.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
quotes.Add(BasketSynthetic.Mid(0.9990m, 0m));
for (var t = 11; t < 20; t++)
{
quotes.Add(t == wideAt ? BasketSynthetic.Mid(1.0000m, 0.0200m) : BasketSynthetic.Mid(1.0000m, 0m));
}
var pauseData = BasketSynthetic.Quarters(start, new Dictionary<string, (QuoteSide, QuoteSide)[]> { ["EURUSD"] = [.. quotes] });
return Run(pauseData, SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m }, VenueCosts.None);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTwoPercentGateStopsNewBasketsButLetsAveragingThrough()
{
// 15,000 EURUSD bought at 0.9985; bar 12 closes at 0.9840: open loss 217.50 / 10,000 = 2.175%. The averaging rule
// holds (−145 pips ≤ −15, z still ≤ −2) and goes through; USDJPY's signal on the same bar is refused by the gate.
var result = Run(GateData(), GateRules(BasketMode.AsDocument), VenueCosts.None);
var eur = result.Traces.Single(x => x.Unit == "EURUSD");
Assert.AreEqual(2, eur.Levels);
Assert.AreEqual(13, eur.Positions[1].EntryBar);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
var refused = result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused);
Assert.AreEqual(BasketReasons.GateOpenLoss, refused.Reason);
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.GateOpenLoss));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveADayAtMinusTwoPercentStopsAveragingToo()
{
// The same days «come dal vivo»: the equity falls from 10,000 to 9,782.50 in one day (−2.175%), so SPEC 9.2 blocks new
// baskets and averaging for 24 hours.
var result = Run(GateData(), GateRules(BasketMode.AsLive), VenueCosts.None);
var eur = result.Traces.Single(x => x.Unit == "EURUSD");
Assert.AreEqual(1, eur.Levels);
Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused).Reason);
Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused).Reason);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveHalfSizeAndQuarterSizeFollowSpec92()
{
// 10,000 EURUSD bought at 0.9985 fall 6% in a day: the Prudente basket stop closes them (5.99% of equity, over 1%).
// The week is −5.99%: SPEC 9.2 halves the size for seven days, so GBPUSD three days later opens 5,000 units, not 10,000.
var half = Run(SizeData(0.06), SizeRules(), VenueCosts.None);
var gbp = half.Traces.Single(x => x.Unit == "GBPUSD");
Assert.AreEqual(5_000m, gbp.Positions[0].Units);
Assert.AreEqual(BasketReasons.StopBasket, half.Run.Baskets[0].ExitReason);
Assert.AreEqual(1, half.Run.Notes.Count(n => n.Reason == BasketReasons.HalfSize));
// An 11% fall: the 9% account stop closes everything; the week is −10.98% and so is the fall from the high: both halve,
// a quarter together. 2,500 units.
var quarter = Run(SizeData(0.11), SizeRules(), VenueCosts.None);
Assert.AreEqual(BasketReasons.AccountStop, quarter.Run.Baskets[0].ExitReason);
Assert.AreEqual(2_500m, quarter.Traces.Single(x => x.Unit == "GBPUSD").Positions[0].Units);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveALevelBelowTheVenueMinimumDoesNotStart()
{
// With 1,000 USD of capital the lot gives 1,000 units (EURUSD raised to 1,002 to reach 1,000 USD). After the 6% fall
// the GBPUSD level would be 500 units, 649.25 USD: under the venue minimum of 1,000 USD, so it does not start.
var result = Run(SizeData(0.06), SizeRules(), VenueCosts.None, 1_000m);
Assert.AreEqual(1_002m, result.Traces.Single(x => x.Unit == "EURUSD").Positions[0].Units);
Assert.IsFalse(result.Traces.Any(x => x.Unit == "GBPUSD"));
Assert.AreEqual(BasketReasons.BelowVenueMinimum, result.Events.Single(x => x.Unit == "GBPUSD" && x.Kind == BasketEventKinds.Refused).Reason);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveTheMarginLimitAndThePositionLimitRefuseEntries()
{
// Ten pairs signal on the same bar. With 0.01 lots every level is small: nine open, the tenth would be the tenth
// position of the shared Demo and is refused.
var data = TenPairs();
var small = Run(data, TenRules(0.01m), VenueCosts.None);
Assert.AreEqual(9, small.Events.Count(x => x.Kind == BasketEventKinds.Open));
Assert.AreEqual(BasketReasons.PositionLimit, small.Events.Single(x => x.Kind == BasketEventKinds.Refused).Reason);
// With 0.05 lots the margin committed reaches 40% of the equity first: the levels after it are refused.
var large = Run(data, TenRules(0.05m), VenueCosts.None);
var opened = large.Events.Count(x => x.Kind == BasketEventKinds.Open);
Assert.IsTrue(opened is > 0 and < 9, $"{opened} opened");
Assert.IsTrue(large.Events.Where(x => x.Kind == BasketEventKinds.Refused).All(x => x.Reason == BasketReasons.MarginLimit));
Assert.AreEqual(10 - opened, large.Events.Count(x => x.Reason == BasketReasons.MarginLimit));
var margin = large.Run.Equity.Max(p => p.Invested);
Assert.IsTrue(margin <= 0.40m * 10_000m, $"margin {margin}");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveNoOppositePositionOnTheSameInstrument()
{
// The chain EURUSD + USDCHF is bought on bar 10 (long EURUSD). On bar 12 EURUSD alone signals a sale: «come dal vivo»
// it would face the long EURUSD of the chain and is refused; «alla lettera» it opens.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.1000, 1.1000, .. Enumerable.Repeat(1.1040, 8)];
double[] c = [.. BasketSynthetic.Alternate(0.8000, 0.8002, 10), .. Enumerable.Repeat(0.7960, 10)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["USDCHF"] = c });
var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf), BasketUnit.OnePair(EurUsd)])
{
Window = 10,
Target = 1_000m,
Distance = 1_000m,
MaxOpenBaskets = 5,
MaxRvol = null,
MinCorrelation = null,
};
var live = Run(data, rules with { Mode = BasketMode.AsLive }, VenueCosts.None);
var refused = live.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused);
Assert.AreEqual(BasketReasons.OppositePosition, refused.Reason);
Assert.AreEqual(1, live.Traces.Count);
var letter = Run(data, rules with { Mode = BasketMode.AsDocument }, VenueCosts.None);
Assert.AreEqual(2, letter.Traces.Count);
Assert.AreEqual(-1, letter.Traces.Single(x => x.Unit == "EURUSD").Direction);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void LiquidationClosesEverythingBelowHalfTheMargin()
{
// 1,000 USD of capital, 9,000 EURUSD bought at the ask 0.998505: exposure 8,986.50 at the mid, margin at leverage 5
// 1,797.30, half of it 898.65. A fall of 1.5% in a day leaves about 862 of equity: below half the margin, every
// position closes at that close. A fall of 1.0% leaves about 906.5 (balance 999.55 less four nights of financing,
// 2.91, less 90.09 at the bid): no liquidation, but the 9% account stop (90.09 / 996.64 = 9.04%).
var deep = Run(LiquidationData(0.9835), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
Assert.AreEqual(BasketReasons.Liquidation, deep.Run.Baskets.Single().ExitReason);
Assert.AreEqual(12, deep.Traces.Single().Positions.Single().ExitBar);
Assert.AreEqual(0.983495m, deep.Traces.Single().Positions.Single().ExitPrice, "the bid of that close");
Assert.AreEqual(1, deep.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
var shallow = Run(LiquidationData(0.9885), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
Assert.AreEqual(BasketReasons.AccountStop, shallow.Run.Baskets.Single().ExitReason);
Assert.AreEqual(0, shallow.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
}
[TestMethod]
[TestCategory(Category.Golden)]
public void TheEngineInItsComparisonSettingMatchesTheReplicaOnTwoHundredSeries()
{
// 200 seeded series: AR(1) with half-lives 20–100, driftless and drifting walks, 600–1,500 bars, prices exp(s) on
// EURUSD. Three cases of table G.4 (no stop, a stop of 90, a stop of 30 with growth): the engine, deciding and filling
// on the same close with no cost and no account rule, must make the replica's baskets, and its result in targets
// computed from the fill prices must be the replica's total.
var cases = new[] { ReplicaSettings.DocumentCases[0], ReplicaSettings.DocumentCases[4], ReplicaSettings.DocumentCases[14] };
// The series are independent: they run in parallel, each with its own assertions.
var baskets = 0;
Parallel.For(0, 200, i =>
{
var bars = 600 + (i * 900 / 199);
var s = (i % 4) switch
{
0 or 1 => BasketSynthetic.Reverting(bars, Synthetic.Phi(20 + (i % 5 * 20)), 1_000 + i, 0.005),
2 => BasketSynthetic.Walk(bars, 1_000 + i, 0, 0.005),
_ => BasketSynthetic.Walk(bars, 1_000 + i, i % 8 == 3 ? 0.0005 : -0.0005, 0.005),
};
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = [.. s.Select(x => 1.1 * Math.Exp(x))] });
var logs = data.Bars("EURUSD").Close.Select(x => Math.Log(x)).ToArray();
var market = BasketMarket.Of(data);
foreach (var c in cases)
{
var replica = StylisedReplica.Run(logs, c.Settings);
var engine = new BasketEngine(market, VenueCosts.None, 10_000m).Run(BasketRules.Comparison(EurUsd, c.Settings));
Assert.AreEqual(replica.Baskets, engine.Traces.Count, $"series {i}, {c.Label} {c.StopLabel}: baskets");
var total = 0d;
for (var k = 0; k < replica.List.Count; k++)
{
var r = replica.List[k];
var x = engine.Traces[k];
var where = $"series {i}, {c.Label} {c.StopLabel}, basket {k}";
Assert.AreEqual(r.Direction, x.Direction, where);
CollectionAssert.AreEqual(r.EntryBars.ToArray(), x.Positions.Select(p => p.EntryBar).ToArray(), where);
Assert.AreEqual(r.ClosedAt, x.ExitBar, where);
Assert.AreEqual(r.Exit switch { ReplicaExits.Target => BasketReasons.Target, ReplicaExits.Stop => BasketReasons.StopBasket, _ => BasketReasons.End }, x.ExitReason, where);
// One target is k_T × σ of ln(price); the engine's σ is that of 10,000 · ln(price).
var target = c.Settings.TargetSigma * x.Sigma / 10_000;
total += x.Positions.Sum(p => x.Direction * (Math.Log((double)p.ExitPrice!.Value) - Math.Log((double)p.EntryPrice)) / target);
}
Assert.AreEqual(replica.Total, total, 1e-9, $"series {i}, {c.Label} {c.StopLabel}: total");
Interlocked.Add(ref baskets, replica.Baskets);
}
});
Assert.IsTrue(baskets > 5_000, $"{baskets} baskets compared");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void FiveNightsAreChargedFromTuesdayToFridayInTheEngine()
{
// Monday 19 January 2026 EURUSD fixes at 1.0985 against a window around 1.1001: z ≤ −2, buy. Filled on Tuesday's
// fixing (00:00 UTC) at the ask 1.098505; Thursday's fixing 1.1000 gives 14.9 pips ≥ 10: sold on Friday's (00:00 UTC).
// Rollovers crossed: Tuesday's (1), Wednesday's (3), Thursday's (1): five nights at the buy rate of 8.096 USD per
// 100,000. Exposure at Tuesday's mid: 1,000 × 1.0985 = 1,098.50 USD; financing 1,098.50 / 100,000 × 8.096 × 5 = 0.4446728.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.0985, 1.0985, 1.0985, .. Enumerable.Repeat(1.1000, 7)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument), VenueCosts.Etoro);
var position = result.Traces.Single().Positions.Single();
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 20)), position.EntryAt);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 23)), position.ExitAt);
Assert.AreEqual(1_098.5m / 100_000m * 8.096m * 5, position.Financing);
Assert.AreEqual(0.4446728m, result.Financing);
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()
{
foreach (var (baseline, shortBars) in new[] { (20, 16), (50, 8) })
{
var x = BasketSynthetic.Walk(400, baseline, 0, 0.3);
var rolling = BasketIndex.RollingRvol(x, baseline, shortBars);
for (var t = 0; t < x.Length; t++)
{
var reference = BasketIndex.Rvol(x, t, baseline, shortBars);
Assert.AreEqual(reference ?? double.NaN, rolling[t], $"t {t}");
}
}
}
// ----- data of the tests -----
private static BasketRunResult Run(BarDataset data, BasketRules rules, VenueCosts costs, decimal capital = 10_000m) =>
new BasketEngine(BasketMarket.Of(data), costs, capital).Run(rules);
/// <summary>A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.</summary>
private static BasketRules SingleRules(FxPair pair, BasketMode mode) => new([BasketUnit.OnePair(pair)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
Mode = mode,
MaxRvol = null,
};
private static BarDataset GateData()
{
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(0.9840, 8)];
double[] j = [.. BasketSynthetic.Alternate(150.00, 150.02, 12), .. Enumerable.Repeat(149.80, 8)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["USDJPY"] = j });
}
private static BasketRules GateRules(BasketMode mode) => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(UsdJpy)])
{
Window = 10,
Target = 10m,
Distance = 15m,
LotPer10k = 0.15m,
Mode = mode,
MaxRvol = null,
};
private static BarDataset SizeData(double gap)
{
var low = 0.9985 * (1 - gap);
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(low, 18)];
double[] g = [.. BasketSynthetic.Alternate(1.3000, 1.3002, 15), .. Enumerable.Repeat(1.2985, 15)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["GBPUSD"] = g });
}
private static BasketRules SizeRules() => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(GbpUsd)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
LotPer10k = 0.1m,
Mode = BasketMode.AsLive,
Profile = BasketProfiles.Prudente,
MaxRvol = null,
};
private static BarDataset TenPairs()
{
var levels = new Dictionary<string, double>(StringComparer.Ordinal)
{
["EURUSD"] = 1.10,
["GBPUSD"] = 1.30,
["AUDUSD"] = 0.66,
["NZDUSD"] = 0.60,
["USDCAD"] = 1.40,
["USDCHF"] = 0.85,
["USDJPY"] = 150,
["EURGBP"] = 0.846,
["EURJPY"] = 165,
["GBPJPY"] = 195,
};
return BasketSynthetic.Daily(levels.ToDictionary(
l => l.Key,
l => (double[])[.. BasketSynthetic.Alternate(l.Value, l.Value * 1.0002, 10), .. Enumerable.Repeat(l.Value * 0.9985, 10)],
StringComparer.Ordinal));
}
private static BasketRules TenRules(decimal lot) => new([.. TenPairs().Symbols.Select(s => BasketUnit.OnePair(FxPairs.Get(s)))])
{
Window = 10,
Target = 1_000m,
Distance = 1_000m,
LotPer10k = lot,
MaxOpenBaskets = 20,
Mode = BasketMode.AsLive,
MaxRvol = null,
};
private static BarDataset LiquidationData(double fall)
{
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(fall, 8)];
return BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
}
private static IEnumerable<decimal> Alt(decimal low, decimal high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
private static (QuoteSide, QuoteSide) Same(QuoteSide side) => (side, side);
}
+409
View File
@@ -0,0 +1,409 @@
using System.Security.Cryptography;
using System.Text;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Core;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The report of the basket family (Phase 14, issue #131): <c>docs/backtests/basket_reversion.md</c> is written whatever
/// the verdict, shows the 15 rows of the replica of appendix G with the binding ones counted, the control against chance,
/// the trial of the basket engine with its orphan legs counted, compares with zero and never with buy and hold, writes
/// numbers the Italian way and never names the product the research document describes.
/// </summary>
[TestClass]
public sealed class BasketReportTests
{
private const string Command = "anubis backtest baskets --to 2026-11-30";
/// <summary>SHA-256 of the lower-case name of the product the research document describes: the test never writes it.</summary>
private const string ProductNameSha256 = "9f00a2f4b75ffa8777d52da7e1a4a5a7c99929f0709b13cb0bc727003bbf9607";
private const int ProductNameLength = 6;
private static readonly DateTimeOffset Now = new(2026, 12, 4, 9, 30, 0, TimeSpan.Zero);
private static readonly DateOnly First = new(2024, 1, 1);
/// <summary>The prototype's totals, positions and baskets of the 15 rows of G.4: what the replica gives on the ECB file.</summary>
private static readonly (double Total, int Positions, int Baskets)[] Ours =
[
(535.5, 1675, 1259), (543.7, 2047, 1543), (257.2, 2390, 1788),
(753.6, 1953, 1467), (1029.1, 2583, 1929), (-100.8, 2937, 2186),
(340.1, 1424, 1066), (536.3, 1641, 1223), (138.4, 1936, 1447),
(647.1, 1977, 1167), (439.5, 2702, 1590), (-47.4, 3650, 2166),
(531.3, 2133, 1273), (757.4, 3010, 1796), (169.9, 3455, 2109),
];
private static readonly Lazy<BasketTrialSection> _trial = new(BuildTrial);
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportIsWrittenWhateverTheVerdict()
{
var trial = _trial.Value;
var passed = BasketReport.Markdown(Input(trial with { Report = trial.Report with { Passed = true } }));
var failedReport = trial.Report with
{
Passed = false,
Checks = [.. trial.Report.Checks.Select(c => c.Key == ReportCheckKeys.Drawdown ? c with { Value = 0.38, Passed = false } : c)],
};
var failed = BasketReport.Markdown(Input(trial with { Report = failedReport }));
var waiting = BasketReport.Markdown(Input(null, "Mancano i cambi della BCE: la prova del motore non è partita."));
foreach (var text in new[] { passed, failed, waiting })
{
Assert.IsTrue(text.StartsWith("# Backtest di `basket_reversion` (Rientro tra strumenti)" + Environment.NewLine, StringComparison.Ordinal), text[..80]);
StringAssert.Contains(text, "Solo ricerca: questa famiglia non manda ordini, nemmeno finti (ADR 0021, 0026).");
StringAssert.Contains(text, "Per rifarlo: `" + Command + "`");
StringAssert.Contains(text, "## Dati");
StringAssert.Contains(text, "## Replica dell'appendice G");
StringAssert.Contains(text, "## Controllo contro il caso (G.5)");
StringAssert.Contains(text, "## Cosa il backtest non rappresenta");
Assert.IsFalse(text.Contains("outcome.json", StringComparison.Ordinal), "No outcome file for baskets in this phase.");
Assert.IsFalse(text.Contains("letto dal bot", StringComparison.Ordinal));
Assert.IsTrue(text.IndexOf("## Dati", StringComparison.Ordinal) < text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal));
Assert.IsTrue(text.IndexOf("## Replica dell'appendice G", StringComparison.Ordinal) < text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal));
Assert.IsTrue(text.IndexOf("## Controllo contro il caso (G.5)", StringComparison.Ordinal) < text.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
}
StringAssert.Contains(passed, "**Esito: superato.**");
StringAssert.Contains(passed, "## Prova del motore a panieri");
StringAssert.Contains(passed, "versione basket-1 del motore a panieri");
StringAssert.Contains(passed, "«come dal vivo»");
StringAssert.Contains(passed, "Motore finto della prova.");
Assert.IsTrue(passed.IndexOf("## Prova del motore a panieri", StringComparison.Ordinal) < passed.IndexOf("## Cosa il backtest non rappresenta", StringComparison.Ordinal));
StringAssert.Contains(failed, "**Esito: non superato.**");
StringAssert.Contains(failed, "calo massimo 38,0%");
StringAssert.Contains(failed, "**non superato**");
StringAssert.Contains(waiting, "**Esito: in attesa.** Mancano i cambi della BCE: la prova del motore non è partita.");
Assert.IsFalse(waiting.Contains("## Prova del motore a panieri", StringComparison.Ordinal));
StringAssert.Contains(waiting, "file a 1 minuto");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReplicaTableShowsEveryRowAndCountsTheBindingOnes()
{
var text = BasketReport.Markdown(Input(null, "Nessuna prova."));
var replica = Section(text, "## Replica dell'appendice G");
StringAssert.Contains(replica, "| Obiettivo · distanza · mediazioni | Stop | Documento | Anubis | Scarto | Tolleranza | Vincolante | Esito |");
foreach (var c in ReplicaSettings.DocumentCases)
{
var row = "| " + c.Label + " | " + c.StopLabel + " |";
Assert.AreEqual(2, Count(replica, row), row + " in the totals and in the break-even table.");
}
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 535,5 | +1,5 | ±26,7 | sì | dentro |");
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 90 obiettivi | 1.032 | 1.029,1 | −2,9 | ±51,6 | sì | dentro |");
StringAssert.Contains(replica, "| 2 σ · 8 σ · 3 | 30 obiettivi | −98 | −100,8 | −2,8 | ±25 | no | solo riportata |");
StringAssert.Contains(replica, "| 2,5 σ · 10 σ · 3 | nessuno | +0,32 | +0,32 | 1.675 | 1.259 | ");
StringAssert.Contains(replica, "13 righe vincolanti su 13 dentro la tolleranza.");
StringAssert.Contains(replica, "2 σ · 8 σ · 3 con stop di 30 obiettivi");
StringAssert.Contains(replica, "2,5 σ · 4 σ · 3 con stop di 30 obiettivi");
StringAssert.Contains(replica, "mai giudicata");
var rows = ReplicaRows();
rows[0] = rows[0] with { Result = rows[0].Result with { Total = 400 } };
var off = Section(BasketReport.Markdown(Input(null, "Nessuna prova.") with { Replica = rows }), "## Replica dell'appendice G");
StringAssert.Contains(off, "| 2,5 σ · 10 σ · 3 | nessuno | 534 | 400 | −134 | ±26,7 | sì | **fuori** |");
StringAssert.Contains(off, "12 righe vincolanti su 13 dentro la tolleranza.");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OrphanLegsAreCountedInTheReport()
{
var trial = _trial.Value;
var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero);
ReportBasket[] baskets =
[
new("EURUSD-USDCHF", opened, opened.AddDays(3), 1_000m, 2, ["EURUSD", "USDCHF"], "mandatory_stop", -40m),
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"], 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 (valutato agli ultimi prezzi) | 1 |");
StringAssert.Contains(two, "Panieri della variante giudicata: 5.");
StringAssert.Contains(two, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 5 |");
StringAssert.Contains(two, "| `weird_code` | 1 |");
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]
[TestCategory(Category.Unit)]
public void EveryCodeOfTheEngineHasAnItalianLabel()
{
var trial = _trial.Value;
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
{
[BasketReasons.PositionLimit] = 3,
[BasketReasons.ClockWindow] = 4,
[BasketReasons.MandatoryStop] = 6,
[BasketReasons.GateOpenLoss] = 1,
[BasketReasons.PausedUntilNextDay] = 1,
[BasketReasons.DailyLossBlock] = 1,
[BasketReasons.HalfSize] = 1,
[BasketReasons.BelowVenueMinimum] = 1,
[BasketReasons.MarginLimit] = 1,
[BasketReasons.OppositePosition] = 1,
[BasketReasons.CurrencyExposure] = 1,
[BasketReasons.CostRule] = 1,
[BasketReasons.RvolFilter] = 1,
[BasketReasons.CorrelationLow] = 1,
[BasketReasons.SwitchTripped] = 1,
[BasketReasons.MaxOpenBaskets] = 1_569,
};
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]
[TestCategory(Category.Unit)]
public void TheComparisonIsZeroNeverBuyAndHold()
{
var text = BasketReport.Markdown(Input(_trial.Value));
StringAssert.Contains(text, "| | Strategia | Zero (nessuna operazione) |");
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** (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 |");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NumbersAreItalianAndTheProductIsNeverNamed()
{
var texts = new[]
{
BasketReport.Markdown(Input(_trial.Value)),
BasketReport.Markdown(Input(null, "Nessuna prova.")),
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketReport.cs")),
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis", "Backtest", "BasketProtocol.cs")),
File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "BasketCommand.cs")),
File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "backtests", "basket_reversion.md")),
};
var text = texts[0];
StringAssert.Contains(text, "535,5");
StringAssert.Contains(text, "−100,8");
Assert.IsFalse(text.Contains("535.5", StringComparison.Ordinal));
Assert.IsFalse(text.Contains("-100,8", StringComparison.Ordinal), "The minus is U+2212, as in the other reports.");
StringAssert.Contains(text, "1.000 USD");
StringAssert.Contains(text, "0,005%");
StringAssert.Contains(text, "dal 04/01/1999 al 02/12/2026");
StringAssert.Contains(text, "`f298c1dcc4be`");
StringAssert.Contains(text, "| 2,5 σ · 10 σ · 3 | nessuno | 150 | 20261202 | +0,32 | ");
StringAssert.Contains(text, " | 35,0% | 37% |");
foreach (var t in texts)
{
var lower = t.ToLowerInvariant();
for (var i = 0; i + ProductNameLength <= lower.Length; i++)
{
var window = lower.AsSpan(i, ProductNameLength);
if (!char.IsLetter(window[0]))
{
continue;
}
var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(window.ToString())));
Assert.AreNotEqual(ProductNameSha256, hash, "The report names the product the research document describes, at " + i + ".");
}
}
}
private static BasketReportInput Input(BasketTrialSection? trial, string? missing = null) => new(
Command,
Now,
new BasketDataNotes("Banca centrale europea, cambi di riferimento (eurofxref-hist)", "f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8",
new DateOnly(1999, 1, 4), new DateOnly(2026, 12, 2), 7_149, 28, new DateOnly(2026, 12, 2)),
VenueCosts.Etoro,
ReplicaRows(),
ControlRows(),
trial,
missing);
private static List<BasketReplicaRow> ReplicaRows() =>
[.. ReplicaSettings.DocumentCases.Select((c, i) => new BasketReplicaRow(c, new ReplicaResult(Ours[i].Total, Ours[i].Positions, Ours[i].Baskets, (int)(Ours[i].Baskets * 0.97), 0, [])))];
private static List<BasketControlRow> ControlRows()
{
var replicas = Enumerable.Range(0, 150).Select(i => -1.8 + (2.7 * i / 149.0)).ToArray();
return [.. BasketReport.DocumentControl.Select(d => new BasketControlRow(d.Case, new ReplicaControl(0.32, replicas, 0.35), 150, 20_261_202, d.Share))];
}
private static string Section(string text, string heading)
{
var start = text.IndexOf(heading, StringComparison.Ordinal);
Assert.IsTrue(start >= 0, heading);
var end = text.IndexOf("\n## ", start + heading.Length, StringComparison.Ordinal);
return end < 0 ? text[start..] : text[start..end];
}
private static int Count(string text, string part)
{
var count = 0;
for (var i = text.IndexOf(part, StringComparison.Ordinal); i >= 0; i = text.IndexOf(part, i + part.Length, StringComparison.Ordinal))
{
count++;
}
return count;
}
private static BasketTrialSection BuildTrial()
{
var plan = new TrialPlan(
"basket_reversion",
"1",
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal) { ["target"] = [2m, 2.5m, 3m] },
new TrialData(TrialSources.Research, "ecb", ["EURUSD", "USDCHF", "AUDNZD"], First, First.AddDays(StubEngine.Days - 1)),
StubEngine.Capital,
[1m, 2m, 3m],
TrialValidation.Default,
TrialThresholds.Default,
"basket-1",
Now);
var hash = TrialPlan.Hash(plan.ToJson());
var (report, _) = TrialRunner.Run(new Guid("6a1f0c3e-2b7d-4e59-8c1a-9d3e5f7a0b2c"), plan, hash, StubFamily.Instance, new StubEngine(), PriorTrials.None, Now);
return new BasketTrialSection("Le 28 coppie della BCE, generazione B in σ", plan, hash, report, BasketReport.LikeLive);
}
/// <summary>A research family with one numeric axis, under the basket family's id.</summary>
private sealed class StubFamily : IResearchFamily
{
public static StubFamily Instance { get; } = new();
public string Id => "basket_reversion";
public string Version => "1";
public string Name => "Rientro tra strumenti";
public string Description => "Famiglia finta per provare il rapporto dei panieri.";
public IReadOnlyList<ParameterSpec> Parameters => [new("target", "Obiettivo", 2.5m, [2m, 2.5m, 3m], 1m, 5m)];
}
/// <summary>An engine with a flat benchmark (zero) and a noisy equity that depends on the target.</summary>
private sealed class StubEngine : ITrialEngine
{
public const int Days = 320;
public const decimal Capital = 20_000m;
public string Currency => "USD";
public bool LongOnly => false;
public int PeriodsPerYear => 260;
public int Sessions => Days;
public string Fingerprint() => "f298c1dcc4be41a4|basket:basket-1";
public IReadOnlyList<ReportInstrument> Instruments() => [new("EURUSD", "ecb", First, First.AddDays(Days - 1), Days, 0, "file")];
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
var target = (double)parameters["target"];
var random = new SeededRandom((int)(target * 10));
var equity = new List<EquityPoint>();
var value = Capital;
for (var i = 0; i < Days; i++)
{
if (i > 0)
{
value *= 1m + (decimal)((0.0002 * target) + (0.006 * random.Normal())) - (0.0001m * (costMultiplier - 1m));
value = Math.Round(value, 6);
}
equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m));
}
return new BacktestRun(Currency, Capital, equity, [], [], [], []);
}
public BacktestRun Benchmark() =>
new(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []);
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => new([First.AddDays(100)], 12, []);
public IReadOnlyList<string> Limitations() => ["Motore finto della prova."];
public TrialExpectations Expected(BacktestRun run, double[] returns) => new(null, null);
}
}
+138
View File
@@ -0,0 +1,138 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// Builders of hand-made market data for the basket engine (Phase 14): daily bars on the currency weekdays, 15-minute bars
/// with explicit bid and ask, the 28 crosses of seven synthetic rates, and log series that revert or walk.
/// </summary>
internal static class BasketSynthetic
{
/// <summary>A Monday in winter, far from any change of the clocks.</summary>
public static readonly DateOnly Monday = new(2026, 1, 5);
/// <summary>The first <paramref name="count"/> currency weekdays from <paramref name="start"/> (Monday to Friday).</summary>
public static IReadOnlyList<DateOnly> Weekdays(DateOnly start, int count)
{
var days = new List<DateOnly>(count);
for (var day = start; days.Count < count; day = day.AddDays(1))
{
if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
{
days.Add(day);
}
}
return days;
}
/// <summary>
/// Daily bars like the ECB's (open = high = low = close, at 00:00 UTC of each weekday from <paramref name="start"/>), one
/// reference price a day and no ask: the engine builds bid and ask with the venue's spread.
/// </summary>
public static BarDataset Daily(IReadOnlyDictionary<string, double[]> closes, DateOnly? start = null)
{
var length = closes.Values.Max(c => c.Length);
var days = Weekdays(start ?? Monday, length);
var bars = closes.ToDictionary(
p => p.Key,
p => (IReadOnlyList<ResearchBar>)[.. p.Value.Select((c, i) => Flat(Midnight(days[i]), c))],
StringComparer.Ordinal);
return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(days[0]), Midnight(days[^1]).AddDays(1), bars);
}
/// <summary>
/// 15-minute bars from <paramref name="first"/>, one per entry of <paramref name="bids"/>, with the ask given beside each
/// bid (open, high, low, close of both sides).
/// </summary>
public static BarDataset Quarters(DateTimeOffset first, IReadOnlyDictionary<string, (QuoteSide Bid, QuoteSide Ask)[]> quotes)
{
var bids = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var asks = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var length = 0;
foreach (var (symbol, rows) in quotes)
{
bids[symbol] = [.. rows.Select((r, i) => r.Bid.Bar(first.AddMinutes(15 * i)))];
asks[symbol] = [.. rows.Select((r, i) => r.Ask.Bar(first.AddMinutes(15 * i)))];
length = Math.Max(length, rows.Length);
}
return BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, first, first.AddMinutes(15 * length), bids, asks);
}
/// <summary>A quote whose four prices are one mid, with the bid half a spread below and the ask half above.</summary>
public static (QuoteSide Bid, QuoteSide Ask) Mid(decimal mid, decimal spread) => (QuoteSide.Flat(mid - (spread / 2)), QuoteSide.Flat(mid + (spread / 2)));
/// <summary>The 28 ECB-like crosses of seven synthetic rates against the euro, one fixing a weekday.</summary>
public static BarDataset Crosses(int days, int seed, double halfLife = 50, double volatility = 0.005, DateOnly? start = null)
{
var dates = Weekdays(start ?? new DateOnly(2020, 1, 6), days);
var levels = new Dictionary<string, double>(StringComparer.Ordinal)
{
["GBP"] = 0.86,
["AUD"] = 1.62,
["NZD"] = 1.78,
["USD"] = 1.10,
["CAD"] = 1.48,
["CHF"] = 0.97,
["JPY"] = 150,
};
var rates = new List<FxRate>();
var k = 0;
foreach (var (currency, level) in levels)
{
var path = Reverting(days, Synthetic.Phi(halfLife), seed + (k++ * 7919), volatility);
rates.AddRange(dates.Select((d, i) => new FxRate(Currencies.Eur, currency, d, Math.Round((decimal)(level * Math.Exp(path[i])), 6), "ecb")));
}
var crosses = EcbCrosses.Build(rates);
return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(dates[0]), Midnight(dates[^1]).AddDays(1), crosses);
}
/// <summary>A log series that reverts to zero: s(t) = φ·s(t−1) + σ·ε, from zero.</summary>
public static double[] Reverting(int bars, double phi, int seed, double volatility = 0.01)
{
var random = new Gen(seed);
var s = new double[bars];
for (var t = 1; t < bars; t++)
{
s[t] = (phi * s[t - 1]) + (volatility * random.Normal());
}
return s;
}
/// <summary>A log series that walks: s(t) = s(t−1) + drift + σ·ε, from zero.</summary>
public static double[] Walk(int bars, int seed, double drift = 0, double volatility = 0.01)
{
var random = new Gen(seed);
var s = new double[bars];
for (var t = 1; t < bars; t++)
{
s[t] = s[t - 1] + drift + (volatility * random.Normal());
}
return s;
}
/// <summary>Prices that alternate between two levels for <paramref name="count"/> bars: a window with a known spread.</summary>
public static IEnumerable<double> Alternate(double low, double high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
public static DateTimeOffset Midnight(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
private static ResearchBar Flat(DateTimeOffset at, double close)
{
var price = (decimal)close;
return new ResearchBar(at, price, price, price, price, 0m);
}
}
/// <summary>Open, high, low and close of one side of a quote.</summary>
internal readonly record struct QuoteSide(decimal Open, decimal High, decimal Low, decimal Close)
{
public static QuoteSide Flat(decimal price) => new(price, price, price, price);
public ResearchBar Bar(DateTimeOffset at) => new(at, Open, High, Low, Close, 0m);
}
@@ -0,0 +1,325 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The basket family and its trial engine (Phase 14, issue #129): one identifier for every sub-variant, the choice axes, the
/// plan that carries mode and costs, the judge on a basket trial (orphan legs counted in the report, one equity point a day
/// for every variant, zero as the comparison, the surrogate of the control), the look-ahead check that catches a rule
/// reading the bars ahead, and the lot that never grows inside a basket.
/// </summary>
[TestClass]
public sealed class BasketTrialEngineTests
{
private static readonly FxPair EurUsd = FxPairs.Get("EURUSD");
private static readonly FxPair UsdChf = FxPairs.Get("USDCHF");
[TestMethod]
[TestCategory(Category.Integration)]
public void AMandatoryStopThatLeavesAnOrphanLegIsCountedInTheReport()
{
// The chain EURUSD + USDCHF is bought on bar 40 (filled on bar 41 at the asks 1.099005 and 0.799505: 0.1 pip of
// spread). On bar 45 USDCHF opens 15% lower: the mandatory stop of the long USDCHF at leverage 5 sits 10% under the
// entry (0.7195545), so it is gapped and filled at the open's bid, 0.679995. The EURUSD leg is left alone: it closes
// at the next execution as an orphan.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 40), .. Enumerable.Repeat(1.0990, 30)];
double[] c = [.. BasketSynthetic.Alternate(0.8000, 0.8002, 40), .. Enumerable.Repeat(0.7995, 5), .. Enumerable.Repeat(0.68, 25)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e, ["USDCHF"] = c });
var days = BasketSynthetic.Weekdays(BasketSynthetic.Monday, 70);
var plan = Plan(days[0], days[^1], BasketModes.AsDocument);
var engine = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data)
{
Customize = r => r with { Units = [BasketUnit.Of(EurUsd, UsdChf)], Window = 10, MaxRvol = null, MinCorrelation = null },
};
var run = engine.RunBaskets(StrategyParameters.Of(BasketReversionFamily.Instance, null));
var basket = run.Run.Baskets[0];
Assert.AreEqual(BasketReasons.OrphanLeg, basket.ExitReason);
var trace = run.Traces[0];
var chf = trace.Positions.Single(p => p.Pair == "USDCHF");
var eur = trace.Positions.Single(p => p.Pair == "EURUSD");
Assert.AreEqual(BasketReasons.MandatoryStop, chf.ExitReason);
Assert.AreEqual(45, chf.ExitBar);
Assert.AreEqual(0.679995m, chf.ExitPrice);
Assert.AreEqual(BasketReasons.OrphanLeg, eur.ExitReason);
Assert.AreEqual(46, eur.ExitBar);
Assert.AreEqual(1, run.Run.Notes.Count(n => n.Reason == BasketReasons.OrphanLeg));
var (report, _) = TrialRunner.Run(Guid.NewGuid(), plan, "plan", BasketReversionFamily.Instance, engine, PriorTrials.None, plan.WrittenAt);
Assert.AreEqual(1, report.Notes[BasketReasons.OrphanLeg]);
Assert.AreEqual(1, report.Notes[BasketReasons.MandatoryStop]);
Assert.AreEqual(BasketReasons.OrphanLeg, report.Baskets![0].ExitReason);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLotNeverGrowsInsideABasket()
{
// Property: on reverting and walking crosses, both modes, both profiles, pips and σ, no level is larger than the first.
var levels = 0;
for (var seed = 1; seed <= 12; seed++)
{
var data = BasketSynthetic.Crosses(320, seed, halfLife: 10 + (seed * 7), volatility: 0.004 + (seed * 0.0007));
var market = BasketMarket.Of(data);
var mode = seed % 2 == 0 ? BasketModes.AsLive : BasketModes.AsDocument;
var parameters = StrategyParameters.Of(BasketReversionFamily.Instance,
$"generation={1 + (seed % 2)};units={1 + (seed / 2 % 2)};target={(seed / 2 % 2 == 0 ? 10 : 2)};distance={(seed / 2 % 2 == 0 ? 15 : 1)};profile={1 + (seed / 4 % 2)};growth={(seed % 3 == 0 ? "1.3" : "1")};averagings={(seed % 3 == 0 ? 4 : 3)};window=20");
var rules = BasketReversionFamily.Instance.Rules(parameters, BasketModes.Parse(mode), data.Timeframe) with { MaxRvol = null, MinCorrelation = null };
var result = new BasketEngine(market, VenueCosts.Etoro, 10_000m).Run(rules);
foreach (var trace in result.Traces)
{
foreach (var leg in trace.Positions.GroupBy(p => p.Pair))
{
var first = leg.First(p => p.Level == 0).Units;
Assert.IsTrue(leg.All(p => p.Units <= first), $"seed {seed}, {trace.Unit}: {string.Join(", ", leg.Select(p => p.Units))}");
levels += leg.Count(p => p.Level > 0);
}
}
}
Assert.IsTrue(levels > 20, $"{levels} averagings: the property must be exercised");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEngineFindsARuleThatReadsTheNextBar()
{
var data = BasketSynthetic.Crosses(520, 7, halfLife: 30);
var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 520);
var plan = Plan(days[120], days[^1], BasketModes.AsDocument);
var parameters = StrategyParameters.Of(BasketReversionFamily.Instance, "generation=2;signal=2;units=2;target=2.5;distance=4;exit=2");
var honest = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data).LookAhead(parameters, 6);
Assert.AreEqual(0, honest.Mismatches.Count, string.Join("\n", honest.Mismatches.Take(3).Select(m => $"{m.Day}: {m.Full} / {m.Cut}")));
Assert.IsTrue(honest.Decisions > 20, $"{honest.Decisions} decisions compared");
// A signal that reads the bars ahead: the same z, fifty bars later (as good as a centred window).
var cheat = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data) { Customize = r => r with { SignalShift = 50 } }.LookAhead(parameters, 6);
Assert.IsTrue(cheat.Mismatches.Count > 0);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void EveryVariantHasOneEquityPointPerDayOnTheSameDays()
{
// Daily fixings: every variant, both modes, one point per weekday of the window.
var data = BasketSynthetic.Crosses(260, 11, halfLife: 25);
var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 260);
foreach (var mode in new[] { BasketModes.AsDocument, BasketModes.AsLive })
{
var engine = new BasketTrialEngine(Plan(days[110], days[^1], mode), BasketReversionFamily.Instance, data);
Assert.AreEqual(150, engine.Sessions);
foreach (var p in new[] { "generation=1", "generation=2", "generation=2;units=2;target=2.5;distance=4;profile=2", "generation=1;signal=2;units=2;target=2.5;distance=10;exit=2" })
{
var run = engine.Run(StrategyParameters.Of(BasketReversionFamily.Instance, p));
CollectionAssert.AreEqual(days.Skip(110).ToArray(), run.Equity.Select(x => x.Day).ToArray(), $"{mode} {p}");
}
CollectionAssert.AreEqual(days.Skip(110).ToArray(), engine.Benchmark().Equity.Select(x => x.Day).ToArray());
Assert.IsTrue(engine.Benchmark().Equity.All(x => x.Equity == 10_000m), "the comparison is zero: capital that does not move");
}
// 15-minute bars: one point per server day, the day that ends at 17:00 New York.
var first = new DateTimeOffset(2026, 1, 13, 0, 0, 0, TimeSpan.Zero);
var walk = BasketSynthetic.Walk(288, 5, 0, 0.0004);
var quarters = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
{
["EURUSD"] = [.. walk.Select(x => BasketSynthetic.Mid(Math.Round((decimal)(1.1 * Math.Exp(x)), 5), 0.0001m))],
});
var serverDays = Enumerable.Range(0, 288).Select(t => ServerClock.Day(first.AddMinutes((15 * t) + 15).AddTicks(-1))).Distinct().ToArray();
Assert.AreEqual(4, serverDays.Length);
foreach (var rules in new[] { SingleRules(EurUsd, BasketMode.AsDocument), SingleRules(EurUsd, BasketMode.AsLive) with { Window = 20, Target = 3m } })
{
CollectionAssert.AreEqual(serverDays, Run(quarters, rules, VenueCosts.Etoro).Run.Equity.Select(x => x.Day).ToArray());
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public void TheTrialEngineJudgesABasketTrial()
{
var data = BasketSynthetic.Crosses(420, 3, halfLife: 30);
var days = BasketSynthetic.Weekdays(new DateOnly(2020, 1, 6), 420);
var plan = Plan(days[120], days[^1], BasketModes.AsLive) with
{
Grid = new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal)
{
["generation"] = [2m],
["signal"] = [2m],
["units"] = [2m],
["target"] = [2m, 2.5m],
["distance"] = [4m],
["exit"] = [2m],
},
};
var engine = new BasketTrialEngine(plan, BasketReversionFamily.Instance, data);
Assert.IsFalse(((ITrialEngine)engine).LongOnly, "a basket sells as well as buys: its control is not centred");
Assert.AreEqual(260, engine.PeriodsPerYear);
StringAssert.Contains(engine.Fingerprint(), "|basket:" + BasketEngine.Version + "|costs:" + VenueCosts.Etoro.Fingerprint() + "|mode:come_dal_vivo");
Assert.AreEqual(28, engine.Instruments().Count);
var (report, summary) = TrialRunner.Run(Guid.NewGuid(), plan, "plan", BasketReversionFamily.Instance, engine, PriorTrials.None, plan.WrittenAt);
Assert.AreEqual(BasketReversionFamily.FamilyId, report.Strategy);
Assert.AreEqual(2, report.Variants.Count);
Assert.AreEqual(5, report.Checks.Count);
Assert.IsNotNull(report.Baskets);
Assert.IsTrue(report.Baskets.Count > 0);
Assert.AreEqual(0d, report.Benchmark.TotalReturn, "the comparison is zero, never buy and hold");
Assert.AreEqual(300, report.Sessions, "the plan's window");
Assert.IsTrue(report.Limitations.Any(l => l.Contains("BCE", StringComparison.Ordinal)));
Assert.IsNotNull(report.ExpectedPathP5);
Assert.AreEqual("USD", summary.Currency);
// The control against chance flips each day's log returns of every pair with the day's sign: their size stays.
var signs = DaySigns.Draw(days[0], days[^1], 42);
var surrogate = (BasketTrialEngine)engine.Surrogate(signs, centred: false);
foreach (var pair in new[] { "EURUSD", "USDJPY", "GBPCHF" })
{
var before = engine.Market.Reference(pair);
var after = surrogate.Market.Reference(pair);
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-12, $"{pair} {t}");
}
}
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()
{
var family = BasketReversionFamily.Instance;
Assert.AreEqual("basket_reversion", family.Id);
Assert.IsNotInstanceOfType<IStrategyFamily>(family, "research only: never a strategy the bot could run");
Assert.IsFalse(StrategyCatalog.All.Any(f => f.Id == family.Id));
var grid = new Dictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal)
{
["generation"] = [1m, 2m],
["signal"] = [1m, 2m],
["units"] = [1m, 2m],
["exit"] = [1m, 2m],
["profile"] = [1m, 2m],
["growth"] = [1m, 1.3m],
["averagings"] = [3m, 4m],
};
var variants = ParameterGrid.Of(family, grid);
Assert.AreEqual(32 * 3, variants.Count, "four averagings only with growth");
var units = new HashSet<string>(StringComparer.Ordinal);
foreach (var v in variants)
{
var rules = family.Rules(v.Parameters, BasketMode.AsLive, Timeframes.Day);
units.UnionWith(rules.Units.Select(u => u.Name));
Assert.AreEqual(v.Parameters["generation"] == 1m ? 5 : 10, rules.Units.Count);
}
Assert.AreEqual(15, units.Count, "five documented spreads and ten symbols");
// The defaults: Moderato, generation A, z of the pip sum, 10 and 40 pips, Fedele.
var defaults = family.Rules(StrategyParameters.Of(family, null), BasketMode.AsLive, Timeframes.Day);
Assert.AreEqual(BasketSignal.ZScorePipSum, defaults.Signal);
Assert.AreEqual(BasketMeasure.Pips, defaults.Measure);
Assert.AreEqual((10m, 40m, 3, 2, 2.0), (defaults.Target, defaults.Distance, defaults.MaxAveragings, defaults.MaxOpenBaskets, defaults.EntryZ));
Assert.AreEqual(BasketProfiles.Fedele, defaults.Profile);
Assert.AreEqual("EURUSD/USDCHF", defaults.Units[0].Name);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ChoiceAxesAreMarkedAsChoices()
{
var choices = BasketReversionFamily.Instance.Parameters.Where(p => p.Choices).Select(p => p.Name).Order(StringComparer.Ordinal).ToArray();
CollectionAssert.AreEqual(new[] { "exit", "generation", "profile", "signal", "units" }, choices);
Assert.IsTrue(BasketReversionFamily.Instance.Parameters.Where(p => p.Choices).All(p => p.Whole));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ABasketPlanCarriesItsModeAndItsCosts()
{
var plan = Plan(new DateOnly(2000, 1, 3), new DateOnly(2026, 11, 30), BasketModes.AsLive);
var json = plan.ToJson();
StringAssert.Contains(json, "\"mode\":\"come_dal_vivo\"");
StringAssert.Contains(json, "\"costs\":{\"venue\":\"etoro\"");
var back = TrialPlan.FromJson(json);
Assert.AreEqual(BasketModes.AsLive, back.Mode);
Assert.AreEqual(VenueCosts.Etoro, back.Costs);
Assert.AreEqual(json, back.ToJson(), "the stored text gives back the same plan and the same hash");
// A daily plan has neither: its text, and so its hash, is the one it always had.
var daily = plan with { Mode = null, Costs = null };
Assert.IsFalse(daily.ToJson().Contains("\"mode\"", StringComparison.Ordinal) || daily.ToJson().Contains("\"costs\"", StringComparison.Ordinal));
}
// ----- data of the tests -----
private static BasketRunResult Run(BarDataset data, BasketRules rules, VenueCosts costs, decimal capital = 10_000m) =>
new BasketEngine(BasketMarket.Of(data), costs, capital).Run(rules);
/// <summary>A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.</summary>
private static BasketRules SingleRules(FxPair pair, BasketMode mode) => new([BasketUnit.OnePair(pair)])
{
Window = 10,
Target = 10m,
Distance = 1_000m,
Mode = mode,
MaxRvol = null,
};
private static TrialPlan Plan(DateOnly from, DateOnly to, string mode) => new(
BasketReversionFamily.FamilyId,
BasketReversionFamily.Instance.Version,
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal),
new TrialData(TrialSources.Research, EcbCrosses.Venue, [.. FxPairs.All.Select(p => p.Name)], from, to),
10_000m,
[1m, 2m, 3m],
TrialValidation.Default,
TrialThresholds.Default,
BasketEngine.Version,
new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero))
{
Mode = mode,
Costs = VenueCosts.Etoro,
};
}
File diff suppressed because it is too large. Load diff
+308
View File
@@ -0,0 +1,308 @@
using System.Security.Cryptography;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The stylised replica of appendix G.3 of the research document (Phase 14, issue #130): the shared rolling signals, the 15
/// «Forex 1999–2026» totals of table G.4 on the ECB history up to 2 December 2026, the break-even on a process built to
/// revert and on a drifting walk, and the control against chance of G.5 on synthetic series whose truth is known.
/// </summary>
[TestClass]
public sealed class StylisedReplicaTests
{
private const string EcbFile = "free/ecb-hist-1999-2026-12-02.csv";
private const string EcbSha256 = "f298c1dcc4be41a4545174e3e1b3ba5977f9cab23a7fbde622955404b3b03fd8";
private static readonly DateOnly DocumentEnd = new(2026, 12, 2);
/// <summary>
/// The 15 rows of a numpy prototype of the same conventions, in G.4 order: total in targets, positions, baskets. The C#
/// replica must give the same within one target and three positions or baskets (the only room is the order of the
/// floating-point sums of the rolling window).
/// </summary>
private static readonly (double Total, int Positions, int Baskets)[] Prototype =
[
(535.5, 1675, 1259), (543.7, 2047, 1543), (257.2, 2390, 1788),
(753.6, 1953, 1467), (1029.1, 2583, 1929), (-100.8, 2937, 2186),
(340.1, 1424, 1066), (536.3, 1641, 1223), (138.4, 1936, 1447),
(647.1, 1977, 1167), (439.5, 2702, 1590), (-47.4, 3650, 2166),
(531.3, 2133, 1273), (757.4, 3010, 1796), (169.9, 3455, 2109),
];
private static readonly Lazy<IReadOnlyList<IReadOnlyList<double>>> _ecb = new(() =>
StylisedReplica.EcbSeries(EcbCrosses.Build(Ecb.ParseHistoryCsv(Fixture.Text(EcbFile), EcbCrosses.Rates)), DocumentEnd));
private static readonly Lazy<ReplicaResult[]> _table = new(() =>
[.. ReplicaSettings.DocumentCases.Select(c => StylisedReplica.Run(_ecb.Value, c.Settings))]);
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEcbHistoryOfTheDocumentIsInTheTestDataWithItsFingerprint()
{
Assert.AreEqual(EcbSha256, Convert.ToHexStringLower(SHA256.HashData(Fixture.Bytes(EcbFile))));
var rates = Ecb.ParseHistoryCsv(Fixture.Text(EcbFile), EcbCrosses.Rates);
var days = rates.Select(r => r.Date).Distinct().ToList();
Assert.AreEqual(7_149, days.Count, "the document counts 7,149 fixings");
Assert.AreEqual(new DateOnly(1999, 1, 4), days[0]);
Assert.AreEqual(DocumentEnd, days[^1]);
Assert.AreEqual(7_149 * 7, rates.Count, "all seven currencies on every day");
var crosses = EcbCrosses.Build(rates);
CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), crosses.Keys.ToArray());
Assert.IsTrue(crosses.Values.All(bars => bars.Count == 7_149));
var logs = StylisedReplica.EcbSeries(crosses, DocumentEnd);
Assert.AreEqual(28, logs.Count);
Assert.IsTrue(logs.All(s => s.Count == 7_149));
// EURUSD on the last day is the rate itself; USDJPY is 175.17 / 1.0856 rounded to 10 decimals.
Assert.AreEqual(Math.Log(1.0856), logs[3][^1], 1e-15);
Assert.AreEqual(Math.Log((double)Math.Round(175.17m / 1.0856m, 10, MidpointRounding.ToEven)), logs[24][^1], 1e-15);
// The cut is inclusive: one day earlier, one value fewer.
Assert.IsTrue(StylisedReplica.EcbSeries(crosses, DocumentEnd.AddDays(-1)).All(s => s.Count == 7_148));
}
[TestMethod]
[TestCategory(Category.Golden)]
public void TheThirteenForexTotalsOfAppendixGAreReproduced()
{
var cases = ReplicaSettings.DocumentCases;
Assert.AreEqual(15, cases.Count);
Assert.AreEqual(13, cases.Count(c => c.Binding));
for (var i = 0; i < cases.Count; i++)
{
var c = cases[i];
var ours = _table.Value[i].Total;
Console.WriteLine($"{i + 1,2} {c.Label} | {c.StopLabel}: documento {c.DocumentTotal}, noi {ours:F1}, differenza {ours - c.DocumentTotal:+0.0;-0.0}, pareggio {_table.Value[i].BreakEven:+0.00;-0.00}");
if (c.Binding)
{
Assert.AreEqual(Math.Sign(c.DocumentTotal), Math.Sign(ours), $"row {i + 1}: sign");
Assert.IsTrue(Math.Abs(ours - c.DocumentTotal) <= Math.Max(25, 0.05 * Math.Abs(c.DocumentTotal)), $"row {i + 1}: {ours} against {c.DocumentTotal}");
Assert.IsTrue(c.Passes(ours), $"row {i + 1}: the case's own band");
}
}
// The two rows near zero are only reported: both negative like the document, both a little lower than it.
foreach (var row in new[] { 6, 12 })
{
var c = cases[row - 1];
var ours = _table.Value[row - 1].Total;
Assert.IsFalse(c.Binding);
Assert.IsTrue(ours < 0 && c.DocumentTotal < 0, $"row {row}: {ours} and {c.DocumentTotal}");
Assert.IsTrue(ours - c.DocumentTotal < 0, $"row {row}: the difference is negative, as in the prototype");
}
}
[TestMethod]
[TestCategory(Category.Golden)]
public void TheReplicaMatchesThePrototypeOnEveryRow()
{
for (var i = 0; i < Prototype.Length; i++)
{
var ours = _table.Value[i];
var (total, positions, baskets) = Prototype[i];
Console.WriteLine($"{i + 1,2}: totale {ours.Total:F2} ({total}), posizioni {ours.Positions} ({positions}), panieri {ours.Baskets} ({baskets}), "
+ $"pareggio {ours.BreakEven:F3}, al bersaglio {ours.AtTargetShare:P1}, arresti {ours.Stops}");
Assert.AreEqual(total, ours.Total, 1.0, $"row {i + 1}: total");
Assert.AreEqual(positions, ours.Positions, 3, $"row {i + 1}: positions");
Assert.AreEqual(baskets, ours.Baskets, 3, $"row {i + 1}: baskets");
Assert.AreEqual(ours.Positions, ours.List.Sum(b => b.Entries.Count));
Assert.AreEqual(ours.Baskets, ours.List.Count);
Assert.AreEqual(ours.Total, ours.List.Sum(b => b.Result), 1e-6);
Assert.AreEqual(ours.AtTarget, ours.List.Count(b => b.Exit == ReplicaExits.Target));
Assert.AreEqual(ours.Stops, ours.List.Count(b => b.Exit == ReplicaExits.Stop));
Assert.AreEqual(ours.Total / ours.Positions, ours.BreakEven, 1e-12);
}
// Without a stop no basket closes at a stop; and the stops of 30 targets close more baskets than those of 90.
Assert.AreEqual(0, _table.Value[0].Stops);
Assert.IsTrue(_table.Value[2].Stops > _table.Value[1].Stops);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnAProcessThatRevertsTheBreakEvenIsAboutOnePointTwoTargets()
{
// Half-life of 50 bars: φ = 2^(−1/50). The document gives 1.23 targets per position.
var series = Enumerable.Range(0, 20).Select(i => Levels(Synthetic.MeanRevertingReturns(5_000, 1_400 + i))).ToList();
var result = StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings);
Console.WriteLine($"pareggio {result.BreakEven:F3}, totale {result.Total:F1}, posizioni {result.Positions}, panieri {result.Baskets}, al bersaglio {result.AtTargetShare:P1}");
Assert.IsTrue(result.BreakEven is >= 1.10 and <= 1.35, $"break-even {result.BreakEven}");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnARandomWalkWithDriftTheBreakEvenIsNegative()
{
var series = Enumerable.Range(0, 20).Select(i => Levels(Synthetic.WalkReturns(5_000, 2_400 + i, drift: 0.001))).ToList();
var result = StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings);
Console.WriteLine($"pareggio {result.BreakEven:F3}, totale {result.Total:F1}, posizioni {result.Positions}, panieri {result.Baskets}");
Assert.IsTrue(result.BreakEven < -1, $"break-even {result.BreakEven}");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnRandomWalksTheShuffledShareIsAboutAHalf()
{
// A driftless walk has the same law once its returns change sign: the observed result is one of the replicas, and
// its share is uniform. 100 sets of 4 walks of 1,000 bars, 100 repetitions each.
var settings = ReplicaSettings.DocumentCases[0].Settings;
var shares = new double[100];
for (var set = 0; set < shares.Length; set++)
{
var series = Enumerable.Range(0, 4).Select(i => Levels(Synthetic.WalkReturns(1_000, 30_000 + (4 * set) + i))).ToList();
shares[set] = StylisedReplica.Control(series, settings, 100, 20_261_202 + (1_000 * set)).Share;
}
var low = shares.Count(s => s < 0.05);
Console.WriteLine($"quota media {shares.Average():F3}, insiemi sotto 0,05: {low}");
Assert.IsTrue(shares.Average() is >= 0.40 and <= 0.60, $"mean share {shares.Average()}");
Assert.IsTrue(low < 10, $"{low} sets below 0.05");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnARevertingProcessTheShuffledShareIsBelowFivePercent()
{
var series = Enumerable.Range(0, 4).Select(i => Levels(Synthetic.MeanRevertingReturns(1_000, 40_000 + i))).ToList();
var control = StylisedReplica.Control(series, ReplicaSettings.DocumentCases[0].Settings, 100, 20_261_202);
Console.WriteLine($"pareggio osservato {control.Observed:F3}, mediana rimescolata {Median(control.Replicas):F3}, quota {control.Share:F3}");
Assert.AreEqual(100, control.Replicas.Count);
Assert.AreEqual(StylisedReplica.Run(series, ReplicaSettings.DocumentCases[0].Settings).BreakEven, control.Observed);
Assert.IsTrue(control.Share < 0.05, $"share {control.Share}");
// The control is deterministic: the same seed gives the same replicas.
var again = StylisedReplica.Control(series, ReplicaSettings.DocumentCases[0].Settings, 100, 20_261_202);
CollectionAssert.AreEqual(control.Replicas.ToArray(), again.Replicas.ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReplicaIsInvariantToScaleShiftAndInversion()
{
var settings = ReplicaSettings.DocumentCases[4].Settings;
var s = Levels(Synthetic.MeanRevertingReturns(4_000, 50_001));
var original = StylisedReplica.Run(s, settings);
Assert.IsTrue(original.Baskets > 20, $"{original.Baskets} baskets");
// A positive affine change of the log price: same baskets, same results.
var moved = StylisedReplica.Run(s.Select(x => (3.7 * x) - 12.5).ToArray(), settings);
Assert.AreEqual(original.Baskets, moved.Baskets);
Assert.AreEqual(original.Positions, moved.Positions);
for (var i = 0; i < original.List.Count; i++)
{
var (a, b) = (original.List[i], moved.List[i]);
Assert.AreEqual(a.Direction, b.Direction);
CollectionAssert.AreEqual(a.EntryBars.ToArray(), b.EntryBars.ToArray());
Assert.AreEqual(a.ClosedAt, b.ClosedAt);
Assert.AreEqual(a.Exit, b.Exit);
Assert.AreEqual(a.Result, b.Result, 1e-9);
Assert.AreEqual(3.7 * a.Sigma, b.Sigma, 1e-12);
}
Assert.AreEqual(original.Total, moved.Total, 1e-8);
// The inverse quote (ln 1/P = −ln P): every basket in the other direction, the same total.
var inverted = StylisedReplica.Run(s.Select(x => -x).ToArray(), settings);
Assert.AreEqual(original.Baskets, inverted.Baskets);
Assert.IsTrue(original.List.Zip(inverted.List).All(p => p.First.Direction == -p.Second.Direction && p.First.ClosedAt == p.Second.ClosedAt));
Assert.AreEqual(original.Total, inverted.Total, 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RollingSignalsEqualTheExactComputation()
{
var series = new List<IReadOnlyList<double>>
{
Levels(Synthetic.WalkReturns(3_000, 60_001)),
Levels(Synthetic.WalkReturns(3_000, 60_002, drift: 0.002)),
Levels(Synthetic.MeanRevertingReturns(3_000, 60_003)),
// A walk far from zero, where sums of raw values would lose digits.
Levels(Synthetic.WalkReturns(3_000, 60_004)).Select(x => 10_000 + x).ToArray(),
};
series.AddRange(_ecb.Value);
foreach (var window in new[] { 100, 20 })
{
foreach (var x in series)
{
var z = BasketIndex.RollingZ(x, window);
var sigma = BasketIndex.RollingSigma(x, window);
Assert.AreEqual(x.Count, z.Length);
Assert.AreEqual(x.Count, sigma.Length);
for (var t = 0; t < x.Count; t++)
{
var exactZ = BasketIndex.ZScore(x, t, window);
// Population deviation of the window − 1 differences = the sample one times √((m − 1) / m).
var exactSigma = BasketIndex.ShortSigma(x, t, window - 1) * Math.Sqrt((window - 2.0) / (window - 1.0));
if (t < window - 1)
{
Assert.IsTrue(double.IsNaN(z[t]) && double.IsNaN(sigma[t]), $"bar {t}: no signal before the window is full");
continue;
}
Assert.IsNotNull(exactZ);
Assert.AreEqual(exactZ.Value, z[t], 1e-9 * Math.Max(1, Math.Abs(exactZ.Value)), $"z at bar {t}");
Assert.AreEqual(exactSigma!.Value, sigma[t], 1e-9 * exactSigma.Value, $"σ at bar {t}");
}
}
}
// A flat stretch has no z and a σ of exactly zero; a straight line has a z but no σ either.
double[] flat = [.. Enumerable.Range(0, 30).Select(i => i < 10 ? i * 0.1 : 0.7)];
Assert.IsTrue(double.IsNaN(BasketIndex.RollingZ(flat, 10)[29]));
Assert.AreEqual(0, BasketIndex.RollingSigma(flat, 10)[29]);
Assert.IsFalse(double.IsNaN(BasketIndex.RollingZ(flat, 10)[12]));
double[] line = [.. Enumerable.Range(0, 30).Select(i => 1.0 + (i * 0.25))];
Assert.AreEqual(0, BasketIndex.RollingSigma(line, 10)[29]);
Assert.AreEqual(BasketIndex.ZScore(line, 29, 10)!.Value, BasketIndex.RollingZ(line, 10)[29], 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASeriesWithAGapIsRefused()
{
var s = Levels(Synthetic.WalkReturns(300, 70_001));
s[150] = double.NaN;
Assert.ThrowsExactly<ArgumentException>(() => BasketIndex.RollingZ(s, 100));
Assert.ThrowsExactly<ArgumentException>(() => BasketIndex.RollingSigma(s, 100));
var settings = ReplicaSettings.DocumentCases[0].Settings;
var error = Assert.ThrowsExactly<ArgumentException>(() => StylisedReplica.Run(s, settings));
StringAssert.Contains(error.Message, "buco");
s[150] = double.PositiveInfinity;
Assert.ThrowsExactly<ArgumentException>(() => StylisedReplica.Run(s, settings));
// The control needs one calendar: series of different lengths are refused.
var a = Levels(Synthetic.WalkReturns(300, 70_002));
var b = Levels(Synthetic.WalkReturns(299, 70_003));
Assert.ThrowsExactly<ArgumentException>(() => StylisedReplica.Control([a, b], settings, 10, 1));
}
/// <summary>The levels of a log price from its log returns: the cumulative sum.</summary>
private static double[] Levels(double[] returns)
{
var levels = new double[returns.Length];
var level = 0.0;
for (var i = 0; i < returns.Length; i++)
{
level += returns[i];
levels[i] = level;
}
return levels;
}
private static double Median(IReadOnlyList<double> values)
{
var sorted = values.Where(v => !double.IsNaN(v)).Order().ToArray();
return sorted.Length == 0 ? double.NaN : sorted.Length % 2 == 1 ? sorted[sorted.Length / 2] : (sorted[(sorted.Length / 2) - 1] + sorted[sorted.Length / 2]) / 2;
}
}
+437
View File
@@ -0,0 +1,437 @@
using System.Globalization;
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The costs of a venue for the basket engine (Phase 14, issue #128): the eToro table copied from appendix A and section 6.3
/// of the research document, margin and mandatory stop of tables 6.4 and 6.5, the financing calendar with the triple
/// Wednesday, the 2× and 3× cost multipliers and the fingerprint the plan carries. Every expected number is the document's,
/// or worked out by hand in the comment next to it.
/// </summary>
[TestClass]
public sealed class VenueCostsTests
{
// Appendix A, one row per pair in its order: eToro id, real-account leverage, bid/ask at 23:03 UTC and at 22:31 UTC (in
// the pause), commission per side in pips, units per 1,000 USD, pip value per 1,000 USD.
private static readonly (string Pair, int Id, int Leverage, decimal Spread, decimal Pause, decimal CommissionPips, int Units, decimal PipValue)[] AppendixA =
[
("EURGBP", 8, 30, 0.4m, 2.3m, 0.42m, 921, 0.120m),
("EURAUD", 12, 20, 1.1m, 8.3m, 0.82m, 921, 0.061m),
("EURNZD", 49, 20, 4.3m, 16.8m, 1.00m, 921, 0.050m),
("EURUSD", 1, 30, 0.1m, 2.2m, 0.54m, 921, 0.092m),
("EURCAD", 13, 30, 0.9m, 8.4m, 0.77m, 921, 0.065m),
("EURCHF", 9, 30, 0.2m, 7.5m, 0.46m, 921, 0.109m),
("EURJPY", 10, 30, 1.6m, 11.2m, 0.87m, 921, 0.057m),
("GBPAUD", 50, 20, 1.2m, 14.9m, 0.98m, 768, 0.051m),
("GBPNZD", 52, 20, 8.3m, 25.0m, 1.20m, 768, 0.042m),
("GBPUSD", 2, 30, 0.2m, 2.3m, 0.65m, 768, 0.077m),
("GBPCAD", 65, 30, 2.0m, 11.0m, 0.93m, 768, 0.054m),
("GBPCHF", 51, 20, 1.0m, 23.3m, 0.55m, 768, 0.091m),
("GBPJPY", 11, 30, 0.9m, 14.8m, 1.05m, 768, 0.048m),
("AUDNZD", 48, 20, 0.8m, 6.9m, 0.61m, 1510, 0.082m),
("AUDUSD", 7, 20, 0.1m, 2.1m, 0.33m, 1510, 0.151m),
("AUDCAD", 47, 20, 1.0m, 7.1m, 0.47m, 1510, 0.106m),
("AUDCHF", 46, 20, 0.9m, 13.5m, 0.28m, 1510, 0.178m),
("AUDJPY", 14, 20, 0.7m, 7.0m, 0.53m, 1510, 0.094m),
("NZDUSD", 3, 20, 0.1m, 2.8m, 0.27m, 1846, 0.185m),
("NZDCAD", 53, 20, 1.6m, 7.3m, 0.39m, 1846, 0.129m),
("NZDCHF", 54, 20, 1.0m, 12.2m, 0.23m, 1846, 0.218m),
("NZDJPY", 55, 20, 1.6m, 9.8m, 0.44m, 1846, 0.115m),
("USDCAD", 4, 30, 0.3m, 4.2m, 0.71m, 1000, 0.070m),
("USDCHF", 6, 30, 0.1m, 11.2m, 0.42m, 1000, 0.118m),
("USDJPY", 5, 30, 0.3m, 5.8m, 0.32m, 1000, 0.062m),
("CADCHF", 56, 30, 0.8m, 11.6m, 0.30m, 1427, 0.169m),
("CADJPY", 15, 30, 0.8m, 10.7m, 0.56m, 1427, 0.089m),
("CHFJPY", 16, 30, 1.7m, 58.4m, 0.95m, 847, 0.053m),
];
// Section 6.3: overnight financing of the twelve legs the table names, in pips per night (buy, sell); positive is a charge.
private static readonly (string Pair, decimal Buy, decimal Sell)[] FinancingPips =
[
("EURUSD", 0.88m, -0.05m),
("USDCHF", -0.66m, 1.31m),
("AUDUSD", 0.10m, 0.41m),
("USDCAD", -0.11m, 1.19m),
("NZDUSD", 0.44m, 0.02m),
("EURNZD", 0.93m, 0.74m),
("EURAUD", 1.70m, -0.45m),
("AUDCAD", -0.29m, 1.02m),
("GBPUSD", 0.51m, 0.48m),
("EURGBP", 0.66m, -0.03m),
("AUDCHF", -0.58m, 1.01m),
("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 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]),
("USDCHF", 0.8472m, [141, 212, 424, 847, 2118]),
("AUDUSD", 0.6621m, [null, 166, 331, 662, 1655]),
("USDCAD", 1.4272m, [238, 357, 714, 1427, 3568]),
("NZDUSD", 0.5416m, [null, 135, 271, 542, 1354]),
("EURNZD", 2.0044m, [null, 501, 1002, 2004, 5011]),
("EURAUD", 1.6400m, [null, 410, 820, 1640, 4100]),
("AUDCAD", 0.9452m, [null, 236, 473, 945, 2363]),
("GBPUSD", 1.3016m, [217, 325, 651, 1302, 3254]),
("EURGBP", 0.8344m, [139, 209, 417, 834, 2086]),
("AUDCHF", 0.5608m, [null, 140, 280, 561, 1402]),
("EURCHF", 0.9196m, [153, 230, 460, 920, 2299]),
];
private static readonly int[] Table65Leverages = [30, 20, 10, 5, 2];
[TestMethod]
[TestCategory(Category.Unit)]
public void MarginAndMandatoryStopFollowTables64And65()
{
var costs = VenueCosts.Etoro;
// Table 6.4 at 1,000 USD of exposure: margin, the loss at the 50% stop, 8 and 16 positions of a two-leg basket, 5 of a
// single trade. The loss at the stop is the exposure times the stop distance over the price: 1,000 × 0.5 / leverage.
(int Leverage, string Margin, string Loss, int Eight, int Sixteen, int Five)[] table64 =
[
(30, "33.33", "16.67", 267, 533, 167),
(20, "50.00", "25.00", 400, 800, 250),
(10, "100.00", "50.00", 800, 1600, 500),
(5, "200.00", "100.00", 1600, 3200, 1000),
(2, "500.00", "250.00", 4000, 8000, 2500),
];
foreach (var row in table64)
{
var margin = costs.Margin(1_000m, row.Leverage);
Assert.AreEqual(row.Margin, Round(margin, 2), $"margine a leva {row.Leverage}");
var distance = costs.StopDistance(1.0859m, row.Leverage);
Assert.IsNotNull(distance);
Assert.AreEqual(row.Loss, Round(1_000m * distance.Value / 1.0859m, 2), $"perdita allo stop a leva {row.Leverage}");
Assert.AreEqual(row.Loss, Round(margin * costs.StopMarginShare!.Value, 2));
Assert.AreEqual(row.Eight, (int)Math.Round(8 * margin, MidpointRounding.AwayFromZero));
Assert.AreEqual(row.Sixteen, (int)Math.Round(16 * margin, MidpointRounding.AwayFromZero));
Assert.AreEqual(row.Five, (int)Math.Round(5 * margin, MidpointRounding.AwayFromZero));
}
// Leverage 1: 1,000 USD of margin; a buy needs no stop and can lose all of it, a short sale keeps the 50% rule.
Assert.AreEqual(1_000m, costs.Margin(1_000m, 1));
Assert.AreEqual(8_000m, 8 * costs.Margin(1_000m, 1));
Assert.AreEqual(16_000m, 16 * costs.Margin(1_000m, 1));
Assert.AreEqual(5_000m, 5 * costs.Margin(1_000m, 1));
Assert.IsNull(costs.StopDistance("EURUSD", Direction.Buy, 1.0859m, 1));
Assert.AreEqual(0.54295m, costs.StopDistance("EURUSD", Direction.Sell, 1.0859m, 1));
// Table 6.5: every cell from the implied price, both sides; the cells marked «non disponibile» are refused.
foreach (var (pair, price, cells) in Table65)
{
for (var i = 0; i < Table65Leverages.Length; i++)
{
var leverage = Table65Leverages[i];
if (cells[i] is not { } expected)
{
Assert.ThrowsExactly<ArgumentException>(() => costs.StopDistancePips(pair, Direction.Sell, price, leverage), $"{pair} a leva {leverage}");
continue;
}
foreach (var side in new[] { Direction.Buy, Direction.Sell })
{
var pips = costs.StopDistancePips(pair, side, price, leverage);
Assert.IsNotNull(pips);
Assert.AreEqual(expected, (int)Math.Round(pips.Value, MidpointRounding.AwayFromZero), $"{pair} {side} a leva {leverage}");
}
}
}
// The default choice of section 6.5: leverage 5, stop at about 10% of the price, 0.5 / 5 × 1.0859 = 0.10859.
Assert.AreEqual(5, costs.DefaultLeverage);
Assert.AreEqual(0.10859m, costs.StopDistance(1.0859m, 5));
Assert.AreEqual(0.10859m, costs.StopDistance("EURUSD", Direction.Buy, 1.0859m, 5));
// The comparison venue has no mandatory stop.
Assert.IsNull(VenueCosts.None.StopDistance(1.0859m, 5));
Assert.IsNull(VenueCosts.None.StopDistancePips("EURUSD", Direction.Sell, 1.0859m, 5));
Assert.IsNull(VenueCosts.None.LiquidationLevel);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APositionOpenedTuesdayAndClosedFridayPaysFiveNights()
{
// Tuesday 1 December 2026 to Friday 4 December, 10:00 New York: rollovers on Tuesday (1), Wednesday (3) and Thursday (1).
Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-12-01", 10), NewYork("2026-12-04", 10)));
// The ECB bar moments: open on Tuesday's bar (00:00 UTC), close on Friday's: the same three rollovers.
Assert.AreEqual(5, FinancingCalendar.Nights(Utc("2026-12-01T00:00:00Z"), Utc("2026-12-04T00:00:00Z")));
// In summer too (New York on daylight time): Tuesday 7 July to Friday 10 July 2026.
Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-07-07", 9), NewYork("2026-07-10", 16)));
Assert.AreEqual(5, FinancingCalendar.Nights(Utc("2026-07-07T00:00:00Z"), Utc("2026-07-10T00:00:00Z")));
// The rollover is the server day change, 17:00 New York: a position opened at that very moment does not pay Tuesday's,
// one closed at Friday's pays it.
Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-12-01", 16, 59), NewYork("2026-12-04", 16, 59)));
Assert.AreEqual(4, FinancingCalendar.Nights(NewYork("2026-12-01", 17), NewYork("2026-12-04", 10)));
Assert.AreEqual(6, FinancingCalendar.Nights(NewYork("2026-12-01", 10), NewYork("2026-12-04", 17)));
// Wednesday alone counts three; Friday one; none on Saturday and Sunday; a whole week seven; nothing backwards.
Assert.AreEqual(3, FinancingCalendar.Nights(NewYork("2026-12-02", 16), NewYork("2026-12-02", 18)));
Assert.AreEqual(1, FinancingCalendar.Nights(NewYork("2026-12-04", 12), NewYork("2026-12-07", 12)));
Assert.AreEqual(0, FinancingCalendar.Nights(NewYork("2026-12-05", 12), NewYork("2026-12-06", 18)));
Assert.AreEqual(7, FinancingCalendar.Nights(NewYork("2026-11-30", 12), NewYork("2026-12-07", 12)));
Assert.AreEqual(0, FinancingCalendar.Nights(NewYork("2026-12-04", 12), NewYork("2026-12-01", 12)));
// Over the whole ECB history the closed form equals counting every 17:00 New York, day by day.
var from = Utc("1999-01-04T00:00:00Z");
var to = Utc("2026-12-02T00:00:00Z");
var counted = 0;
for (var day = new DateOnly(1999, 1, 1); day <= new DateOnly(2026, 12, 3); day = day.AddDays(1))
{
var rollover = Zones.At(day, new TimeOnly(17, 0), Zones.NewYork);
if (rollover > from && rollover <= to && day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
{
counted += day.DayOfWeek == DayOfWeek.Wednesday ? 3 : 1;
}
}
Assert.AreEqual(counted, FinancingCalendar.Nights(from, to));
// The charge: 1,000 USD of EURUSD bought for five nights at 8.096 USD per 100,000 a night = 0.4048 USD; sold, a credit
// of 0.46 per 100,000 a night = −0.023.
Assert.AreEqual(0.4048m, VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_000m, 5));
Assert.AreEqual(-0.023m, VenueCosts.Etoro.Financing("EURUSD", Direction.Sell, 1_000m, 5));
Assert.AreEqual(0m, VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_000m, 0));
Assert.AreEqual(0m, VenueCosts.None.Financing("EURUSD", Direction.Buy, 1_000m, 5));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void CostMultipliersScaleCommissionSpreadAndPaidFinancingOnly()
{
var one = VenueCosts.Etoro;
Assert.AreEqual(one, one.Scaled(1m));
Assert.AreEqual(one.Fingerprint(), one.Scaled(1m).Fingerprint());
foreach (var m in new[] { 2m, 3m })
{
var scaled = one.Scaled(m);
Assert.AreEqual(one.Venue, scaled.Venue);
Assert.AreEqual(one.AsOf, scaled.AsOf);
Assert.AreEqual(one.MinimumUsd, scaled.MinimumUsd);
Assert.AreEqual(one.DefaultLeverage, scaled.DefaultLeverage);
Assert.AreEqual(one.StopMarginShare, scaled.StopMarginShare);
Assert.AreEqual(one.LiquidationLevel, scaled.LiquidationLevel);
CollectionAssert.AreEqual(one.Leverages.ToArray(), scaled.Leverages.ToArray());
Assert.AreNotEqual(one.Fingerprint(), scaled.Fingerprint());
Assert.AreEqual(one.Pairs.Count, scaled.Pairs.Count);
for (var i = 0; i < one.Pairs.Count; i++)
{
var a = one.Pairs[i];
var b = scaled.Pairs[i];
Assert.AreEqual(a.Pair, b.Pair);
Assert.AreEqual(a.InstrumentId, b.InstrumentId);
Assert.AreEqual(a.MaxLeverage, b.MaxLeverage);
Assert.AreEqual(a.FinancingEstimated, b.FinancingEstimated);
Assert.AreEqual(a.Spread * m, b.Spread, a.Pair);
Assert.AreEqual(a.PauseSpread * m, b.PauseSpread, a.Pair);
Assert.AreEqual(a.CommissionPerSide * m, b.CommissionPerSide, a.Pair);
// A charge grows with the multiplier; a credit stays what it is.
Assert.AreEqual(a.FinancingBuy > 0m ? a.FinancingBuy * m : a.FinancingBuy, b.FinancingBuy, a.Pair);
Assert.AreEqual(a.FinancingSell > 0m ? a.FinancingSell * m : a.FinancingSell, b.FinancingSell, a.Pair);
}
// EURUSD at 3×: spread 0.3, commission 0.015%, buy financing 24.288; the sell credit stays −0.46.
if (m == 3m)
{
var eurusd = scaled.Pair("EURUSD");
Assert.AreEqual(0.3m, eurusd.Spread);
Assert.AreEqual(0.00015m, eurusd.CommissionPerSide);
Assert.AreEqual(24.288m, eurusd.FinancingBuy);
Assert.AreEqual(-0.46m, eurusd.FinancingSell);
Assert.AreEqual(3m * one.Financing("EURUSD", Direction.Buy, 5_000m, 5), scaled.Financing("EURUSD", Direction.Buy, 5_000m, 5));
Assert.AreEqual(one.Financing("EURUSD", Direction.Sell, 5_000m, 5), scaled.Financing("EURUSD", Direction.Sell, 5_000m, 5));
}
}
// Costs that are zero stay zero; a negative multiplier means nothing.
Assert.AreEqual(VenueCosts.None, VenueCosts.None.Scaled(3m));
Assert.AreEqual(VenueCosts.None.Fingerprint(), VenueCosts.None.Scaled(3m).Fingerprint());
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => one.Scaled(-1m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEtoroTableCopiesAppendixA()
{
var costs = VenueCosts.Etoro;
Assert.AreEqual("etoro", costs.Venue);
Assert.AreEqual(new DateOnly(2026, 12, 2), costs.AsOf);
StringAssert.Contains(costs.Source, "appendice A");
StringAssert.Contains(costs.Source, "sezione 6.3");
Assert.AreEqual(1_000m, costs.MinimumUsd);
Assert.AreEqual(5, costs.DefaultLeverage);
Assert.AreEqual(0.5m, costs.StopMarginShare);
Assert.AreEqual(0.5m, costs.LiquidationLevel);
CollectionAssert.AreEqual(new[] { 1, 2, 5, 10, 20, 30 }, costs.Leverages.ToArray());
// The 28 pairs in the order of appendix A, which is the order of FxPairs.All.
CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), costs.Pairs.Select(p => p.Pair).ToArray());
CollectionAssert.AreEqual(AppendixA.Select(r => r.Pair).ToArray(), costs.Pairs.Select(p => p.Pair).ToArray());
Assert.AreEqual(34.0m, costs.Pairs.Sum(p => p.Spread));
Assert.AreEqual(318.6m, costs.Pairs.Sum(p => p.PauseSpread));
Assert.AreEqual(14, costs.Pairs.Count(p => p.MaxLeverage == 30));
Assert.AreEqual(14, costs.Pairs.Count(p => p.MaxLeverage == 20));
// The 1 December prices appendix A implies: usd(c) = 1,000 / units of a pair with base c; the yen from USDJPY's pip value.
var usd = new Dictionary<string, decimal>(StringComparer.Ordinal)
{
[Currencies.Usd] = 1m,
[Currencies.Jpy] = 0.062m / (1_000m * 0.01m),
};
foreach (var row in AppendixA)
{
usd.TryAdd(row.Pair[..3], 1_000m / row.Units);
}
foreach (var row in AppendixA)
{
var cost = costs.Pair(row.Pair);
Assert.AreEqual(row.Id, cost.InstrumentId, row.Pair);
Assert.AreEqual(row.Leverage, cost.MaxLeverage, row.Pair);
Assert.AreEqual(row.Spread, cost.Spread, row.Pair);
Assert.AreEqual(row.Pause, cost.PauseSpread, row.Pair);
Assert.AreEqual(row.Pair == "USDJPY" ? 0.00002m : 0.00005m, cost.CommissionPerSide, row.Pair);
var price = usd[row.Pair[..3]] / usd[row.Pair[3..]];
var pips = cost.CommissionPips(price);
Assert.IsTrue(Math.Abs(pips - row.CommissionPips) <= 0.01m, $"{row.Pair}: {pips.ToString("0.000", CultureInfo.InvariantCulture)} pip contro {row.CommissionPips}");
}
// USDJPY at 0.005% would be 0.81 pip, not the 0.32 of the table: the fee page's 0.002% is the one that fits.
var usdjpy = usd[Currencies.Usd] / usd[Currencies.Jpy];
Assert.IsTrue(Math.Abs((0.00005m * usdjpy / 0.01m) - 0.32m) > 0.4m);
// Financing: the twelve legs of section 6.3, stored in USD per 100,000 USD a night (pips × pip value per 1,000 × 100),
// give back the document's pips exactly; EURUSD's buy is the 8.10 USD of section 6.7.
foreach (var (pair, buy, sell) in FinancingPips)
{
var cost = costs.Pair(pair);
var pipValue = AppendixA.Single(r => r.Pair == pair).PipValue;
Assert.IsFalse(cost.FinancingEstimated, pair);
Assert.AreEqual(buy, cost.FinancingBuy / (pipValue * 100m), pair);
Assert.AreEqual(sell, cost.FinancingSell / (pipValue * 100m), pair);
}
Assert.AreEqual(8.10m, Math.Round(costs.Pair("EURUSD").FinancingBuy, 2));
// The sixteen pairs the document gives no rate for pay, on both sides, the largest known charge: AUDCHF's sale.
var largest = FinancingPips.SelectMany(f => new[] { costs.Pair(f.Pair).FinancingBuy, costs.Pair(f.Pair).FinancingSell }).Max();
Assert.AreEqual(costs.Pair("AUDCHF").FinancingSell, largest);
Assert.AreEqual(17.978m, largest);
var estimated = costs.Pairs.Where(p => p.FinancingEstimated).ToArray();
Assert.AreEqual(16, estimated.Length);
Assert.IsTrue(estimated.All(p => p.FinancingBuy == largest && p.FinancingSell == largest));
Assert.IsTrue(estimated.All(p => FinancingPips.All(f => f.Pair != p.Pair)));
// The comparison venue: the same pairs and leverages, nothing to pay.
var none = VenueCosts.None;
Assert.AreEqual(28, none.Pairs.Count);
Assert.IsTrue(none.Pairs.All(p => p is { Spread: 0m, PauseSpread: 0m, CommissionPerSide: 0m, FinancingBuy: 0m, FinancingSell: 0m, FinancingEstimated: false }));
Assert.IsNull(none.StopMarginShare);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AnUnknownLeverageIsRefusedInItalian()
{
var costs = VenueCosts.Etoro;
foreach (var leverage in new[] { 0, 3, 50, 400 })
{
var error = Assert.ThrowsExactly<ArgumentException>(() => costs.Margin(1_000m, leverage));
StringAssert.Contains(error.Message, "leva");
StringAssert.Contains(error.Message, "1, 2, 5, 10, 20, 30");
Assert.ThrowsExactly<ArgumentException>(() => costs.StopDistance(1.0859m, leverage));
}
// Above the pair's real-account leverage: AUDUSD stops at 20, GBPCHF too (less than the European 30).
var tooHigh = Assert.ThrowsExactly<ArgumentException>(() => costs.CheckLeverage("AUDUSD", 30));
StringAssert.Contains(tooHigh.Message, "AUDUSD");
StringAssert.Contains(tooHigh.Message, "20");
Assert.ThrowsExactly<ArgumentException>(() => costs.CheckLeverage("GBPCHF", 30));
Assert.ThrowsExactly<ArgumentException>(() => costs.StopDistance("GBPCHF", Direction.Buy, 1.1m, 30));
Assert.AreEqual(30, costs.CheckLeverage("EURUSD", 30));
Assert.AreEqual(20, costs.CheckLeverage("AUDUSD", 20));
// A pair that is not in the table.
var unknown = Assert.ThrowsExactly<ArgumentException>(() => costs.Pair("EURSEK"));
StringAssert.Contains(unknown.Message, "EURSEK");
StringAssert.Contains(unknown.Message, "coppia");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFingerprintChangesWithAnyValue()
{
var costs = VenueCosts.Etoro;
var print = costs.Fingerprint();
Assert.AreEqual(64, print.Length);
Assert.IsTrue(print.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f'));
// Written like the plan: snake_case, null fields left out; read back it is the same table with the same fingerprint.
var json = costs.ToJson();
StringAssert.Contains(json, "\"commission_per_side\":");
StringAssert.Contains(json, "\"financing_estimated\":");
StringAssert.Contains(json, "\"as_of\":\"2026-12-02\"");
var back = VenueCosts.FromJson(json);
Assert.AreEqual(costs, back);
Assert.AreEqual(print, back.Fingerprint());
Assert.AreEqual(json, back.ToJson());
Assert.IsFalse(VenueCosts.None.ToJson().Contains("stop_margin_share", StringComparison.Ordinal));
Assert.IsFalse(VenueCosts.None.ToJson().Contains("liquidation_level", StringComparison.Ordinal));
Assert.AreNotEqual(print, VenueCosts.None.Fingerprint());
var eurusd = costs.Pair("EURUSD");
VenueCosts WithPair(PairCost changed) => costs with { Pairs = [.. costs.Pairs.Select(p => p.Pair == changed.Pair ? changed : p)] };
VenueCosts[] changes =
[
costs with { Venue = "altra" },
costs with { AsOf = costs.AsOf.AddDays(1) },
costs with { Source = costs.Source + "." },
costs with { MinimumUsd = 999m },
costs with { DefaultLeverage = 2 },
costs with { Leverages = [1, 2, 5, 10, 20] },
costs with { StopMarginShare = 0.4m },
costs with { StopMarginShare = null },
costs with { LiquidationLevel = 0.3m },
costs with { Pairs = [.. costs.Pairs.Take(27)] },
WithPair(eurusd with { InstrumentId = 99 }),
WithPair(eurusd with { InstrumentId = null }),
WithPair(eurusd with { Spread = 0.2m }),
WithPair(eurusd with { PauseSpread = 2.3m }),
WithPair(eurusd with { MaxLeverage = 20 }),
WithPair(eurusd with { CommissionPerSide = 0.00006m }),
WithPair(eurusd with { FinancingBuy = 8.097m }),
WithPair(eurusd with { FinancingSell = -0.47m }),
WithPair(eurusd with { FinancingEstimated = true }),
];
var prints = new HashSet<string>(StringComparer.Ordinal) { print };
foreach (var changed in changes)
{
Assert.AreNotEqual(costs, changed);
Assert.IsTrue(prints.Add(changed.Fingerprint()), changed.ToJson());
}
}
private static string Round(decimal value, int decimals) => Math.Round(value, decimals, MidpointRounding.AwayFromZero).ToString("F" + decimals, CultureInfo.InvariantCulture);
private static DateTimeOffset Utc(string text) => DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
private static DateTimeOffset NewYork(string day, int hour, int minute = 0) =>
Zones.At(DateOnly.Parse(day, CultureInfo.InvariantCulture), new TimeOnly(hour, minute), Zones.NewYork);
}