Fase 9 — Rifinitura e consegna in Docker #111
No files matched your search
@@ -0,0 +1,180 @@
|
||||
# Backtest di `crypto_relative_momentum` (Momentum relativo tra crypto)
|
||||
|
||||
**Esito: non superato.** Scartata nei test: deflated sharpe ratio 0,744, serve ≥ 0,90; calo massimo 35,3%, serve ≤ 25%. Resta in archivio, non riceve capitale.
|
||||
|
||||
Calcolato il 2026-12-01 con la versione 1 della strategia. 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 candidates --to 2026-10-31`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/crypto_relative_momentum.outcome.json`.
|
||||
|
||||
## Dati
|
||||
|
||||
- Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.
|
||||
- Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno (7133 giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1).
|
||||
- 47 coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni.
|
||||
- Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.
|
||||
- Senza archivi nel periodo, quindi non usate: BCCEUR, VENEUR.
|
||||
|
||||
## Riepilogo
|
||||
|
||||
| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
|
||||
|---|---|---:|---:|---:|---:|---:|---|
|
||||
| Universo ampio | `lookback=20;positions=2` | 7,3% | −35,3% | 5.586,23 € | 0,744 | 0,289 | non superata |
|
||||
|
||||
## Cosa conserva il bot
|
||||
|
||||
Una candidata non opera e non riceve capitale: queste cifre restano come documentazione, e servirebbero solo se un giorno avanzasse.
|
||||
|
||||
- Calo massimo del backtest: −35,2%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).
|
||||
- Scostamento di prezzo previsto: 11,62 punti base; costo stimato di andata e ritorno 0,63%.
|
||||
- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −5,2% dopo 30 giorni, −9,2% dopo 90, −17,7% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro.
|
||||
|
||||
## Universo ampio
|
||||
|
||||
Le 3 monete più forti a 30 giorni tra le 10 con più scambi, scelte ogni mese tra 47 coppie (anche quelle poi chiuse).
|
||||
|
||||
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `lookback=20;positions=2` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `373c7434e77d`, dei dati `840015607150`.
|
||||
|
||||
| | Strategia | Comprare e tenere |
|
||||
|---|---:|---:|
|
||||
| Risultato netto | 7.350,22 € | 82.820,55 € |
|
||||
| Rendimento totale | 73,5% | 828,2% |
|
||||
| Rendimento annuo | 7,3% | 32,9% |
|
||||
| Volatilità annua | 16,1% | 74,7% |
|
||||
| Calo massimo | −35,3% (02/2021 → 10/2023) | −85,8% |
|
||||
| Sharpe annuo | 0,52 | 0,76 |
|
||||
| Operazioni chiuse | 194 | 0 |
|
||||
| Operazioni in guadagno | 33,0% | — |
|
||||
| Rapporto guadagni/perdite | 1,43 | — |
|
||||
| Commissioni pagate | 1.068,52 € | 20,00 € |
|
||||
| Tempo investito | 10,4% | 92,0% |
|
||||
|
||||
**Per anno**
|
||||
|
||||
| Anno | Strategia | Comprare e tenere |
|
||||
|---|---:|---:|
|
||||
| 2019 | −8,4% | 4,8% |
|
||||
| 2020 | 10,5% | 103,2% |
|
||||
| 2021 | 22,7% | 1.603,8% |
|
||||
| 2022 | −1,0% | −79,9% |
|
||||
| 2023 | 37,9% | 56,4% |
|
||||
| 2024 | 3,2% | 33,8% |
|
||||
| 2025 | −6,5% | −32,9% |
|
||||
| 2026 | 6,1% | −9,4% |
|
||||
|
||||
**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)
|
||||
|
||||
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| ×1 | 7.350,22 € | 73,5% | 0,52 | −35,3% | 1.068,52 € |
|
||||
| ×2 | 5.586,23 € | 55,9% | 0,43 | −36,4% | 2.037,03 € |
|
||||
| ×3 | 3.220,73 € | 32,2% | 0,30 | −39,7% | 2.804,15 € |
|
||||
|
||||
**Convalide**
|
||||
|
||||
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 56,2%, Sharpe annuo 0,52.
|
||||
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,33, peggiore 0,16, percorsi positivi 100,0%.
|
||||
- Deflated Sharpe Ratio 0,74, contando 9 varianti provate in tutto.
|
||||
- Probabilità di sovra-adattamento (PBO) 0,29, su 12870 combinazioni di 9 varianti.
|
||||
- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
|
||||
|
||||
**Soglie**
|
||||
|
||||
| Controllo | Valore | Soglia | Esito |
|
||||
|---|---:|---:|---|
|
||||
| Risultato netto con costi doppi | 5.586,23 € | > 0,00 € | superato |
|
||||
| Deflated Sharpe Ratio | 0,744 | ≥ 0,9 | **non superato** |
|
||||
| Probabilità di sovra-adattamento (PBO) | 0,289 | ≤ 0,4 | superato |
|
||||
| Calo massimo | 35,3% | ≤ 25% | **non superato** |
|
||||
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
|
||||
|
||||
**Varianti della griglia**
|
||||
|
||||
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| `lookback=20;positions=2` (scelta) | 0,52 | 0,29 | 7.350,22 € | −35,3% | 194 |
|
||||
| `lookback=20;positions=3` | 0,28 | 0,22 | 2.756,21 € | −34,3% | 274 |
|
||||
| `lookback=20;positions=4` | −0,01 | −0,01 | −807,55 € | −33,2% | 335 |
|
||||
| `lookback=30;positions=2` | 0,17 | 0,17 | 1.138,18 € | −30,9% | 182 |
|
||||
| `lookback=30;positions=3` | 0,19 | 0,19 | 1.446,50 € | −29,9% | 247 |
|
||||
| `lookback=30;positions=4` | 0,15 | 0,15 | 926,35 € | −29,8% | 308 |
|
||||
| `lookback=40;positions=2` | −0,12 | −0,12 | −1.638,85 € | −31,7% | 175 |
|
||||
| `lookback=40;positions=3` | 0,32 | 0,17 | 3.451,75 € | −32,7% | 247 |
|
||||
| `lookback=40;positions=4` | 0,32 | 0,25 | 3.446,03 € | −32,0% | 305 |
|
||||
|
||||
**Interventi di correttivi e rischio sulla variante scelta**
|
||||
|
||||
Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.
|
||||
|
||||
| Motivo | Volte |
|
||||
|---|---:|
|
||||
| `trade_risk_limit` | 68 |
|
||||
| `risk_reduction` | 37 |
|
||||
| `switch_tripped` | 1 |
|
||||
|
||||
**Note del motore di prova**
|
||||
|
||||
Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.
|
||||
|
||||
| Motivo | Volte |
|
||||
|---|---:|
|
||||
| `residue_written_off` | 194 |
|
||||
|
||||
**Strumenti**
|
||||
|
||||
| Coppia | Prima barra | Ultima barra | Barre |
|
||||
|---|---|---|---:|
|
||||
| ADAEUR | 2018-04-17 | 2026-10-31 | 3120 |
|
||||
| APEEUR | 2022-03-17 | 2026-10-31 | 1690 |
|
||||
| ARBEUR | 2023-03-23 | 2026-10-31 | 1319 |
|
||||
| ATOMEUR | 2019-04-29 | 2026-10-31 | 2743 |
|
||||
| AVAXEUR | 2020-09-22 | 2026-10-31 | 2231 |
|
||||
| BCHABCEUR | 2018-11-16 | 2019-11-28 | 378 |
|
||||
| BCHEUR | 2019-11-28 | 2026-10-31 | 2530 |
|
||||
| BCHSVEUR | 2018-11-16 | 2019-04-22 | 158 |
|
||||
| BNBEUR | 2017-11-06 | 2026-10-31 | 3282 |
|
||||
| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||
| DASHEUR | 2019-03-28 | 2026-10-31 | 2775 |
|
||||
| DOGEEUR | 2019-07-05 | 2026-10-31 | 2676 |
|
||||
| DOTEUR | 2020-08-18 | 2026-10-31 | 2266 |
|
||||
| EOSEUR | 2018-05-28 | 2025-05-26 | 2556 |
|
||||
| ETCEUR | 2018-06-12 | 2026-10-31 | 3064 |
|
||||
| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 |
|
||||
| FILEUR | 2020-10-15 | 2026-10-31 | 2208 |
|
||||
| FTTEUR | 2019-12-20 | 2022-11-15 | 1062 |
|
||||
| GMTEUR | 2022-03-09 | 2026-10-31 | 1698 |
|
||||
| ICXEUR | 2018-06-13 | 2026-09-03 | 3005 |
|
||||
| IOTAEUR | 2018-05-31 | 2026-10-31 | 3076 |
|
||||
| LINKEUR | 2019-01-16 | 2026-10-31 | 2846 |
|
||||
| LTCEUR | 2017-12-13 | 2026-10-31 | 3245 |
|
||||
| LUNAEUR | 2020-08-21 | 2022-05-13 | 631 |
|
||||
| MATICEUR | 2019-04-26 | 2024-09-10 | 1965 |
|
||||
| NEAREUR | 2020-10-14 | 2026-10-31 | 2209 |
|
||||
| NEOEUR | 2017-11-20 | 2026-10-31 | 3268 |
|
||||
| ONTEUR | 2018-06-08 | 2026-10-31 | 3068 |
|
||||
| OPEUR | 2022-06-01 | 2026-10-31 | 1614 |
|
||||
| ORDIEUR | 2023-11-07 | 2026-10-31 | 1090 |
|
||||
| PEPEEUR | 2023-05-05 | 2026-10-31 | 1276 |
|
||||
| POLEUR | 2024-09-13 | 2026-10-31 | 779 |
|
||||
| QTUMEUR | 2018-03-19 | 2026-10-31 | 3149 |
|
||||
| SANDEUR | 2020-08-14 | 2026-10-31 | 2270 |
|
||||
| SHIBEUR | 2021-05-10 | 2026-10-31 | 2001 |
|
||||
| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 |
|
||||
| SUIEUR | 2023-05-03 | 2026-10-31 | 1278 |
|
||||
| TONEUR | 2024-08-08 | 2026-06-30 | 692 |
|
||||
| TRUMPEUR | 2025-01-19 | 2026-10-31 | 651 |
|
||||
| TRXEUR | 2018-06-11 | 2026-10-31 | 3065 |
|
||||
| UNIEUR | 2020-09-17 | 2026-10-31 | 2236 |
|
||||
| VETEUR | 2018-07-25 | 2026-10-31 | 3021 |
|
||||
| WIFEUR | 2024-03-05 | 2026-10-31 | 971 |
|
||||
| XLMEUR | 2018-05-31 | 2026-10-31 | 3076 |
|
||||
| XMREUR | 2019-03-15 | 2024-02-20 | 1804 |
|
||||
| XRPEUR | 2018-05-04 | 2026-10-31 | 3103 |
|
||||
| ZECEUR | 2019-03-21 | 2026-10-31 | 2782 |
|
||||
|
||||
## Cosa il backtest non rappresenta
|
||||
|
||||
- I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.
|
||||
- Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.
|
||||
- Sharpe e volatilità sono calcolati senza tasso privo di rischio.
|
||||
- Limiti di rischio applicati come dal vivo. La strategia è il 40% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo.
|
||||
- Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX.
|
||||
@@ -0,0 +1,377 @@
|
||||
{
|
||||
"passed": false,
|
||||
"verdict": "Scartata nei test: deflated sharpe ratio 0,744, serve \u2265 0,90; calo massimo 35,3%, serve \u2264 25%. Resta in archivio, non riceve capitale.",
|
||||
"report": "docs/backtests/crypto_relative_momentum.md",
|
||||
"plan_hash": "373c7434e77dacb965704c49d41dc44d5719c92c634b0c3bad78a473ccc7440d",
|
||||
"parameters": "lookback=20;positions=2",
|
||||
"max_drawdown": 0.3525,
|
||||
"expected_slippage_bp": 11.62,
|
||||
"round_trip_cost": 0.006324,
|
||||
"expected_path_p5": [
|
||||
-0.0104,
|
||||
-0.0139,
|
||||
-0.0179,
|
||||
-0.0214,
|
||||
-0.0237,
|
||||
-0.0267,
|
||||
-0.0274,
|
||||
-0.0292,
|
||||
-0.0314,
|
||||
-0.0322,
|
||||
-0.0323,
|
||||
-0.0352,
|
||||
-0.0362,
|
||||
-0.0379,
|
||||
-0.0383,
|
||||
-0.0401,
|
||||
-0.0414,
|
||||
-0.0419,
|
||||
-0.0435,
|
||||
-0.0433,
|
||||
-0.0443,
|
||||
-0.0444,
|
||||
-0.045,
|
||||
-0.0475,
|
||||
-0.0475,
|
||||
-0.0493,
|
||||
-0.0492,
|
||||
-0.0496,
|
||||
-0.0505,
|
||||
-0.0517,
|
||||
-0.0525,
|
||||
-0.0533,
|
||||
-0.053,
|
||||
-0.0542,
|
||||
-0.055,
|
||||
-0.0557,
|
||||
-0.0571,
|
||||
-0.0585,
|
||||
-0.0584,
|
||||
-0.0592,
|
||||
-0.0601,
|
||||
-0.0595,
|
||||
-0.0626,
|
||||
-0.0635,
|
||||
-0.0638,
|
||||
-0.0654,
|
||||
-0.0659,
|
||||
-0.0653,
|
||||
-0.0662,
|
||||
-0.0682,
|
||||
-0.0678,
|
||||
-0.0695,
|
||||
-0.0705,
|
||||
-0.0707,
|
||||
-0.0727,
|
||||
-0.0732,
|
||||
-0.0738,
|
||||
-0.074,
|
||||
-0.0744,
|
||||
-0.0756,
|
||||
-0.0766,
|
||||
-0.0777,
|
||||
-0.0777,
|
||||
-0.078,
|
||||
-0.0788,
|
||||
-0.0788,
|
||||
-0.0802,
|
||||
-0.0797,
|
||||
-0.081,
|
||||
-0.0813,
|
||||
-0.0828,
|
||||
-0.0823,
|
||||
-0.0832,
|
||||
-0.0827,
|
||||
-0.0839,
|
||||
-0.084,
|
||||
-0.0847,
|
||||
-0.0859,
|
||||
-0.0853,
|
||||
-0.086,
|
||||
-0.0864,
|
||||
-0.0879,
|
||||
-0.0883,
|
||||
-0.0887,
|
||||
-0.0895,
|
||||
-0.0901,
|
||||
-0.0901,
|
||||
-0.0918,
|
||||
-0.0927,
|
||||
-0.0925,
|
||||
-0.0925,
|
||||
-0.0937,
|
||||
-0.0945,
|
||||
-0.0936,
|
||||
-0.0932,
|
||||
-0.0949,
|
||||
-0.0942,
|
||||
-0.0954,
|
||||
-0.095,
|
||||
-0.0968,
|
||||
-0.0956,
|
||||
-0.0975,
|
||||
-0.0976,
|
||||
-0.0975,
|
||||
-0.0979,
|
||||
-0.0984,
|
||||
-0.0986,
|
||||
-0.0991,
|
||||
-0.0991,
|
||||
-0.0993,
|
||||
-0.0997,
|
||||
-0.0991,
|
||||
-0.0997,
|
||||
-0.1,
|
||||
-0.0998,
|
||||
-0.1005,
|
||||
-0.1018,
|
||||
-0.1008,
|
||||
-0.1021,
|
||||
-0.1018,
|
||||
-0.1025,
|
||||
-0.1035,
|
||||
-0.1031,
|
||||
-0.1029,
|
||||
-0.1042,
|
||||
-0.1042,
|
||||
-0.1023,
|
||||
-0.1039,
|
||||
-0.1044,
|
||||
-0.1052,
|
||||
-0.106,
|
||||
-0.1054,
|
||||
-0.1074,
|
||||
-0.108,
|
||||
-0.1088,
|
||||
-0.1088,
|
||||
-0.1107,
|
||||
-0.1116,
|
||||
-0.1126,
|
||||
-0.1119,
|
||||
-0.1125,
|
||||
-0.1127,
|
||||
-0.1126,
|
||||
-0.1125,
|
||||
-0.1126,
|
||||
-0.1135,
|
||||
-0.1126,
|
||||
-0.1138,
|
||||
-0.1135,
|
||||
-0.1138,
|
||||
-0.1145,
|
||||
-0.1156,
|
||||
-0.1164,
|
||||
-0.1171,
|
||||
-0.1174,
|
||||
-0.1193,
|
||||
-0.1165,
|
||||
-0.1175,
|
||||
-0.1174,
|
||||
-0.1194,
|
||||
-0.1189,
|
||||
-0.1204,
|
||||
-0.1196,
|
||||
-0.1173,
|
||||
-0.1177,
|
||||
-0.1173,
|
||||
-0.1174,
|
||||
-0.1168,
|
||||
-0.12,
|
||||
-0.1204,
|
||||
-0.1206,
|
||||
-0.1214,
|
||||
-0.1214,
|
||||
-0.1226,
|
||||
-0.1215,
|
||||
-0.1236,
|
||||
-0.1221,
|
||||
-0.1238,
|
||||
-0.1243,
|
||||
-0.1256,
|
||||
-0.1253,
|
||||
-0.1265,
|
||||
-0.1273,
|
||||
-0.1279,
|
||||
-0.1294,
|
||||
-0.1274,
|
||||
-0.1274,
|
||||
-0.1274,
|
||||
-0.1269,
|
||||
-0.1267,
|
||||
-0.1274,
|
||||
-0.1281,
|
||||
-0.1274,
|
||||
-0.1274,
|
||||
-0.1276,
|
||||
-0.1291,
|
||||
-0.1294,
|
||||
-0.1287,
|
||||
-0.1297,
|
||||
-0.1294,
|
||||
-0.1293,
|
||||
-0.1305,
|
||||
-0.1302,
|
||||
-0.1301,
|
||||
-0.1299,
|
||||
-0.1328,
|
||||
-0.132,
|
||||
-0.132,
|
||||
-0.1342,
|
||||
-0.1338,
|
||||
-0.1345,
|
||||
-0.1364,
|
||||
-0.1361,
|
||||
-0.1364,
|
||||
-0.1372,
|
||||
-0.1374,
|
||||
-0.1374,
|
||||
-0.1393,
|
||||
-0.1394,
|
||||
-0.1375,
|
||||
-0.1395,
|
||||
-0.1395,
|
||||
-0.1416,
|
||||
-0.1418,
|
||||
-0.1403,
|
||||
-0.1394,
|
||||
-0.1415,
|
||||
-0.1427,
|
||||
-0.1427,
|
||||
-0.142,
|
||||
-0.1425,
|
||||
-0.1441,
|
||||
-0.1435,
|
||||
-0.1444,
|
||||
-0.1448,
|
||||
-0.1444,
|
||||
-0.1466,
|
||||
-0.1453,
|
||||
-0.1466,
|
||||
-0.1471,
|
||||
-0.1492,
|
||||
-0.1489,
|
||||
-0.1504,
|
||||
-0.1509,
|
||||
-0.1499,
|
||||
-0.151,
|
||||
-0.151,
|
||||
-0.1512,
|
||||
-0.1529,
|
||||
-0.1512,
|
||||
-0.151,
|
||||
-0.1506,
|
||||
-0.149,
|
||||
-0.1496,
|
||||
-0.1494,
|
||||
-0.1496,
|
||||
-0.1518,
|
||||
-0.1527,
|
||||
-0.1541,
|
||||
-0.1551,
|
||||
-0.1548,
|
||||
-0.1542,
|
||||
-0.1541,
|
||||
-0.1552,
|
||||
-0.1552,
|
||||
-0.1563,
|
||||
-0.1556,
|
||||
-0.1552,
|
||||
-0.1563,
|
||||
-0.1569,
|
||||
-0.1563,
|
||||
-0.1575,
|
||||
-0.1569,
|
||||
-0.1563,
|
||||
-0.1563,
|
||||
-0.1568,
|
||||
-0.1562,
|
||||
-0.1563,
|
||||
-0.1569,
|
||||
-0.1563,
|
||||
-0.1569,
|
||||
-0.1575,
|
||||
-0.1586,
|
||||
-0.1586,
|
||||
-0.1591,
|
||||
-0.1601,
|
||||
-0.1603,
|
||||
-0.1607,
|
||||
-0.1614,
|
||||
-0.1626,
|
||||
-0.1614,
|
||||
-0.1621,
|
||||
-0.1612,
|
||||
-0.1622,
|
||||
-0.1621,
|
||||
-0.1625,
|
||||
-0.163,
|
||||
-0.1614,
|
||||
-0.1611,
|
||||
-0.1614,
|
||||
-0.1614,
|
||||
-0.1604,
|
||||
-0.1605,
|
||||
-0.1614,
|
||||
-0.1614,
|
||||
-0.1614,
|
||||
-0.1621,
|
||||
-0.1609,
|
||||
-0.1606,
|
||||
-0.1604,
|
||||
-0.1604,
|
||||
-0.1614,
|
||||
-0.1609,
|
||||
-0.1611,
|
||||
-0.1614,
|
||||
-0.1621,
|
||||
-0.1626,
|
||||
-0.1626,
|
||||
-0.1624,
|
||||
-0.1647,
|
||||
-0.1639,
|
||||
-0.167,
|
||||
-0.167,
|
||||
-0.166,
|
||||
-0.1656,
|
||||
-0.1674,
|
||||
-0.1659,
|
||||
-0.1685,
|
||||
-0.1693,
|
||||
-0.1696,
|
||||
-0.1702,
|
||||
-0.1703,
|
||||
-0.1708,
|
||||
-0.1706,
|
||||
-0.1707,
|
||||
-0.17,
|
||||
-0.1705,
|
||||
-0.1702,
|
||||
-0.1707,
|
||||
-0.1707,
|
||||
-0.1714,
|
||||
-0.1707,
|
||||
-0.172,
|
||||
-0.1707,
|
||||
-0.172,
|
||||
-0.1722,
|
||||
-0.1734,
|
||||
-0.1727,
|
||||
-0.1739,
|
||||
-0.1747,
|
||||
-0.1741,
|
||||
-0.1749,
|
||||
-0.1749,
|
||||
-0.1747,
|
||||
-0.1749,
|
||||
-0.1744,
|
||||
-0.174,
|
||||
-0.1751,
|
||||
-0.1737,
|
||||
-0.1736,
|
||||
-0.1732,
|
||||
-0.1767,
|
||||
-0.1768,
|
||||
-0.1768,
|
||||
-0.1772
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Backtest di `stock_ath_breakout` (Nuovi massimi storici sulle azioni USA)
|
||||
|
||||
**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare. Raccoglie solo segnali, senza capitale.
|
||||
|
||||
Per provare questa strategia servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.
|
||||
|
||||
Le regole sono già fissate (ADR 0020): compra all'apertura dopo una chiusura sopra tutte le chiusure precedenti, con almeno 300 sedute di storia; esce solo con lo stop a 10 ATR(42) sotto il massimo raggiunto. La storia raccolta parte dal 2016: un titolo che aveva un massimo più alto prima di allora conta lo stesso come nuovo massimo.
|
||||
|
||||
Finché manca il backtest la strategia resta in osservazione, senza capitale: scrive i suoi segnali quando ci sono i dati e non manda mai ordini.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"passed": false,
|
||||
"verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare. Raccoglie solo segnali, senza capitale.",
|
||||
"report": "docs/backtests/stock_ath_breakout.md",
|
||||
"max_drawdown": 0,
|
||||
"expected_slippage_bp": 0,
|
||||
"round_trip_cost": 0,
|
||||
"expected_path_p5": []
|
||||
}
|
||||
@@ -485,7 +485,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.observing dt { font-weight: 650; padding-right: 32px; }
|
||||
.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); }
|
||||
.observing form { margin: 0; flex: none; }
|
||||
.attention { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.attention, .observing .clock { display: inline-flex; align-items: center; gap: 6px; }
|
||||
|
||||
/* ---- Rischio ---- */
|
||||
.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
|
||||
|
||||
@@ -14,18 +14,19 @@ namespace Anubis.Server;
|
||||
/// Binance daily archives (each checked against its SHA-256) and the ECB rates into the research history, converts
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class BacktestCommand
|
||||
{
|
||||
private const string Usage =
|
||||
"Uso: anubis backtest base [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||
"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: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||
|
||||
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] != "base")
|
||||
if (args.Length < 1 || args[0] is not ("base" or "candidates"))
|
||||
{
|
||||
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||
return 2;
|
||||
@@ -66,23 +67,30 @@ internal static class BacktestCommand
|
||||
var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").ConfigureAwait(false);
|
||||
|
||||
var outcome = await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||
var candidates = args[0] == "candidates";
|
||||
var name = candidates ? StrategyNames.CryptoRelativeMomentum : StrategyNames.CryptoTrend;
|
||||
var outcome = candidates
|
||||
? await CandidateProtocol.RunCryptoAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false)
|
||||
: await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||
var notes = DataNotes(outcome, rates);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.md"),
|
||||
ProtocolReport.Markdown(outcome, "crypto_trend", notes, "anubis backtest base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, name + ".md"),
|
||||
ProtocolReport.Markdown(outcome, name, notes, $"anubis backtest {args[0]} --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, name + ".outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||
foreach (var run in outcome.Runs)
|
||||
{
|
||||
// The full reports (curve, trades) stay with the data: the repository keeps the summary and the outcome.
|
||||
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, "crypto_trend-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, name + "-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") })
|
||||
(string Strategy, string Name, Qualification Waiting, IReadOnlyList<string> Lines)[] waiting = candidates
|
||||
? [(StrategyNames.StockAthBreakout, StrategyNames.Label(StrategyNames.StockAthBreakout), CandidateProtocol.StockWaiting(), CandidateProtocol.StockExplanation)]
|
||||
: [(StrategyNames.EquityMomentum, "Momentum azioni", EquityProtocol.Waiting(StrategyNames.EquityMomentum), EquityProtocol.Explanation),
|
||||
(StrategyNames.EquityMeanrev, "Ritorno alla media azioni", EquityProtocol.Waiting(StrategyNames.EquityMeanrev), EquityProtocol.Explanation)];
|
||||
foreach (var w in waiting)
|
||||
{
|
||||
var waiting = EquityProtocol.Waiting(strategy);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".md"), ProtocolReport.Waiting(w.Strategy, w.Name, w.Waiting, w.Lines)).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".outcome.json"), BacktestOutcomes.ToJson(w.Waiting)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false);
|
||||
|
||||
@@ -23,12 +23,14 @@
|
||||
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
|
||||
{
|
||||
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
|
||||
// The candidates count among the observed ones, the discarded ones no more (mockup 04).
|
||||
var count = here.Count + (stage == StrategyStages.Observation ? v.Candidates.Count(x => !x.Archived) : 0);
|
||||
<li class="@(here.Count > 0 ? "here" : null)">
|
||||
<span class="step">@(i + 1)</span>
|
||||
<strong>@Capital(StrategyStages.Label(stage))</strong>
|
||||
<p>@StageText(stage)</p>
|
||||
<p class="stage-count">
|
||||
@if (here.Count == 0)
|
||||
@if (count == 0)
|
||||
{
|
||||
<span class="muted">Nessuna strategia</span>
|
||||
}
|
||||
@@ -38,7 +40,7 @@
|
||||
{
|
||||
<span class="swatch round" style="background: @x.Color"></span>
|
||||
}
|
||||
<strong>@(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")</strong>
|
||||
<strong>@(count == 1 ? "1 strategia" : $"{count} strategie")</strong>
|
||||
}
|
||||
</p>
|
||||
</li>
|
||||
@@ -189,9 +191,9 @@
|
||||
<h2 id="osservazione">In osservazione</h2>
|
||||
<a href="/laboratorio">Prova una nuova strategia nel laboratorio</a>
|
||||
</div>
|
||||
@if (watching.Count == 0)
|
||||
@if (watching.Count == 0 && v.Candidates.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna strategia di base in osservazione.</p>
|
||||
<p class="note">Nessuna strategia in osservazione.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -209,7 +211,26 @@
|
||||
}
|
||||
else if (!passed)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")</span>
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(StrategiesView.IsWaiting(s.Stage) ? "In attesa dei dati" : "Non supera i test")</span>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
@foreach (var s in v.Candidates)
|
||||
{
|
||||
<dt>@s.Name</dt>
|
||||
<dd>
|
||||
<span>@s.Text@if (!Shell.IsDemo && StrategiesView.ReportOf(s.Stage) is { } report) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||
@if (s.Archived)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />Non supera i test</span>
|
||||
}
|
||||
else if (s.Waiting)
|
||||
{
|
||||
<span class="attention nowrap"><Icon Name="alert" Size="16" />In attesa dei dati</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="nowrap clock"><Icon Name="clock" Size="16" />@(Math.Min(s.Days, StageBook.ObservationDays)) giorni su @StageBook.ObservationDays</span>
|
||||
}
|
||||
</dd>
|
||||
}
|
||||
|
||||
@@ -34,11 +34,45 @@ internal sealed record StrategyCard(
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
|
||||
/// strategy with its requirements, and the ones in observation with the reason.
|
||||
/// A candidate of SPEC 8.4 on the same screen: only the signals collected so far, or why it was discarded. It has no
|
||||
/// capital, no card and no button.
|
||||
/// </summary>
|
||||
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
|
||||
internal sealed record CandidateLine(StrategyStage Stage, string Name, int Signals, int Days)
|
||||
{
|
||||
public bool Archived => StageBook.IsArchived(Stage);
|
||||
|
||||
public bool Waiting => StrategiesView.IsWaiting(Stage);
|
||||
|
||||
public string Text
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Archived)
|
||||
{
|
||||
return Stage.Qualification!.Verdict;
|
||||
}
|
||||
|
||||
var signals = $"Raccoglie segnali senza fare ordini: {Signals} in {Days} {(Days == 1 ? "giorno" : "giorni")}.";
|
||||
return signals + " " + (Waiting ? Stage.Qualification!.Verdict
|
||||
: Days < StageBook.ObservationDays ? $"Servono almeno {StageBook.ObservationDays} giorni per giudicarla."
|
||||
: $"I {StageBook.ObservationDays} giorni di segnali sono raccolti; resta senza capitale.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
|
||||
/// strategy with its requirements, and the ones in observation with the reason, the candidates of 8.4 among them.
|
||||
/// </summary>
|
||||
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, IReadOnlyList<CandidateLine> Candidates, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
|
||||
{
|
||||
/// <summary>Whether a strategy's backtest could not be run yet for lack of data: not the same as having failed it.</summary>
|
||||
public static bool IsWaiting(StrategyStage stage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stage);
|
||||
return stage.Qualification is { Passed: false, PlanHash: null };
|
||||
}
|
||||
|
||||
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
|
||||
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
|
||||
{
|
||||
@@ -82,9 +116,19 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
|
||||
.ConfigureAwait(false) ?? "?";
|
||||
var cards = new List<StrategyCard>();
|
||||
var candidates = new List<CandidateLine>();
|
||||
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
|
||||
if (StrategyNames.IsCandidate(stage.Strategy))
|
||||
{
|
||||
var observedFrom = stage.StageSince ?? clock.UtcNow;
|
||||
var signals = await services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l AND strategy = @s AND decided_at >= @f",
|
||||
("l", Anubis.Learning.CaseSources.Live), ("s", stage.Strategy), ("f", observedFrom)), cancellationToken).ConfigureAwait(false);
|
||||
candidates.Add(new CandidateLine(stage, StrategyNames.Label(stage.Strategy), (int)signals, Math.Max(0, (int)(clock.UtcNow - observedFrom).TotalDays)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!StrategyNames.IsBase(stage.Strategy))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -174,7 +218,8 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
}
|
||||
|
||||
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
|
||||
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
|
||||
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))],
|
||||
[.. candidates.OrderBy(c => c.Archived).ThenBy(c => c.Name, StringComparer.Ordinal)], liveAllowed, live);
|
||||
}
|
||||
|
||||
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>
|
||||
/// The protocol of SPEC 12.2 for the candidates of 8.4. <c>crypto_relative_momentum</c> runs once, on the broad universe
|
||||
/// of <c>crypto_trend</c>: choosing three coins among three would say nothing. <c>stock_ath_breakout</c> waits for the Alpaca
|
||||
/// history. Dates, capital, grid, costs and thresholds are those of the base strategies, fixed before the run; the
|
||||
/// outcome is written whatever it is, and neither outcome gives a candidate any capital.
|
||||
/// </summary>
|
||||
public static class CandidateProtocol
|
||||
{
|
||||
public static string ReportPath(string strategy) => "docs/backtests/" + strategy + ".md";
|
||||
|
||||
public static async Task<ProtocolOutcome> RunCryptoAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action<string>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
|
||||
if (!broad.Contains("BTCEUR"))
|
||||
{
|
||||
throw new InvalidOperationException("Manca lo storico di BTC in euro: scarica prima gli archivi Binance e il cambio BCE.");
|
||||
}
|
||||
|
||||
var run = await CryptoTrendProtocol.RunOneAsync(CryptoRelativeMomentumFamily.Instance, "Universo ampio",
|
||||
$"Le 3 monete più forti a 30 giorni tra le 10 con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).",
|
||||
broad, to, now, researchRoot, PriorTrials.None, progress, cancellationToken).ConfigureAwait(false);
|
||||
return new ProtocolOutcome(QualificationOf(run), [run]);
|
||||
}
|
||||
|
||||
public static Qualification QualificationOf(ProtocolRun run)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(run);
|
||||
var report = run.Report;
|
||||
var it = CultureInfo.GetCultureInfo("it-IT");
|
||||
var verdict = report.Passed
|
||||
? "Protocollo superato sui dati storici. Resta in osservazione: servono anche 90 giorni di segnali dal vivo, e una candidata non riceve capitale senza una tua decisione."
|
||||
: "Scartata nei test: " + string.Join("; ", report.Checks.Where(c => c.Passed == false).Select(c => CryptoTrendProtocol.Describe(c, it))) + ". Resta in archivio, non riceve capitale.";
|
||||
return CryptoTrendProtocol.Measured(run, report.Strategy, report.Passed, verdict, ReportPath(report.Strategy));
|
||||
}
|
||||
|
||||
public static readonly IReadOnlyList<string> StockExplanation =
|
||||
[
|
||||
"Per provare questa strategia servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.",
|
||||
"Le regole sono già fissate (ADR 0020): compra all'apertura dopo una chiusura sopra tutte le chiusure precedenti, con almeno 300 sedute di storia; esce solo con lo stop a 10 ATR(42) sotto il massimo raggiunto. La storia raccolta parte dal 2016: un titolo che aveva un massimo più alto prima di allora conta lo stesso come nuovo massimo.",
|
||||
"Finché manca il backtest la strategia resta in osservazione, senza capitale: scrive i suoi segnali quando ci sono i dati e non manda mai ordini.",
|
||||
];
|
||||
|
||||
public static Qualification StockWaiting() => EquityProtocol.Waiting(StrategyNames.StockAthBreakout) with
|
||||
{
|
||||
Verdict = "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare. Raccoglie solo segnali, senza capitale.",
|
||||
};
|
||||
}
|
||||
@@ -138,7 +138,7 @@ public sealed partial class Laboratory : IDisposable
|
||||
family.Id,
|
||||
family.Version,
|
||||
grid,
|
||||
new TrialData(request.Source, request.Venue, symbols, request.From, request.To),
|
||||
new TrialData(request.Source, request.Venue, symbols, request.From, request.To) { FullHistory = family.NeedsFullHistory },
|
||||
request.InitialCapital,
|
||||
[1m, 2m, 3m],
|
||||
TrialValidation.Default,
|
||||
@@ -146,7 +146,7 @@ public sealed partial class Laboratory : IDisposable
|
||||
BacktestEngine.Version,
|
||||
now)
|
||||
{
|
||||
ReferenceShare = StrategyPipeline.DefaultShare(family.Id),
|
||||
ReferenceShare = StrategyPipeline.ResearchShare(family.Id),
|
||||
Slippage = slippage == SlippageTable.Standard ? null : slippage,
|
||||
};
|
||||
var variants = ParameterGrid.Of(family, plan.Grid).Count;
|
||||
|
||||
@@ -209,17 +209,23 @@ public static class CryptoTrendProtocol
|
||||
verdict = "Protocollo non superato. " + string.Join(". ", failures) + ". Resta in osservazione.";
|
||||
}
|
||||
|
||||
var taker = PaperOptions.Okx().TakerFee;
|
||||
return Measured(main, Strategy, passed, verdict, ReportPath);
|
||||
}
|
||||
|
||||
/// <summary>The figures an outcome keeps of the trial it comes from (SPEC 12.3), verdict aside.</summary>
|
||||
internal static Qualification Measured(ProtocolRun main, string strategy, bool passed, string verdict, string report)
|
||||
{
|
||||
var fee = StrategyNames.IsCrypto(strategy) ? PaperOptions.Okx().TakerFee : 0m;
|
||||
return new Qualification
|
||||
{
|
||||
Passed = passed,
|
||||
Verdict = verdict,
|
||||
Report = ReportPath,
|
||||
Report = report,
|
||||
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
|
||||
Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
|
||||
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
|
||||
ExpectedSlippageBp = main.ExpectedSlippageBp,
|
||||
RoundTripCost = Math.Round(2m * (taker + (main.ExpectedSlippageBp / 10_000m)), 6),
|
||||
RoundTripCost = Math.Round(2m * (fee + (main.ExpectedSlippageBp / 10_000m)), 6),
|
||||
ExpectedPathP5 = [.. PathBootstrap.Percentile(main.DailyReturns, PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
|
||||
.Select(x => Math.Round(x, 4))],
|
||||
};
|
||||
@@ -241,7 +247,7 @@ public static class CryptoTrendProtocol
|
||||
return $"{check.Name.ToLower(CultureInfo.GetCultureInfo("it-IT"))} {value}, serve {check.Comparison} {threshold}";
|
||||
}
|
||||
|
||||
private static async Task<ProtocolRun> RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList<string> symbols, DateOnly to,
|
||||
internal static async Task<ProtocolRun> RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList<string> symbols, DateOnly to,
|
||||
DateTimeOffset now, string researchRoot, PriorTrials prior, Action<string>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var request = new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, symbols, From, to, Capital, null);
|
||||
|
||||
@@ -47,6 +47,11 @@ public static class ProtocolReport
|
||||
|
||||
b.AppendLine();
|
||||
b.AppendLine("## Cosa conserva il bot").AppendLine();
|
||||
if (StrategyNames.IsCandidate(first.Strategy))
|
||||
{
|
||||
b.AppendLine("Una candidata non opera e non riceve capitale: queste cifre restano come documentazione, e servirebbero solo se un giorno avanzasse.").AppendLine();
|
||||
}
|
||||
|
||||
b.AppendLine(Text($"- Calo massimo del backtest: {Pct(-(double)q.MaxDrawdown)}. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3)."));
|
||||
b.AppendLine(Text($"- Scostamento di prezzo previsto: {q.ExpectedSlippageBp.ToString("0.##", It)} punti base; costo stimato di andata e ritorno {Pct((double)q.RoundTripCost, 2)}."));
|
||||
if (q.ExpectedPathP5.Count > 0)
|
||||
|
||||
@@ -249,11 +249,11 @@ public static class TrialRunner
|
||||
"Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.",
|
||||
"Sharpe e volatilità sono calcolati senza tasso privo di rischio.",
|
||||
};
|
||||
if (StrategyPipeline.IsBase(family.Id))
|
||||
if (StrategyPipeline.ResearchShare(family.Id) is { } researched)
|
||||
{
|
||||
var share = plan.ReferenceShare ?? StrategyPipeline.DefaultShare(family.Id) ?? 1m;
|
||||
var share = plan.ReferenceShare ?? researched;
|
||||
result.Add(string.Create(CultureInfo.GetCultureInfo("it-IT"),
|
||||
$"Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo."));
|
||||
$"{(family.Id == StrategyNames.CryptoTrend ? "Limiti di rischio e regime crypto applicati" : "Limiti di rischio applicati")} come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo."));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -227,11 +227,22 @@ public static class StrategyPipeline
|
||||
|
||||
public static bool IsBase(string strategy) => DefaultShare(strategy) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The share of the bot the risk limits assume for a strategy in a trial: the default one for the base strategies,
|
||||
/// that of its market for a candidate (SPEC 8.4), which has none of its own. Null for the examples.
|
||||
/// </summary>
|
||||
public static decimal? ResearchShare(string strategy) => DefaultShare(strategy) ?? strategy switch
|
||||
{
|
||||
StrategyNames.CryptoRelativeMomentum => 0.40m,
|
||||
StrategyNames.StockAthBreakout => 0.45m,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public static BacktestOptions For(string strategy, BacktestDataset data, BacktestOptions options, decimal? share = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (!IsBase(strategy))
|
||||
if (ResearchShare(strategy) is not { } researched)
|
||||
{
|
||||
return options;
|
||||
}
|
||||
@@ -242,6 +253,6 @@ public static class StrategyPipeline
|
||||
correctives = [new CryptoRegimeStage(bitcoin.Symbol)];
|
||||
}
|
||||
|
||||
return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? DefaultShare(strategy) };
|
||||
return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? researched };
|
||||
}
|
||||
}
|
||||
@@ -28,8 +28,12 @@ public sealed record TrialData(string Source, string Venue, IReadOnlyList<string
|
||||
/// <summary>Calendar days of history before the start: a year of 252 sessions, a 360-day lookback, 400 days of listing.</summary>
|
||||
public const int WarmupDays = 450;
|
||||
|
||||
/// <summary>Every bar there is before the start, for a strategy that needs the whole history (an all-time high).</summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public bool FullHistory { get; init; }
|
||||
|
||||
/// <summary>The first day read from the history.</summary>
|
||||
public DateOnly HistoryStart() => From.AddDays(-WarmupDays);
|
||||
public DateOnly HistoryStart() => FullHistory ? new DateOnly(2009, 1, 1) : From.AddDays(-WarmupDays);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -142,6 +142,36 @@ public static class DemoMode
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// F.3: the two candidates, one collecting signals for 31 days and one discarded.
|
||||
foreach (var (name, account, since, qualification) in new[]
|
||||
{
|
||||
(Trading.StrategyNames.StockAthBreakout, alpaca, 31, (Trading.Qualification?)null),
|
||||
(Trading.StrategyNames.CryptoRelativeMomentum, okx, 58, new Trading.Qualification
|
||||
{
|
||||
Passed = false,
|
||||
Verdict = "Scartata nei test: tolti i costi, il risultato è vicino a zero. Resta in archivio, non riceve capitale.",
|
||||
Report = "docs/backtests/crypto_relative_momentum.md",
|
||||
PlanHash = "esempio",
|
||||
}),
|
||||
})
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, qualification, capital, share, state, created_at, updated_at) " +
|
||||
"VALUES (@id, @n, @a, 'observation', @since, @q, 0, 0, @st, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-since)),
|
||||
("q", qualification is null ? null : new DbJson(JsonSerializer.Serialize(qualification, Trading.Qualification.Json))), ("st", new DbJson("{}")), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var i in Enumerable.Range(0, 14))
|
||||
{
|
||||
var at = now.AddDays(-30 + (2 * i));
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO ml_features (id, strategy, symbol, source, decided_day, decided_at, stage, reason, weight, features, multiplier, created_at) " +
|
||||
"VALUES (@id, @n, @sy, 'live', @d, @t, 'observation', 'ath_entry', 0.02, @f, 1, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("n", Trading.StrategyNames.StockAthBreakout), ("sy", "SEGNALE" + (i + 1).ToString(_it)), ("d", DateOnly.FromDateTime(at.UtcDateTime).ToString("yyyy-MM-dd", _it)),
|
||||
("f", new DbJson("{}")), ("t", at)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var started = now.AddDays(-60);
|
||||
await s.ExecuteAsync("INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, 'EUR', 'USD', @d, @r, 'ecb', @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("d", DateOnly.FromDateTime(Now.DateTime).ToString("yyyy-MM-dd", _it)), ("r", UsdRate), ("t", now.AddMinutes(-21)))
|
||||
|
||||
@@ -108,7 +108,7 @@ public static class Clues
|
||||
public static string? MarketOf(string strategy, StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (strategy != StrategyNames.CryptoTrend)
|
||||
if (!StrategyNames.IsCrypto(strategy))
|
||||
{
|
||||
return StrategyNames.MarketSymbol;
|
||||
}
|
||||
@@ -176,7 +176,7 @@ public static class Clues
|
||||
Put(Vix, outside.Vix);
|
||||
Put(Funding, outside.BtcFunding);
|
||||
Put(OpenInterest, outside.BtcOpenInterest);
|
||||
if (strategy != StrategyNames.CryptoTrend && outside.Earnings is { } earnings)
|
||||
if (!StrategyNames.IsCrypto(strategy) && outside.Earnings is { } earnings)
|
||||
{
|
||||
Put(EarningsDays, earnings.TryGetValue(intent.Symbol, out var day) ? Math.Clamp(day.DayNumber - context.Day.DayNumber, 0, FarReport) : FarReport);
|
||||
}
|
||||
|
||||
@@ -73,6 +73,8 @@ public static class DiscoveryFinder
|
||||
StrategyNames.CryptoTrend => "i segnali di trend sulle crypto",
|
||||
StrategyNames.EquityMomentum => "i segnali sulle azioni più forti",
|
||||
StrategyNames.EquityMeanrev => "i rimbalzi sulle azioni",
|
||||
StrategyNames.StockAthBreakout => "i nuovi massimi sulle azioni",
|
||||
StrategyNames.CryptoRelativeMomentum => "i segnali sulle crypto più forti",
|
||||
_ => "i segnali",
|
||||
};
|
||||
|
||||
|
||||
@@ -103,8 +103,8 @@ public sealed class SingleOperation(IStrategy inner, Example example) : IStrateg
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => inner.Schedule();
|
||||
|
||||
/// <summary>Only <c>equity_momentum</c> needs the others, to know the rank; the rest look at their own instrument.</summary>
|
||||
public static bool NeedsUniverse(string strategy) => strategy == StrategyNames.EquityMomentum;
|
||||
/// <summary>The strategies that rank need the others; the rest look at their own instrument.</summary>
|
||||
public static bool NeedsUniverse(string strategy) => strategy is StrategyNames.EquityMomentum or StrategyNames.CryptoRelativeMomentum;
|
||||
|
||||
public IReadOnlyList<string> Universe(UniverseContext context) => NeedsUniverse(inner.Id) ? inner.Universe(context) : [example.Symbol];
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(create);
|
||||
if (!StrategyPipeline.IsBase(strategy))
|
||||
if (StrategyPipeline.ResearchShare(strategy) is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>The fixed rules of <c>crypto_relative_momentum</c> (SPEC 8.4, ADR 0020).</summary>
|
||||
public sealed record CryptoRelativeMomentumSettings
|
||||
{
|
||||
/// <summary>Days of the return that ranks the coins.</summary>
|
||||
public int Lookback { get; init; } = 30;
|
||||
|
||||
/// <summary>The strongest coins bought.</summary>
|
||||
public int Positions { get; init; } = 3;
|
||||
|
||||
/// <summary>A coin held leaves when it falls out of these.</summary>
|
||||
public int Keep => Positions + 2;
|
||||
|
||||
/// <summary>Only with Bitcoin above its average of these days.</summary>
|
||||
public int MarketTrend { get; init; } = 200;
|
||||
|
||||
public int AtrLength { get; init; } = 20;
|
||||
|
||||
public double AtrMultiple { get; init; } = 3;
|
||||
|
||||
public int VolatilityWindow { get; init; } = 90;
|
||||
|
||||
public double StrategyVolatility { get; init; } = 0.20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>crypto_relative_momentum</c> (SPEC 8.4), a candidate: among the ten coins of <c>crypto_trend</c>'s universe, the
|
||||
/// strongest over 30 days, only with Bitcoin in a trend. The review is on the Sunday close; every close moves the
|
||||
/// trailing stops and leaves everything when Bitcoin falls below its average.
|
||||
/// </summary>
|
||||
public sealed class CryptoRelativeMomentum(CryptoRelativeMomentumSettings? settings = null) : IStrategy
|
||||
{
|
||||
private static readonly string[] Bitcoin = ["BTC-EUR", "BTCEUR", "BTCUSDT"];
|
||||
|
||||
private readonly CryptoRelativeMomentumSettings _settings = settings ?? new CryptoRelativeMomentumSettings();
|
||||
private readonly CryptoTrend _universe = new();
|
||||
|
||||
public string Id => CryptoRelativeMomentumFamily.FamilyId;
|
||||
|
||||
public string Version => CryptoRelativeMomentumFamily.FamilyVersion;
|
||||
|
||||
public CryptoRelativeMomentumSettings Settings => _settings;
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
/// <summary>The same ten coins as <c>crypto_trend</c>: live, the universe saved for it.</summary>
|
||||
public IReadOnlyList<string> Universe(UniverseContext context) => _universe.Universe(context);
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var held = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key).Order(StringComparer.Ordinal).ToList();
|
||||
if (!MarketUp(context))
|
||||
{
|
||||
return [.. held.Select(s => new Intent(s, 0m, Reasons.ExitMarket))];
|
||||
}
|
||||
|
||||
var intents = new SortedDictionary<string, Intent>(StringComparer.Ordinal);
|
||||
foreach (var symbol in held)
|
||||
{
|
||||
if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop };
|
||||
}
|
||||
}
|
||||
|
||||
if (context.Day.DayOfWeek != DayOfWeek.Sunday || context.Portfolio.Equity <= 0m)
|
||||
{
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
var ranking = context.Universe.Select(s => (Symbol: s, Return: Indicators.Momentum(context.Bars(s), _settings.Lookback, 0)))
|
||||
.Where(s => s.Return is not null).OrderByDescending(s => s.Return).ThenBy(s => s.Symbol, StringComparer.Ordinal).ToList();
|
||||
var keep = new HashSet<string>(ranking.Take(_settings.Keep).Select(r => r.Symbol), StringComparer.Ordinal);
|
||||
foreach (var symbol in held.Where(s => !keep.Contains(s)))
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, 0m, Reasons.ExitRank);
|
||||
}
|
||||
|
||||
var kept = held.Where(keep.Contains).ToList();
|
||||
var entries = ranking.Take(_settings.Positions).Where(r => r.Return > 0 && !held.Contains(r.Symbol)).Take(Math.Max(0, _settings.Positions - kept.Count)).ToList();
|
||||
|
||||
// Equal parts; one factor, never above 1, when the estimated volatility of the whole is above the limit.
|
||||
var part = 1d / _settings.Positions;
|
||||
var all = kept.Concat(entries.Select(e => e.Symbol)).Select(s => (context.Bars(s), part)).ToList();
|
||||
var volatility = Indicators.PortfolioVolatility(all, _settings.VolatilityWindow, context.PeriodsPerYear);
|
||||
var factor = volatility is { } v && v > _settings.StrategyVolatility ? _settings.StrategyVolatility / v : 1;
|
||||
var weight = Math.Round((decimal)(part * factor), 6, MidpointRounding.ToZero);
|
||||
foreach (var (symbol, momentum) in entries)
|
||||
{
|
||||
if (Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is > 0 and var atr)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8), Strength = momentum };
|
||||
}
|
||||
}
|
||||
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
private bool MarketUp(StrategyContext context)
|
||||
{
|
||||
var bitcoin = context.Universe.FirstOrDefault(s => Symbols.BaseOf(context.Spec(s), s) == "BTC") ?? Bitcoin.FirstOrDefault(s => context.Bars(s).Count > 0);
|
||||
if (bitcoin is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bars = context.Bars(bitcoin);
|
||||
return Indicators.Sma(bars, _settings.MarketTrend) is { } average && bars.Close(bars.Count - 1) > average;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "relative_entry";
|
||||
public const string ExitRank = "relative_exit_rank";
|
||||
public const string ExitMarket = "relative_exit_market";
|
||||
public const string StopMoved = "relative_stop";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CryptoRelativeMomentumFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "crypto_relative_momentum";
|
||||
|
||||
public const string FamilyVersion = "1";
|
||||
|
||||
public static CryptoRelativeMomentumFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => FamilyVersion;
|
||||
|
||||
public string Name => "Momentum relativo tra crypto";
|
||||
|
||||
public string Description =>
|
||||
"Strategia candidata, senza capitale: ogni settimana tiene le 3 crypto salite di più in 30 giorni tra le 10 più scambiate, solo mentre Bitcoin sta sopra la sua media di 200 giorni. " +
|
||||
"Ognuna ha uno stop che sale con il prezzo.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("lookback", "Giorni del rendimento che fa la classifica", 30m, [20m, 30m, 40m], 5m, 200m, Whole: true),
|
||||
new("positions", "Numero di monete", 3m, [2m, 3m, 4m], 1m, 10m, Whole: true),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new CryptoRelativeMomentum(new CryptoRelativeMomentumSettings { Lookback = parameters.Whole("lookback"), Positions = parameters.Whole("positions") });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The fixed rules of <c>stock_ath_breakout</c> (SPEC 8.4, ADR 0020).</summary>
|
||||
public sealed record StockAthBreakoutSettings
|
||||
{
|
||||
public int UniverseSize { get; init; } = EquityUniverse.Size;
|
||||
|
||||
/// <summary>Sessions of history before a high counts as the highest ever.</summary>
|
||||
public int MinSessions { get; init; } = EquityUniverse.MinSessions;
|
||||
|
||||
public int MaxPositions { get; init; } = 20;
|
||||
|
||||
public int AtrLength { get; init; } = 42;
|
||||
|
||||
public double AtrMultiple { get; init; } = 10;
|
||||
|
||||
public int VolatilityWindow { get; init; } = 60;
|
||||
|
||||
/// <summary>Volatility each stock adds: weight = this / its volatility, up to the cap.</summary>
|
||||
public double StockVolatility { get; init; } = 0.02;
|
||||
|
||||
public double Cap { get; init; } = 0.10;
|
||||
|
||||
/// <summary>A purchase smaller than this share of the capital is not worth its order.</summary>
|
||||
public double Minimum { get; init; } = 0.005;
|
||||
|
||||
public double StrategyVolatility { get; init; } = 0.20;
|
||||
|
||||
/// <summary>When the new highs of a day are more than the free places: the strongest over these sessions first.</summary>
|
||||
public int Strength { get; init; } = 63;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>stock_ath_breakout</c> (SPEC 8.4), a candidate: buys the stocks of 8.2 that close at the highest price of their
|
||||
/// history, at the next open, and leaves only through a trailing stop 10 ATR(42) below the highest close. "Ever" is
|
||||
/// the history there is, which for the bot starts in 2016: the strategy needs all of it.
|
||||
/// </summary>
|
||||
public sealed class StockAthBreakout(StockAthBreakoutSettings? settings = null) : IStrategy
|
||||
{
|
||||
private readonly StockAthBreakoutSettings _settings = settings ?? new StockAthBreakoutSettings();
|
||||
private readonly Dictionary<string, HighTracker> _highs = new(StringComparer.Ordinal);
|
||||
|
||||
public string Id => StockAthBreakoutFamily.FamilyId;
|
||||
|
||||
public string Version => StockAthBreakoutFamily.FamilyVersion;
|
||||
|
||||
public StockAthBreakoutSettings Settings => _settings;
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
/// <summary>The universe of 8.2, the one saved for <c>equity_momentum</c>.</summary>
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.Members?.Invoke(EquityMomentumFamily.FamilyId, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize);
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var equity = context.Portfolio.Equity;
|
||||
var intents = new SortedDictionary<string, Intent>(StringComparer.Ordinal);
|
||||
var weights = new List<(BarSeries Bars, double Weight)>();
|
||||
var open = 0;
|
||||
foreach (var (symbol, holding) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).OrderBy(h => h.Key, StringComparer.Ordinal))
|
||||
{
|
||||
open++;
|
||||
var bars = context.Bars(symbol);
|
||||
if (bars.Count > 0 && equity > 0m)
|
||||
{
|
||||
weights.Add((bars, (double)holding.Quantity * bars.Close(bars.Count - 1) / (double)equity));
|
||||
}
|
||||
|
||||
if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop };
|
||||
}
|
||||
}
|
||||
|
||||
var highs = new List<(string Symbol, double Strength, double Atr, double Weight)>();
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
if (Tracker(symbol).IsNewHigh(bars) && bars.Count >= _settings.MinSessions && !context.Portfolio.Holds(symbol)
|
||||
&& Indicators.Atr(bars, _settings.AtrLength) is > 0 and var atr
|
||||
&& Indicators.Volatility(bars, _settings.VolatilityWindow, context.PeriodsPerYear) is > 0 and var volatility)
|
||||
{
|
||||
highs.Add((symbol, Indicators.Momentum(bars, _settings.Strength, 0) ?? 0, atr, Math.Min(_settings.Cap, _settings.StockVolatility / volatility)));
|
||||
}
|
||||
}
|
||||
|
||||
var slots = _settings.MaxPositions - open;
|
||||
if (slots <= 0 || equity <= 0m || highs.Count == 0)
|
||||
{
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
var entries = highs.OrderByDescending(h => h.Strength).ThenBy(h => h.Symbol, StringComparer.Ordinal).Take(slots).ToList();
|
||||
var whole = Indicators.PortfolioVolatility([.. weights, .. entries.Select(e => (context.Bars(e.Symbol), e.Weight))], _settings.VolatilityWindow, context.PeriodsPerYear);
|
||||
var factor = whole is { } w && w > _settings.StrategyVolatility ? _settings.StrategyVolatility / w : 1;
|
||||
var free = 1 - weights.Sum(x => x.Weight);
|
||||
foreach (var (symbol, strength, atr, wanted) in entries)
|
||||
{
|
||||
var weight = Math.Min(wanted * factor, free);
|
||||
if (weight < _settings.Minimum)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
intents[symbol] = new Intent(symbol, Math.Round((decimal)weight, 6, MidpointRounding.ToZero), Reasons.Entry)
|
||||
{
|
||||
StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8),
|
||||
Strength = strength,
|
||||
};
|
||||
free -= weight;
|
||||
}
|
||||
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
private HighTracker Tracker(string symbol)
|
||||
{
|
||||
if (!_highs.TryGetValue(symbol, out var tracker))
|
||||
{
|
||||
_highs[symbol] = tracker = new HighTracker();
|
||||
}
|
||||
|
||||
return tracker;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "ath_entry";
|
||||
public const string StopMoved = "ath_stop";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the highest close before the last bar is, walked one bar at a time. The bar is kept, not its price: adjusted
|
||||
/// prices are anchored to the day they are read on.
|
||||
/// </summary>
|
||||
private sealed class HighTracker
|
||||
{
|
||||
private int _walked;
|
||||
private int _highest = -1;
|
||||
private DateOnly? _first;
|
||||
private DateOnly? _last;
|
||||
|
||||
public bool IsNewHigh(BarSeries bars)
|
||||
{
|
||||
if (bars.Count < _walked || (_walked > 0 && (bars.FirstDay != _first || bars.Day(_walked - 1) != _last)))
|
||||
{
|
||||
_walked = 0;
|
||||
_highest = -1;
|
||||
}
|
||||
|
||||
if (bars.Count < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Every bar but the last: the last is the one that must beat them.
|
||||
for (var i = _walked; i < bars.Count - 1; i++)
|
||||
{
|
||||
if (_highest < 0 || bars.Close(i) > bars.Close(_highest))
|
||||
{
|
||||
_highest = i;
|
||||
}
|
||||
}
|
||||
|
||||
_walked = bars.Count - 1;
|
||||
_first = bars.FirstDay;
|
||||
_last = bars.Day(_walked - 1);
|
||||
return bars.Close(bars.Count - 1) > bars.Close(_highest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class StockAthBreakoutFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "stock_ath_breakout";
|
||||
|
||||
public const string FamilyVersion = "1";
|
||||
|
||||
public static StockAthBreakoutFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => FamilyVersion;
|
||||
|
||||
public string Name => "Nuovi massimi storici sulle azioni USA";
|
||||
|
||||
public string Description =>
|
||||
"Strategia candidata, senza capitale: compra le azioni americane che chiudono al prezzo più alto della loro storia raccolta (dal 2016) e le tiene finché non scendono di 10 volte la loro oscillazione media sotto il massimo. " +
|
||||
"Al massimo 20 titoli.";
|
||||
|
||||
public bool NeedsFullHistory => true;
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("stop_atr", "Stop in ATR sotto il massimo", 10m, [8m, 10m, 12m], 2m, 30m, Whole: true),
|
||||
new("positions", "Numero massimo di titoli", 20m, [15m, 20m, 25m], 3m, 50m, Whole: true),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new StockAthBreakout(new StockAthBreakoutSettings { AtrMultiple = (double)parameters["stop_atr"], MaxPositions = parameters.Whole("positions") });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The stop that follows the highest close since the entry at some ATRs and can only rise.</summary>
|
||||
internal static class Trailing
|
||||
{
|
||||
public static decimal? Stop(StrategyContext context, string symbol, int atrLength, double multiple)
|
||||
{
|
||||
var holding = context.Portfolio.Of(symbol)!;
|
||||
var bars = context.Bars(symbol);
|
||||
if (Indicators.Atr(bars, atrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var candidate = Math.Round((decimal)(high - (multiple * atr)), 8);
|
||||
return candidate <= 0m || (holding.Stop is { } current && candidate <= current) ? null : candidate;
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,8 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
|
||||
var stops = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var symbol in held)
|
||||
{
|
||||
if (TrailingStop(context, symbol) is { } stop)
|
||||
// 3 ATR(20) below the highest close since the entry; it can only rise.
|
||||
if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
|
||||
{
|
||||
stops[symbol] = stop;
|
||||
}
|
||||
@@ -246,25 +247,6 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
|
||||
return raw.ToDictionary(p => p.Key, p => Math.Round((decimal)(p.Value * factor), 6, MidpointRounding.ToZero), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>3 ATR(20) below the highest close since the entry; it can only rise.</summary>
|
||||
private decimal? TrailingStop(StrategyContext context, string symbol)
|
||||
{
|
||||
var holding = context.Portfolio.Of(symbol)!;
|
||||
var bars = context.Bars(symbol);
|
||||
if (Indicators.Atr(bars, _settings.AtrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var candidate = Math.Round((decimal)(high - (_settings.AtrMultiple * atr)), 8);
|
||||
if (candidate <= 0m || (holding.Stop is { } current && candidate <= current))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "momentum_entry";
|
||||
|
||||
@@ -143,11 +143,14 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The strategies the laboratory can test: the three of the bot first, then the examples.</summary>
|
||||
/// <summary>The strategies the laboratory can test: the three of the bot first, then the candidates (SPEC 8.4) and the examples.</summary>
|
||||
public static class StrategyCatalog
|
||||
{
|
||||
public static IReadOnlyList<IStrategyFamily> All { get; } =
|
||||
[CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
||||
[
|
||||
CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, StockAthBreakoutFamily.Instance, CryptoRelativeMomentumFamily.Instance,
|
||||
MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance,
|
||||
];
|
||||
|
||||
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
|
||||
}
|
||||
@@ -326,6 +326,9 @@ public interface IStrategyFamily
|
||||
|
||||
IReadOnlyList<ParameterSpec> Parameters { get; }
|
||||
|
||||
/// <summary>True when a window is not enough: the strategy reads every bar there is, such as an all-time high.</summary>
|
||||
bool NeedsFullHistory => false;
|
||||
|
||||
/// <summary>False for a point of the grid that makes no sense (a short average longer than the long one).</summary>
|
||||
bool Accepts(StrategyParameters parameters) => true;
|
||||
|
||||
|
||||
@@ -21,8 +21,29 @@ public static class StrategyNames
|
||||
(EquityMeanrev, Venues.Alpaca, 0.25m),
|
||||
];
|
||||
|
||||
public const string StockAthBreakout = "stock_ath_breakout";
|
||||
public const string CryptoRelativeMomentum = "crypto_relative_momentum";
|
||||
|
||||
/// <summary>
|
||||
/// The candidates of SPEC 8.4: research and observation only. They have no share, no capital and no order code, so
|
||||
/// they are never among the <see cref="Base"/> ones.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<(string Name, string Broker)> Candidates =
|
||||
[
|
||||
(StockAthBreakout, Venues.Alpaca),
|
||||
(CryptoRelativeMomentum, Venues.Okx),
|
||||
];
|
||||
|
||||
public static bool IsBase(string strategy) => Base.Any(b => b.Name == strategy);
|
||||
|
||||
public static bool IsCandidate(string strategy) => Candidates.Any(c => c.Name == strategy);
|
||||
|
||||
/// <summary>The market of a strategy: crypto on OKX Europe, the others trade US stocks.</summary>
|
||||
public static bool IsCrypto(string strategy) => BrokerOf(strategy) == Venues.Okx;
|
||||
|
||||
public static string BrokerOf(string strategy) =>
|
||||
Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy));
|
||||
Base.FirstOrDefault(b => b.Name == strategy).Broker ?? Candidates.FirstOrDefault(c => c.Name == strategy).Broker
|
||||
?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy));
|
||||
|
||||
/// <summary>The name the user reads (appendix F): short in tables, with the market in legends.</summary>
|
||||
public static string Label(string strategy, bool withMarket = false) => strategy switch
|
||||
@@ -30,6 +51,8 @@ public static class StrategyNames
|
||||
CryptoTrend => "Trend crypto",
|
||||
EquityMomentum => withMarket ? "Momentum azioni" : "Momentum",
|
||||
EquityMeanrev => withMarket ? "Mean reversion azioni" : "Mean reversion",
|
||||
StockAthBreakout => "Nuovi massimi storici sulle azioni USA",
|
||||
CryptoRelativeMomentum => "Momentum relativo tra crypto",
|
||||
_ => strategy,
|
||||
};
|
||||
|
||||
@@ -84,7 +107,8 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
var given = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, amount FROM cash_ledger WHERE kind = @k AND strategy IS NOT NULL",
|
||||
r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false);
|
||||
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return rows.Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency,
|
||||
// A candidate of SPEC 8.4 has no share and no capital: it is no part of any plan.
|
||||
return rows.Where(r => !StrategyNames.IsCandidate(r.Strategy)).Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency,
|
||||
r.Share ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Strategy).Share,
|
||||
given.Where(g => g.Account == r.Account && g.Strategy == r.Strategy).Sum(g => g.Amount),
|
||||
equities.Where(e => e.AccountId == r.Account && e.Strategy == r.Strategy).Sum(e => e.Cash))).ToList();
|
||||
@@ -134,6 +158,11 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
public async Task SetSharesAsync(string broker, IReadOnlyDictionary<string, decimal> shares, string changedBy, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(shares);
|
||||
if (shares.Keys.Any(StrategyNames.IsCandidate))
|
||||
{
|
||||
throw new CapitalException("Una strategia candidata non riceve capitale.");
|
||||
}
|
||||
|
||||
if (shares.Values.Any(v => v is < 0m or > 1m) || shares.Values.Sum() != 1m)
|
||||
{
|
||||
throw new CapitalException("Le quote vanno da 0 a 100% e insieme fanno 100%.");
|
||||
|
||||
@@ -143,6 +143,10 @@ public static class DiaryText
|
||||
public static string NoData(string strategy, string what) =>
|
||||
$"{StrategyNames.Label(strategy, withMarket: true)}: nessuna decisione oggi. Mancano {what}: non apro nuove posizioni.";
|
||||
|
||||
/// <summary>A candidate (SPEC 8.4) found in a stage that trades: nothing in the program puts it there.</summary>
|
||||
public static string CandidateStage(string strategy) =>
|
||||
$"{StrategyNames.Label(strategy, withMarket: true)} è una strategia candidata ma nel database risulta fuori dall'osservazione: non la faccio decidere.";
|
||||
|
||||
/// <summary>A missed job done at the restart (SPEC 5.6).</summary>
|
||||
public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) =>
|
||||
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
|
||||
|
||||
@@ -119,6 +119,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
/// </summary>
|
||||
public static readonly TimeSpan LateDataWait = TimeSpan.FromMinutes(30);
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly HashSet<string> _candidatesRefused = new(StringComparer.Ordinal);
|
||||
|
||||
public LiveEngine(Database db, IClock clock, Ledger ledger, StageBook stages, Func<Guid, OrderManager?> managers, Func<string, CancellationToken, Task<Quote?>> quotes,
|
||||
IMarketCalendar? calendar = null, LiveEngineOptions? options = null, ILogger? logger = null)
|
||||
@@ -216,6 +217,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
|
||||
await ReleaseAsync(now, cancellationToken).ConfigureAwait(false);
|
||||
await CandidatesAsync(now, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -234,14 +236,74 @@ public sealed partial class LiveEngine : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
await DecideAsync(CryptoMoment(StrategyNames.CryptoTrend, today, due, now), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private Moment CryptoMoment(string strategy, DateOnly today, DateTimeOffset due, DateTimeOffset now)
|
||||
{
|
||||
var deadline = At(today, Options.CryptoDeadline);
|
||||
var day = today.AddDays(-1);
|
||||
|
||||
// The orders go at once. A decision made long after 00:05 (the bot was off) keeps 00:05 as its time, so its
|
||||
// entries are checked against the price they were decided on (SPEC 5.6); waiting for the bars is not an absence.
|
||||
var ordersDue = now - due > Options.RecoveredAfter ? due : now;
|
||||
await DecideAsync(new Moment(StrategyNames.CryptoTrend, day, Key(StrategyNames.CryptoTrend, day), due, now > deadline, deadline, now, ordersDue, deadline), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new Moment(strategy, day, Key(strategy, day), due, now > deadline, deadline, now, ordersDue, deadline);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The candidates of SPEC 8.4, after everything that can trade: they only note their signals, and one that fails
|
||||
/// is said and changes nothing for the others.
|
||||
/// </summary>
|
||||
private async Task CandidatesAsync(DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var (strategy, _) in StrategyNames.Candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (CandidateMoment(strategy, now) is not { } moment || await RunExistsAsync(moment.Key, cancellationToken).ConfigureAwait(false)
|
||||
|| await _stages.GetAsync(strategy, cancellationToken).ConfigureAwait(false) is not { } stage || StageBook.IsArchived(stage))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stage.Stage != StrategyStages.Observation)
|
||||
{
|
||||
// Nothing in the program puts a candidate there: whoever did, it does not trade.
|
||||
if (_candidatesRefused.Add(strategy))
|
||||
{
|
||||
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "candidate_stage", DiaryText.CandidateStage(strategy), null, cancellationToken),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
await DecideAsync(moment, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogCandidateFailed(_logger, ex, strategy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Moment? CandidateMoment(string strategy, DateTimeOffset now)
|
||||
{
|
||||
if (StrategyNames.IsCrypto(strategy))
|
||||
{
|
||||
var today = DateOnly.FromDateTime(now.UtcDateTime);
|
||||
var due = At(today, Options.CryptoDecision);
|
||||
return now < due ? null : CryptoMoment(strategy, today, due, now);
|
||||
}
|
||||
|
||||
if (_calendar is null || LastClosed(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, NewYork).DateTime), now) is not { } last
|
||||
|| now < last.CloseUtc + Options.SignalsAfterClose || NextSession(last.Date) is not { } next)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, now >= next.OpenUtc, next.OpenUtc, now,
|
||||
next.OpenUtc + Options.OrdersAfterOpen, next.CloseUtc);
|
||||
}
|
||||
|
||||
private static DateTimeOffset At(DateOnly day, TimeOnly time) => new(day.ToDateTime(time), TimeSpan.Zero);
|
||||
@@ -463,6 +525,11 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
|
||||
var observation = stage.Stage == StrategyStages.Observation;
|
||||
if (!observation && StrategyNames.IsCandidate(m.Strategy))
|
||||
{
|
||||
return; // Never an order for a candidate, whatever its row says (SPEC 8.4).
|
||||
}
|
||||
|
||||
var accountId = observation ? stage.AccountId : stage.OrdersAccount;
|
||||
if (accountId is not { } account)
|
||||
{
|
||||
@@ -536,7 +603,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyDictionary<string, DateOnly>?> EarningsOfAsync(Moment m, CancellationToken cancellationToken) =>
|
||||
Earnings is null || m.Strategy == StrategyNames.CryptoTrend ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next;
|
||||
Earnings is null || StrategyNames.IsCrypto(m.Strategy) ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next;
|
||||
|
||||
private DateTimeOffset LateSince(string key, DateTimeOffset now)
|
||||
{
|
||||
@@ -571,7 +638,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
/// <summary>The earnings calendar as the decision of <paramref name="day"/> reads it (SPEC 10.5, fourth row; 8.3).</summary>
|
||||
private async Task<BacktestOptions> WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Earnings is null || strategy == StrategyNames.CryptoTrend || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
|
||||
if (Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
|
||||
{
|
||||
return options;
|
||||
}
|
||||
@@ -614,8 +681,13 @@ public sealed partial class LiveEngine : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
var what = m.Strategy == StrategyNames.CryptoTrend ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni";
|
||||
var what = StrategyNames.IsCrypto(m.Strategy) ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni";
|
||||
var text = DiaryText.NoData(m.Strategy, what);
|
||||
if (StrategyNames.IsCandidate(m.Strategy))
|
||||
{
|
||||
return; // The strategies of its market already say it.
|
||||
}
|
||||
|
||||
if (observation)
|
||||
{
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.MissingBars, text, null, cancellationToken).ConfigureAwait(false);
|
||||
@@ -905,8 +977,12 @@ public sealed partial class LiveEngine : IDisposable
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary),
|
||||
new { decision = decisionId }, cancellationToken).ConfigureAwait(false);
|
||||
if (plan.Summary.HasChanges || !StrategyNames.IsCandidate(m.Strategy))
|
||||
{
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary),
|
||||
new { decision = decisionId }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -952,7 +1028,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
var summary = m.Strategy == StrategyNames.CryptoTrend ? DiaryText.CryptoClose(plan.Summary) : DiaryText.StockSignals(plan.Summary);
|
||||
var summary = StrategyNames.IsCrypto(m.Strategy) ? DiaryText.CryptoClose(plan.Summary) : DiaryText.StockSignals(plan.Summary);
|
||||
if (mode == DecisionModes.ExitsOnly && plan.Notes.Any(n => n.Reason == LiveReasons.LateExitsOnly))
|
||||
{
|
||||
summary += " " + ReasonCatalog.Text(LiveReasons.LateExitsOnly);
|
||||
@@ -961,7 +1037,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
if (m.Now - m.Due > Options.RecoveredAfter)
|
||||
{
|
||||
// Made late because the bot was off (SPEC 5.6): said before what was decided.
|
||||
var what = m.Strategy == StrategyNames.CryptoTrend ? "la chiusura giornaliera crypto" : "il calcolo dei segnali sulle azioni";
|
||||
var what = StrategyNames.IsCrypto(m.Strategy) ? "la chiusura giornaliera crypto" : "il calcolo dei segnali sulle azioni";
|
||||
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.Recovered, DiaryText.Recovered(what, m.Due, Zone), new { decision = decisionId },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -1352,7 +1428,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
private DateOnly? LastClosed(string strategy)
|
||||
{
|
||||
var now = _clock.UtcNow;
|
||||
if (strategy == StrategyNames.CryptoTrend)
|
||||
if (StrategyNames.IsCrypto(strategy))
|
||||
{
|
||||
return DateOnly.FromDateTime(now.UtcDateTime).AddDays(-1);
|
||||
}
|
||||
@@ -1364,7 +1440,7 @@ public sealed partial class LiveEngine : IDisposable
|
||||
private async Task<Loaded> LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken, IReadOnlyList<string>? extra = null,
|
||||
DateOnly? since = null)
|
||||
{
|
||||
var crypto = strategy == StrategyNames.CryptoTrend;
|
||||
var crypto = StrategyNames.IsCrypto(strategy);
|
||||
var venue = crypto ? Venues.Okx : Venues.Alpaca;
|
||||
var members = await _universes.AsOfAsync(crypto ? Universes.Crypto : Universes.Equity, day, cancellationToken).ConfigureAwait(false);
|
||||
var symbols = new SortedSet<string>(members.Select(m => m.Symbol), StringComparer.Ordinal);
|
||||
@@ -1383,8 +1459,8 @@ public sealed partial class LiveEngine : IDisposable
|
||||
}
|
||||
|
||||
// The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The
|
||||
// stock strategies read windows: the warm-up of a trial is enough.
|
||||
var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
|
||||
// stock strategies read windows: the warm-up of a trial is enough, unless the strategy says it needs everything.
|
||||
var from = crypto || StrategyCatalog.Find(strategy) is { NeedsFullHistory: true } ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
|
||||
from = since < from ? since.Value : from;
|
||||
var instruments = new List<BacktestInstrument>();
|
||||
var missing = new HashSet<string>(StringComparer.Ordinal);
|
||||
@@ -1490,6 +1566,9 @@ public sealed partial class LiveEngine : IDisposable
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Asking for the missing bars failed")]
|
||||
private static partial void LogDataRequestFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "The candidate strategy {Strategy} could not decide")]
|
||||
private static partial void LogCandidateFailed(ILogger logger, Exception exception, string strategy);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Planned order {Id} could not be released")]
|
||||
private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ public static class ReasonCatalog
|
||||
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
|
||||
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
|
||||
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
|
||||
["ath_entry"] = "Aveva chiuso al prezzo più alto della sua storia raccolta.",
|
||||
["ath_stop"] = "Lo stop di protezione è salito con il prezzo.",
|
||||
["relative_entry"] = "Era tra le crypto salite di più nell'ultimo mese, con Bitcoin in tendenza.",
|
||||
["relative_exit_rank"] = "Non era più tra le crypto più forti.",
|
||||
["relative_exit_market"] = "Bitcoin è sceso sotto la sua media a 200 giorni.",
|
||||
["relative_stop"] = "Lo stop di protezione è salito con il prezzo.",
|
||||
// Exits recorded on the trade.
|
||||
["stop"] = "Stop di protezione raggiunto.",
|
||||
["exit"] = "Uscita decisa dalla strategia.",
|
||||
|
||||
@@ -248,18 +248,37 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
|
||||
return;
|
||||
}
|
||||
|
||||
if (qualification.Passed)
|
||||
// A candidate (SPEC 8.4) has no capital and no order code: whatever its outcome, it stays in observation.
|
||||
if (qualification.Passed && !StrategyNames.IsCandidate(strategy))
|
||||
{
|
||||
await MoveCoreAsync(s, strategy, current.Stage, StrategyStages.Simulation, "backtest_passed", "primo avvio", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE strategy_state SET stage_reason = @r, stage_since = COALESCE(stage_since, @t), updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||
("r", "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
|
||||
("r", qualification.Passed ? "candidate" : "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A candidate the protocol turned down on its data (SPEC 12.3): kept as documentation, it decides no more. One that
|
||||
/// waits for its data has no plan yet. "Archived" is not a stage: it is read from the outcome.
|
||||
/// </summary>
|
||||
public static bool IsArchived(StrategyStage stage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stage);
|
||||
return StrategyNames.IsCandidate(stage.Strategy) && stage.Qualification is { Passed: false, PlanHash: not null };
|
||||
}
|
||||
|
||||
private static void RefuseCandidate(string strategy)
|
||||
{
|
||||
if (StrategyNames.IsCandidate(strategy))
|
||||
{
|
||||
throw new LiveConfirmationException("candidate", "È una strategia candidata: raccoglie solo segnali e non riceve capitale.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a strategy between observation and simulation (the user's choice from the interface). Real money is
|
||||
/// never reached this way: only <see cref="ConfirmLiveAsync"/> does it.
|
||||
@@ -271,6 +290,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
|
||||
throw new LiveConfirmationException("procedure", "Per i soldi veri serve la procedura di conferma.");
|
||||
}
|
||||
|
||||
RefuseCandidate(strategy);
|
||||
var current = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy));
|
||||
if (StrategyStages.IsLive(current.Stage))
|
||||
{
|
||||
@@ -360,6 +380,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
|
||||
public async Task ConfirmLiveAsync(LiveConfirmation c, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(c);
|
||||
RefuseCandidate(c.Strategy);
|
||||
if (!consent.AllowLive)
|
||||
{
|
||||
throw new LiveConfirmationException(RiskReasons.NoConsent,
|
||||
|
||||
@@ -129,6 +129,15 @@ public static class AccountSetup
|
||||
}
|
||||
}
|
||||
|
||||
// The candidates of SPEC 8.4 only note their signals: in observation, with no capital and no share.
|
||||
foreach (var (strategy, broker) in StrategyNames.Candidates)
|
||||
{
|
||||
var target = accounts.First(a => a.Broker == broker && a.Environment == TradingEnvironments.Simulation).AccountId;
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) " +
|
||||
"VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 0) ON CONFLICT (strategy) DO NOTHING", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", StrategyNames.Observation), ("j", new DbJson("{}")), ("now", now)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -569,7 +578,7 @@ public sealed partial class TradingService : IDisposable
|
||||
/// </summary>
|
||||
public async Task LoadOutcomesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var (strategy, _, _) in StrategyNames.Base)
|
||||
foreach (var strategy in StrategyNames.Base.Select(b => b.Name).Concat(StrategyNames.Candidates.Select(c => c.Name)))
|
||||
{
|
||||
if (Backtest.BacktestOutcomes.Find(strategy) is { } outcome)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The candidates of SPEC 8.4 (issue #74): their rules, their protocol, and that they never trade.</summary>
|
||||
[TestClass]
|
||||
public sealed class CandidateTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly DateOnly Monday = new(2022, 1, 3);
|
||||
private static readonly DateOnly LiveFrom = new(2026, 9, 1);
|
||||
|
||||
private static string[] Names => [.. StrategyNames.Candidates.Select(c => c.Name)];
|
||||
|
||||
private static BacktestDataset Coins(int days, double btcDrift, ulong seed = 40) =>
|
||||
StrategyData.Crypto([.. new[] { "BTC", "ETH", "SOL", "XRP", "ADA", "LTC" }.Select((c, i) =>
|
||||
(c, (IReadOnlyList<DailyBar>)[.. BacktestData.Walk(days, seed + (ulong)i, start: 100, drift: i == 0 ? btcDrift : 0.0006 * (i - 1), volatility: 0.03).Select(b => b with { Volume = 1_000_000 })]))]);
|
||||
|
||||
private static BacktestDataset Stocks(int sessions, ulong seed = 300, int count = 25) =>
|
||||
new([.. Enumerable.Range(0, count).Select(k => new BacktestInstrument(StrategyData.Share("S" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
|
||||
StrategyData.OnBusinessDays([.. BacktestData.Walk(sessions, seed + (ulong)k, start: 50 + k, drift: 0.0004 * (k % 5), volatility: 0.015).Select(b => b with { Volume = 100_000 })], Monday)))], "USD");
|
||||
|
||||
// ---- crypto_relative_momentum ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCryptoCandidateBuysTheStrongestOnSundaysOnlyWhileBitcoinRises()
|
||||
{
|
||||
var run = BacktestEngine.Run(new CryptoRelativeMomentum(), Coins(900, 0.002));
|
||||
var entries = run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == CryptoRelativeMomentum.Reasons.Entry).Select(i => (d.Day, Intent: i))).ToList();
|
||||
Assert.IsNotEmpty(entries);
|
||||
Assert.IsTrue(entries.All(e => e.Day.DayOfWeek == DayOfWeek.Sunday), "the review is on the Sunday close");
|
||||
Assert.IsTrue(entries.All(e => e.Intent.TargetWeight <= 1m / 3m && e.Intent.StopOffset > 0m && e.Intent.Strength > 0));
|
||||
Assert.IsTrue(run.Fills.Where(f => f.Side == OrderSide.Buy).All(f => f.Day.DayOfWeek == DayOfWeek.Monday), "bought at the open of Monday");
|
||||
|
||||
// Never more than three coins at once.
|
||||
var held = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var day in run.Fills.GroupBy(f => f.Day))
|
||||
{
|
||||
foreach (var fill in day)
|
||||
{
|
||||
// A sale leaves a residue of the fee, which the engine writes off: it is no position.
|
||||
held[fill.Symbol] = fill.Side == OrderSide.Buy ? held.GetValueOrDefault(fill.Symbol) + fill.Quantity : 0m;
|
||||
}
|
||||
|
||||
Assert.IsLessThanOrEqualTo(3, held.Count(h => h.Value > 0m));
|
||||
}
|
||||
|
||||
// Bitcoin up and down: an entry only on the days it closes above its average.
|
||||
var mixed = Coins(1200, 0, seed: 90);
|
||||
var bought = BacktestEngine.Run(new CryptoRelativeMomentum(), mixed).Decisions.Where(d => d.Proposed.Any(i => i.Reason == CryptoRelativeMomentum.Reasons.Entry)).ToList();
|
||||
var sundays = mixed.Sessions.Where(d => d.DayOfWeek == DayOfWeek.Sunday && d > mixed.Sessions[450]).ToList();
|
||||
bool Up(DateOnly day) => mixed["BTC-EUR"]!.SeriesThrough(day) is { } s && s.Close(s.Count - 1) > Indicators.Sma(s, 200);
|
||||
Assert.IsTrue(bought.All(d => Up(d.Day)) && bought.Count > 0 && sundays.Any(d => !Up(d)), "the path must have both");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCryptoCandidateLeavesEverythingWhenBitcoinFallsBelowItsAverage()
|
||||
{
|
||||
var data = Coins(900, -0.003);
|
||||
var day = data.Sessions[^1];
|
||||
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["ETH-EUR"] = new(1m, 100m, null, day.AddDays(-3)) });
|
||||
var intent = BacktestEngine.DecideOnce(new CryptoRelativeMomentum(), data, state, day).Proposed.Single();
|
||||
Assert.AreEqual(("ETH-EUR", 0m, CryptoRelativeMomentum.Reasons.ExitMarket), (intent.Symbol, intent.TargetWeight!.Value, intent.Reason));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCryptoCandidateRanksTheUniverseChosenForTheTrend()
|
||||
{
|
||||
var asked = new List<string>();
|
||||
var context = new UniverseContext(new DateOnly(2026, 5, 20), ["BTC-EUR"])
|
||||
{
|
||||
Members = (strategy, day) =>
|
||||
{
|
||||
asked.Add(strategy + " " + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
|
||||
return ["BTC-EUR", "ETH-EUR"];
|
||||
},
|
||||
};
|
||||
CollectionAssert.AreEqual(new[] { "BTC-EUR", "ETH-EUR" }, new CryptoRelativeMomentum().Universe(context).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "crypto_trend 2026-05-01" }, asked);
|
||||
}
|
||||
|
||||
// ---- stock_ath_breakout ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheStockCandidateBuysOnlyTheHighestCloseOfTheWholeHistory()
|
||||
{
|
||||
// A high of 120, a long fall, and a close at 115 that beats everything of the last 400 sessions but not the old high.
|
||||
var closes = Enumerable.Range(0, 100).Select(i => 100 + (0.2 * i)).Concat(Enumerable.Range(0, 400).Select(i => 80 + (0.05 * i))).Append(115d).ToList();
|
||||
var bars = StrategyData.OnBusinessDays(StrategyData.FromCloses(closes, range: 1, volume: 100_000), Monday);
|
||||
var context = new Func<List<DailyBar>, IReadOnlyList<Intent>>(b =>
|
||||
{
|
||||
var data = new BacktestDataset([new BacktestInstrument(StrategyData.Share("AAA"), b)], "USD");
|
||||
return BacktestEngine.DecideOnce(new StockAthBreakout(), data, new PortfolioState(10_000m, new Dictionary<string, Holding>()), data.Sessions[^1]).Proposed;
|
||||
});
|
||||
Assert.IsEmpty(context(bars), "115 is the highest of 400 sessions, not of all of them");
|
||||
Assert.AreEqual(StockAthBreakout.Reasons.Entry, context([.. bars.Skip(100)]).Single().Reason, "with a short history the same close would look like a record");
|
||||
|
||||
var record = context([.. bars.Take(500), bars[^1] with { Close = 121, High = 122 }]).Single();
|
||||
Assert.IsTrue(record.TargetWeight is > 0m and <= 0.10m);
|
||||
Assert.IsGreaterThan(0m, record.StopOffset!.Value);
|
||||
Assert.IsTrue(StockAthBreakoutFamily.Instance.NeedsFullHistory);
|
||||
Assert.AreEqual(new DateOnly(2009, 1, 1), new TrialData(TrialSources.Database, Venues.Alpaca, ["AAA"], Monday, Monday.AddDays(30)) { FullHistory = true }.HistoryStart());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ThePlansAlreadyWrittenKeepTheirFingerprint()
|
||||
{
|
||||
var data = new TrialData(TrialSources.Research, EuroHistory.Venue, ["BTCEUR"], Monday, Monday.AddDays(30));
|
||||
var plain = System.Text.Json.JsonSerializer.Serialize(data, TrialPlan.Json);
|
||||
Assert.IsFalse(plain.Contains("full_history", StringComparison.Ordinal), plain);
|
||||
StringAssert.Contains(System.Text.Json.JsonSerializer.Serialize(data with { FullHistory = true }, TrialPlan.Json), "\"full_history\":true");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheStockCandidateKeepsToItsPlacesItsCapitalAndAStopThatOnlyRises()
|
||||
{
|
||||
var strategy = new StockAthBreakout(new StockAthBreakoutSettings { MaxPositions = 6 });
|
||||
var run = BacktestEngine.Run(strategy, Stocks(700));
|
||||
Assert.IsTrue(run.Fills.Any(f => f.Side == OrderSide.Buy));
|
||||
var held = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var fill in run.Fills)
|
||||
{
|
||||
held[fill.Symbol] = held.GetValueOrDefault(fill.Symbol) + (fill.Side == OrderSide.Buy ? fill.Quantity : -fill.Quantity);
|
||||
Assert.IsLessThanOrEqualTo(6, held.Count(h => h.Value > 0.0001m));
|
||||
}
|
||||
|
||||
Assert.IsTrue(run.Fills.Where(f => f.Side == OrderSide.Sell).All(f => f.Reason is not StockAthBreakout.Reasons.Entry), "it leaves only through the stop");
|
||||
foreach (var group in run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == StockAthBreakout.Reasons.StopMoved).Select(i => (d.Day, i.Symbol, Stop: i.Stop!.Value))).GroupBy(s => s.Symbol))
|
||||
{
|
||||
var list = group.OrderBy(s => s.Day).ToList();
|
||||
for (var i = 1; i < list.Count; i++)
|
||||
{
|
||||
var exited = run.Fills.Any(f => f.Symbol == group.Key && f.Side == OrderSide.Sell && f.Day > list[i - 1].Day && f.Day <= list[i].Day);
|
||||
Assert.IsTrue(exited || list[i].Stop > list[i - 1].Stop, $"{list[i - 1]} → {list[i]}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void NeitherCandidateLooksAhead()
|
||||
{
|
||||
var crypto = LookAheadCheck.Run(_ => new CryptoRelativeMomentum(), Coins(900, 0.002));
|
||||
Assert.IsTrue(crypto.Passed, string.Join("\n", crypto.Mismatches.Take(3)));
|
||||
var stock = LookAheadCheck.Run(_ => new StockAthBreakout(), Stocks(700));
|
||||
Assert.IsTrue(stock.Passed, string.Join("\n", stock.Mismatches.Take(3)));
|
||||
}
|
||||
|
||||
// ---- The protocol and its files ----
|
||||
|
||||
[TestMethod]
|
||||
public void EveryCandidateHasItsOutcomeAndNoneHasAWayToTrade()
|
||||
{
|
||||
CollectionAssert.AreEqual(new[] { "crypto_trend", "equity_momentum", "equity_meanrev" }, StrategyNames.Base.Select(b => b.Name).ToArray());
|
||||
foreach (var name in Names)
|
||||
{
|
||||
var outcome = BacktestOutcomes.Find(name);
|
||||
Assert.IsNotNull(outcome, name);
|
||||
Assert.AreEqual("docs/backtests/" + name + ".md", outcome.Report);
|
||||
Assert.IsNotNull(StrategyCatalog.Find(name));
|
||||
Assert.IsFalse(ClientOrderIds.StrategyCodes.ContainsKey(name), "without an order code the order manager refuses it");
|
||||
Assert.IsNull(StrategyPipeline.DefaultShare(name));
|
||||
Assert.IsNotNull(StrategyPipeline.ResearchShare(name), "its trials keep the risk limits");
|
||||
Assert.AreNotEqual(name, StrategyNames.Label(name));
|
||||
}
|
||||
|
||||
var crypto = BacktestOutcomes.Find(StrategyNames.CryptoRelativeMomentum)!;
|
||||
Assert.IsNotNull(crypto.PlanHash, "it was run");
|
||||
StringAssert.Contains(crypto.Verdict, crypto.Passed ? "Protocollo superato" : "Scartata nei test");
|
||||
Assert.IsNull(BacktestOutcomes.Find(StrategyNames.StockAthBreakout)!.PlanHash, "it waits for the Alpaca history");
|
||||
Assert.ThrowsExactly<ArgumentException>(() => ClientOrderIds.Build("ABCD", TradingEnvironments.Simulation, StrategyNames.CryptoRelativeMomentum, OrderPurpose.Entry, "ABCDEFGH", 0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheProtocolOfTheCandidateIsWrittenAsTheOthersAndLeavesTheirFilesAlone()
|
||||
{
|
||||
var folder = TempFolder.Create("candidate");
|
||||
try
|
||||
{
|
||||
var store = new ResearchStore(Path.Combine(folder, "research"));
|
||||
Directory.CreateDirectory(Path.Combine(folder, "research"));
|
||||
var random = new Random(5);
|
||||
var from = new DateOnly(2017, 8, 1);
|
||||
var to = new DateOnly(2020, 12, 31);
|
||||
foreach (var coin in new[] { "BTC", "ETH", "XRP", "LTC", "ADA" })
|
||||
{
|
||||
var price = 100d;
|
||||
await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, Enumerable.Range(0, to.DayNumber - from.DayNumber + 1).Select(i =>
|
||||
{
|
||||
price *= 1 + 0.0005 + ((random.NextDouble() - 0.5) * 0.06);
|
||||
var p = Math.Round((decimal)price, 6);
|
||||
return new ResearchBar(new DateTimeOffset(from.AddDays(i).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), p, p * 1.01m, p * 0.99m, p, 1_000_000m) { QuoteVolume = p * 1_000_000m };
|
||||
}).ToList(), _none);
|
||||
}
|
||||
|
||||
var outcome = await CandidateProtocol.RunCryptoAsync(Path.Combine(folder, "research"), to, new DateTimeOffset(2021, 1, 2, 0, 0, 0, TimeSpan.Zero), null, _none);
|
||||
Assert.HasCount(1, outcome.Runs, "a choice of three coins among three would say nothing");
|
||||
Assert.HasCount(9, outcome.Runs[0].Report.Variants);
|
||||
CollectionAssert.AreEqual(new[] { 1m, 2m, 3m }, outcome.Runs[0].Report.Costs.Select(c => c.Multiplier).ToArray());
|
||||
Assert.IsTrue(outcome.Runs[0].Report.LookAhead.Passed);
|
||||
Assert.AreEqual(outcome.Runs[0].Report.Passed, outcome.Qualification.Passed);
|
||||
Assert.IsNotNull(outcome.Qualification.PlanHash);
|
||||
StringAssert.Contains(ProtocolReport.Markdown(outcome, "crypto_relative_momentum", ["prova"], "anubis backtest candidates"), "Una candidata non opera");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- No capital, no order, no stage ----
|
||||
|
||||
private static StageBook Stages(TradingRig rig) => new(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACandidateWithAnOutcomeThatPassedStaysInObservationAndNobodyCanMoveIt()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
|
||||
await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
|
||||
var stages = Stages(rig);
|
||||
var passed = new Qualification { Passed = true, Verdict = "ok", Report = "r", PlanHash = "h" };
|
||||
foreach (var name in Names)
|
||||
{
|
||||
await stages.ApplyQualificationAsync(name, passed, _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromDays(200));
|
||||
var stage = (await stages.GetAsync(name, _none).ConfigureAwait(false))!;
|
||||
Assert.AreEqual((StrategyStages.Observation, 0m, 0m), (stage.Stage, stage.Capital, stage.Share));
|
||||
Assert.IsFalse(StageBook.IsArchived(stage));
|
||||
Assert.AreEqual("candidate", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => stages.MoveAsync(name, StrategyStages.Simulation, "x", "utente", _none))).Code);
|
||||
Assert.AreEqual("candidate", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() =>
|
||||
stages.ConfirmLiveAsync(new LiveConfirmation(name, Guid.NewGuid(), "", "", null, "utente"), _none))).Code);
|
||||
await stages.ApplyQualificationAsync(name, passed with { Passed = false }, _none).ConfigureAwait(false);
|
||||
Assert.IsTrue(StageBook.IsArchived((await stages.GetAsync(name, _none).ConfigureAwait(false))!), "turned down on its data: archived");
|
||||
await stages.ApplyQualificationAsync(name, passed with { Passed = false, PlanHash = null }, _none).ConfigureAwait(false);
|
||||
Assert.IsFalse(StageBook.IsArchived((await stages.GetAsync(name, _none).ConfigureAwait(false))!), "waiting for its data is not turned down");
|
||||
}
|
||||
|
||||
var crypto = (await stages.GetAsync(StrategyNames.CryptoTrend, _none).ConfigureAwait(false))! with { Qualification = passed with { Passed = false } };
|
||||
Assert.IsFalse(StageBook.IsArchived(crypto), "only a candidate is archived");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCandidatesAreNoPartOfTheCapitalPlan()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
|
||||
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, new FxStore(rig.Db, rig.Clock));
|
||||
await capital.SetAsync(Venues.Okx, 4_000m, "test", _none).ConfigureAwait(false);
|
||||
var strategies = await capital.StrategiesAsync(Venues.Okx, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual((StrategyNames.CryptoTrend, 4_000m), (strategies.Single().Strategy, strategies.Single().Capital));
|
||||
Assert.AreEqual(0m, (await Stages(rig).GetAsync(StrategyNames.CryptoRelativeMomentum, _none).ConfigureAwait(false))!.Capital);
|
||||
await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetSharesAsync(Venues.Okx,
|
||||
new Dictionary<string, decimal> { [StrategyNames.CryptoTrend] = 0.5m, [StrategyNames.CryptoRelativeMomentum] = 0.5m }, "test", _none)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static Task<int> AddAsync(TradingRig rig, string strategy, Guid account, string stage, Qualification? outcome = null) =>
|
||||
rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since, qualification) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 0, @now, @q)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account), ("st", stage), ("j", new DbJson("{}")), ("now", rig.Clock.UtcNow),
|
||||
("q", outcome is null ? null : new DbJson(System.Text.Json.JsonSerializer.Serialize(outcome, Qualification.Json)))), _none);
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLiveCandidateNotesItsSignalsAndSendsNothing()
|
||||
{
|
||||
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(20), stage: StrategyStages.Observation).ConfigureAwait(false);
|
||||
await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation).ConfigureAwait(false);
|
||||
for (var day = LiveFrom; day <= LiveFrom.AddDays(20); day = day.AddDays(1))
|
||||
{
|
||||
await live.DayAsync(day, morning: 3).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var runs = await live.Rig.QueryAsync("SELECT mode, state FROM engine_runs WHERE strategy = @s", r => (Mode: r.Text("mode"), State: r.TextOrNull("state")),
|
||||
("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
|
||||
Assert.HasCount(21, runs);
|
||||
Assert.IsTrue(runs.All(r => r.Mode == DecisionModes.Observation && r.State is null));
|
||||
Assert.IsEmpty(live.Sent);
|
||||
foreach (var table in new[] { "planned_orders", "orders", "fills", "executions" })
|
||||
{
|
||||
Assert.AreEqual(0, (await live.Rig.QueryAsync("SELECT COUNT(*) AS n FROM " + table, r => r.Number("n")).ConfigureAwait(false)).Single(), table);
|
||||
}
|
||||
|
||||
var examples = await live.Rig.QueryAsync("SELECT symbol FROM ml_features WHERE strategy = @s", r => r.Text("symbol"), ("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
|
||||
Assert.IsNotEmpty(examples, "its signals are examples too (SPEC 11.2)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACandidateOutOfObservationInTheDatabaseDecidesNothingAndItIsSaidOnce()
|
||||
{
|
||||
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(3)).ConfigureAwait(false);
|
||||
await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Simulation).ConfigureAwait(false);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
await live.DayAsync(LiveFrom.AddDays(i), morning: 3).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var runs = await live.Rig.QueryAsync("SELECT strategy FROM engine_runs", r => r.Text("strategy")).ConfigureAwait(false);
|
||||
Assert.HasCount(3, runs);
|
||||
Assert.IsTrue(runs.All(r => r == StrategyNames.CryptoTrend));
|
||||
Assert.HasCount(1, await live.Rig.QueryAsync("SELECT id FROM journal WHERE code = 'candidate_stage'", r => r.Id("id")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnArchivedCandidateDecidesNoMoreAndAWaitingOneDoes()
|
||||
{
|
||||
foreach (var (plan, expected) in new[] { ("h", 0), (null, 2) })
|
||||
{
|
||||
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(2)).ConfigureAwait(false);
|
||||
await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation,
|
||||
new Qualification { Passed = false, Verdict = "v", Report = "r", PlanHash = plan }).ConfigureAwait(false);
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
await live.DayAsync(LiveFrom.AddDays(i), morning: 3).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var runs = await live.Rig.QueryAsync("SELECT id FROM engine_runs WHERE strategy = @s", r => r.Id("id"), ("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
|
||||
Assert.HasCount(expected, runs, plan ?? "waiting");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACandidateThatFailsStopsNobody()
|
||||
{
|
||||
await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(2)).ConfigureAwait(false);
|
||||
|
||||
// Its account does not exist any more and its outcome is not an outcome: reading its row throws.
|
||||
await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation).ConfigureAwait(false);
|
||||
await live.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q WHERE strategy = @s", _none, ("q", new DbJson("[]")), ("s", StrategyNames.CryptoRelativeMomentum)), _none)
|
||||
.ConfigureAwait(false);
|
||||
await live.DayAsync(LiveFrom, morning: 3).ConfigureAwait(false);
|
||||
Assert.AreEqual(0, live.Failures);
|
||||
Assert.HasCount(1, await live.Rig.QueryAsync("SELECT id FROM engine_runs WHERE strategy = @s", r => r.Id("id"), ("s", StrategyNames.CryptoTrend)).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStockCandidateLooksAtStocksWithTheirWholeHistory()
|
||||
{
|
||||
var last = LiveFrom.AddDays(8);
|
||||
await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
|
||||
await AddAsync(live.Rig, StrategyNames.StockAthBreakout, live.Alpaca.AccountId, StrategyStages.Observation).ConfigureAwait(false);
|
||||
|
||||
// A close above all the others, older than the 450 days the stock strategies read.
|
||||
var bars = await live.Rig.QueryAsync("SELECT MIN(day) AS d FROM bars_1d", r => r.Text("d")).ConfigureAwait(false);
|
||||
Assert.IsLessThan(LiveFrom.AddDays(-450), BarStore.ParseDay(bars.Single()));
|
||||
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
|
||||
{
|
||||
await live.SessionAsync(day).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var decisions = await live.Rig.QueryAsync("SELECT symbol, data FROM decisions WHERE strategy = @s AND stage = 'strategy'", r => r.Text("symbol"), ("s", StrategyNames.StockAthBreakout))
|
||||
.ConfigureAwait(false);
|
||||
Assert.IsFalse(decisions.Contains(StrategyNames.MarketSymbol), "SPY is data");
|
||||
Assert.IsGreaterThan(0, await CountAsync(live.Rig, StrategyNames.StockAthBreakout).ConfigureAwait(false));
|
||||
Assert.AreEqual(0, (await live.Rig.QueryAsync("SELECT COUNT(*) AS n FROM planned_orders WHERE strategy = @s", r => r.Number("n"), ("s", StrategyNames.StockAthBreakout)).ConfigureAwait(false)).Single());
|
||||
}
|
||||
|
||||
private static async Task<int> CountAsync(TradingRig rig, string strategy) =>
|
||||
(int)(await rig.QueryAsync("SELECT COUNT(*) AS n FROM engine_runs WHERE strategy = @s", r => r.Number("n"), ("s", strategy)).ConfigureAwait(false)).Single();
|
||||
}
|
||||
@@ -43,7 +43,9 @@ public sealed class StrategyScreensTests
|
||||
|
||||
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
|
||||
var strategies = await server.TextAsync("/strategie");
|
||||
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" })
|
||||
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni", "1 strategia", "Nuovi massimi storici sulle azioni USA",
|
||||
"Raccoglie segnali senza fare ordini: 14 in 31 giorni. Servono almeno 90 giorni per giudicarla.", "31 giorni su 90", "Momentum relativo tra crypto",
|
||||
"Scartata nei test: tolti i costi, il risultato è vicino a zero. Resta in archivio, non riceve capitale.", "Non supera i test" })
|
||||
{
|
||||
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
|
||||
}
|
||||
@@ -83,6 +85,19 @@ public sealed class StrategyScreensTests
|
||||
StringAssert.Contains(page, "In attesa dei dati");
|
||||
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
|
||||
|
||||
// The candidates of 8.4: the discarded one with its verdict, the other waiting, no button for either, and none by hand.
|
||||
foreach (var text in new[] { "Momentum relativo tra crypto", "Scartata nei test", "Nuovi massimi storici sulle azioni USA", "0 in 0 giorni" })
|
||||
{
|
||||
StringAssert.Contains(page, text);
|
||||
}
|
||||
|
||||
foreach (var (candidate, _) in StrategyNames.Candidates)
|
||||
{
|
||||
Assert.IsFalse(page.Contains("/azioni/strategie/" + candidate, StringComparison.Ordinal), "A candidate has no button.");
|
||||
using var post = await server.PostFormAsync("/strategie", $"/azioni/strategie/{candidate}/simulazione");
|
||||
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(candidate, CancellationToken.None))!.Stage);
|
||||
}
|
||||
|
||||
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
|
||||
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
|
||||
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
|
||||
|
||||
@@ -36,16 +36,18 @@ public sealed class TradingServiceTests
|
||||
// Every strategy starts in observation, crypto on OKX and stocks on Alpaca.
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
(StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.EquityMomentum, "Alpaca simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
|
||||
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray());
|
||||
|
||||
// A second start finds what is there.
|
||||
using var again = Service(rig, http);
|
||||
await again.StartAsync(_none).ConfigureAwait(false);
|
||||
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM accounts", r => r.Id("id")).ConfigureAwait(false));
|
||||
Assert.HasCount(3, await StrategiesAsync(rig).ConfigureAwait(false));
|
||||
Assert.HasCount(5, await StrategiesAsync(rig).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -62,9 +64,11 @@ public sealed class TradingServiceTests
|
||||
Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2).");
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
(StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
|
||||
(StrategyNames.EquityMomentum, "Alpaca paper", StrategyNames.Observation),
|
||||
(StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
|
||||
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is.");
|
||||
}
|
||||
|
||||
@@ -90,7 +94,7 @@ public sealed class TradingServiceTests
|
||||
|
||||
Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false));
|
||||
Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call.");
|
||||
var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
|
||||
var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state WHERE share > 0 ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { (StrategyNames.CryptoTrend, 1000m), (StrategyNames.EquityMeanrev, 550m), (StrategyNames.EquityMomentum, 1650m) }, shares.ToArray());
|
||||
|
||||
// The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate.
|
||||
|
||||
Reference in new issue
Block a user