From 04bb5737d658696d5e7f5333de0a36d667f48a21 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 09:27:38 +0100 Subject: [PATCH 1/6] Record the golden reports of the trial judge before the seam Three reports, byte for byte, with the elapsed seconds set to zero: the average cross with prior trials, the crypto_trend protocol and a judged variant outside the grid. The seam between the judge and the engines must leave them unchanged. refs #118 Co-Authored-By: Claude Opus 5.5 --- .../Fixtures/golden/crypto_trend.report.json | 1 + .../golden/crypto_trend_judged.report.json | 1 + .../Fixtures/golden/sma_cross.report.json | 1 + tests/Anubis.Tests/TrialSeamTests.cs | 86 +++++++++++++++++++ 4 files changed, 89 insertions(+) create mode 100644 tests/Anubis.Tests/Fixtures/golden/crypto_trend.report.json create mode 100644 tests/Anubis.Tests/Fixtures/golden/crypto_trend_judged.report.json create mode 100644 tests/Anubis.Tests/Fixtures/golden/sma_cross.report.json create mode 100644 tests/Anubis.Tests/TrialSeamTests.cs diff --git a/tests/Anubis.Tests/Fixtures/golden/crypto_trend.report.json b/tests/Anubis.Tests/Fixtures/golden/crypto_trend.report.json new file mode 100644 index 0000000..0b79177 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/golden/crypto_trend.report.json @@ -0,0 +1 @@ +{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"crypto_trend","strategy_name":"Trend crypto","strategy_version":"1","plan_hash":"7ec3317ccccbafae965e26b5c3346bfb4b5b98aec00bceb947e3dc996868e7d1","data_fingerprint":"c642391a4ac6bb996b606faa124a920f145d7e48348fd9992e8dc8847e7f5210","currency":"EUR","periods_per_year":365,"sessions":800,"instruments":[{"symbol":"BTCEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"ETHEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"SOLEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"}],"chosen":"coin_vol=10;max_stop=10","metrics":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":42498.58399720671700250,"total_return":3.2498583997206714,"annual_return":0.9375426829552627,"volatility":0.07235876643893155,"sharpe":9.178841572568931,"daily_sharpe":0.48044252607481563,"max_drawdown":0.026175829689565357,"drawdown_peak":"2026-10-11","drawdown_low":"2026-10-16","trades":36,"winners":10,"profit_factor":35.29456708299872,"average_win":2313.081459858028508055,"average_loss":-25.206335956407039201923076923,"fees":396.81028898370354480,"exposure":0.23565100560758143,"years":[{"year":2024,"start":10000,"end":10000,"result":0,"return":0},{"year":2025,"start":10000,"end":11331.10279399256161285,"result":1331.10279399256161285,"return":0.13311027939925602},{"year":2026,"start":11331.10279399256161285,"end":42498.58399720671700250,"result":31167.48120321415538965,"return":2.7506132253727587}],"net_result":32498.58399720671700250,"win_rate":0.2777777777777778},"benchmark":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":166213.82941437167155,"total_return":15.621382941437169,"annual_return":2.6141681851348806,"volatility":0.14608381895658237,"sharpe":8.877533265620782,"daily_sharpe":0.46467132848163395,"max_drawdown":0.09004021309394361,"drawdown_peak":"2026-10-11","drawdown_low":"2026-11-24","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.9099499956572297,"exposure":0.9974278743768157,"years":[{"year":2024,"start":10000,"end":15368.88961128832475,"result":5368.88961128832475,"return":0.5368889611288326},{"year":2025,"start":15368.88961128832475,"end":51003.69143985236835,"result":35634.80182856404360,"return":2.3186321673096395},{"year":2026,"start":51003.69143985236835,"end":166213.82941437167155,"result":115210.13797451930320,"return":2.2588588143739425}],"net_result":156213.82941437167155,"win_rate":0},"costs":[{"multiplier":1,"net_result":32498.58399720671700250,"total_return":3.2498583997206714,"sharpe":9.178841572568931,"max_drawdown":0.026175829689565357,"fees":396.81028898370354480},{"multiplier":2,"net_result":31681.95878299984471576,"total_return":3.1681958782999846,"sharpe":9.045311963181552,"max_drawdown":0.02651561512819553,"fees":784.70618400521720504},{"multiplier":3,"net_result":31370.57922715067109828,"total_return":3.1370579227150674,"sharpe":8.94483685023732,"max_drawdown":0.0274714489120567,"fees":1172.66034249574190652}],"variants":[{"parameters":"coin_vol=10;max_stop=10","sharpe":0.48044252607481563,"plateau_score":0.4653655889498502,"net_result":32498.58399720671700250,"max_drawdown":0.026175829689565357,"trades":36,"chosen":true,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=15","sharpe":0.445931236512579,"plateau_score":0.445931236512579,"net_result":26183.75750214343511961,"max_drawdown":0.029641772278433863,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=20","sharpe":0.4223858225329875,"plateau_score":0.4223858225329875,"net_result":24328.79097386721189274,"max_drawdown":0.029754173892141213,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=10","sharpe":0.4930869429792893,"plateau_score":0.4639457230048902,"net_result":50498.43419278263970438,"max_drawdown":0.025774756298243173,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=15","sharpe":0.4420016502327168,"plateau_score":0.4420016502327168,"net_result":38197.30057159239968207,"max_drawdown":0.033017070317847674,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=20","sharpe":0.41763453843434895,"plateau_score":0.41763453843434895,"net_result":33625.32347837452987842,"max_drawdown":0.03612622409318185,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=10","sharpe":0.48560767004198907,"plateau_score":0.46432514386048657,"net_result":51112.96885923040428466,"max_drawdown":0.026505594831178845,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=15","sharpe":0.4366043121879511,"plateau_score":0.4366043121879511,"net_result":38707.024288553773908135,"max_drawdown":0.03625399850714449,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=20","sharpe":0.40635067102248235,"plateau_score":0.40635067102248235,"net_result":33305.24937534011635522,"max_drawdown":0.041135914790743626,"trades":35,"chosen":false,"outside_grid":false}],"walk_forward":{"windows":[{"window":1,"train_from":"2024-10-24","train_to":"2025-03-23","test_from":"2025-04-01","test_to":"2025-09-06","chosen":"coin_vol=10;max_stop=10","return":0,"sharpe":0},{"window":2,"train_from":"2024-10-24","train_to":"2025-08-29","test_from":"2025-09-07","test_to":"2026-02-12","chosen":"coin_vol=10;max_stop=10","return":0.4423158345662517,"sharpe":0.6154747036989195},{"window":3,"train_from":"2024-10-24","train_to":"2026-02-04","test_from":"2026-02-13","test_to":"2026-07-21","chosen":"coin_vol=10;max_stop=10","return":0.6601940594738362,"sharpe":0.7122429008759283},{"window":4,"train_from":"2024-10-24","train_to":"2026-07-13","test_from":"2026-07-22","test_to":"2026-12-31","chosen":"coin_vol=10;max_stop=10","return":0.7748237559890154,"sharpe":0.6998269304595159}],"purge":8,"return":3.2498583997207255,"sharpe":0.5528375496854625},"combinatorial":{"groups":6,"test_groups":2,"splits":15,"purge":8,"embargo":8,"path_sharpes":[0.48099859422597113,0.48099859422597113,0.48099859422597113,0.47685720494377715,0.48099859422597113],"mean_sharpe":0.4801703163695324,"worst_sharpe":0.47685720494377715,"positive_share":1},"overfitting":{"groups":16,"combinations":12870,"variants":9,"probability":0.0056721056721056725},"deflated_sharpe":{"sharpe":0.48044252607481563,"benchmark":0.04803769136054648,"observations":799,"skewness":1.0506935269138513,"kurtosis":4.340720124391887,"trials":9,"sharpe_variance":0.0009977747366630469,"value":1},"trials_counted":9,"look_ahead":{"cutoffs":["2025-02-14","2025-06-08","2025-09-30","2026-01-22","2026-05-16","2026-09-07"],"decisions":2400,"changed":0,"examples":[],"passed":true},"checks":[{"key":"double_costs","name":"Risultato netto con costi doppi","value":31681.958782999845,"comparison":"\u003E","threshold":0,"unit":"money","passed":true},{"key":"deflated_sharpe","name":"Deflated Sharpe Ratio","value":1,"comparison":"\u2265","threshold":0.9,"unit":"ratio","passed":true},{"key":"overfitting","name":"Probabilit\u00E0 di sovra-adattamento (PBO)","value":0.0056721056721056725,"comparison":"\u2264","threshold":0.4,"unit":"ratio","passed":true},{"key":"drawdown","name":"Calo massimo","value":0.026175829689565357,"comparison":"\u2264","threshold":0.25,"unit":"percent","passed":true},{"key":"look_ahead","name":"Decisioni cambiate aggiungendo dati successivi","value":0,"comparison":"=","threshold":0,"unit":"count","passed":true}],"passed":true,"limitations":["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\u0027apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.","Sharpe e volatilit\u00E0 sono calcolati senza tasso privo di rischio.","Limiti di rischio e regime crypto applicati come dal vivo. La strategia \u00E8 il 40% del bot: il resto conta come liquidit\u00E0 ferma. Ogni chiusura vale come un giorno; se scatta l\u0027interruttore, supponiamo che tu riparta dopo sette giorni. Et\u00E0 dei prezzi, prezzo dell\u0027ordine 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: \u00E8 un\u0027approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si pu\u00F2 misurare: l\u0027universo sono le monete con pi\u00F9 scambi, passo di prezzo e quantit\u00E0 minima sono stime, i costi sono quelli di OKX."],"curve":[{"day":"2024-10-23","equity":10000,"benchmark":10000},{"day":"2024-10-25","equity":10000,"benchmark":9907.39294975227535},{"day":"2024-10-27","equity":10000,"benchmark":10100.99059585040975},{"day":"2024-10-29","equity":10000,"benchmark":10107.02811245373975},{"day":"2024-10-31","equity":10000,"benchmark":10121.44293143056055},{"day":"2024-11-02","equity":10000,"benchmark":10200.24564608361075},{"day":"2024-11-04","equity":10000,"benchmark":10407.52283344629535},{"day":"2024-11-06","equity":10000,"benchmark":10427.26983677752695},{"day":"2024-11-08","equity":10000,"benchmark":10736.75287602973955},{"day":"2024-11-10","equity":10000,"benchmark":10761.71396343938175},{"day":"2024-11-12","equity":10000,"benchmark":10916.86585963190935},{"day":"2024-11-14","equity":10000,"benchmark":10932.22286615293895},{"day":"2024-11-16","equity":10000,"benchmark":10945.20411382255095},{"day":"2024-11-18","equity":10000,"benchmark":11167.01859878092235},{"day":"2024-11-20","equity":10000,"benchmark":11408.96099153841835},{"day":"2024-11-22","equity":10000,"benchmark":11574.22987531692555},{"day":"2024-11-24","equity":10000,"benchmark":11806.02949883897415},{"day":"2024-11-26","equity":10000,"benchmark":12166.58149447871575},{"day":"2024-11-28","equity":10000,"benchmark":12269.01175081692975},{"day":"2024-11-30","equity":10000,"benchmark":12234.30746049562435},{"day":"2024-12-02","equity":10000,"benchmark":12484.33490641317755},{"day":"2024-12-04","equity":10000,"benchmark":12687.25334945991115},{"day":"2024-12-06","equity":10000,"benchmark":12803.46745301810455},{"day":"2024-12-08","equity":10000,"benchmark":12966.46505918465275},{"day":"2024-12-10","equity":10000,"benchmark":13292.63493996667735},{"day":"2024-12-12","equity":10000,"benchmark":13588.57572205340475},{"day":"2024-12-14","equity":10000,"benchmark":13768.89243879303395},{"day":"2024-12-16","equity":10000,"benchmark":13751.94033706368815},{"day":"2024-12-18","equity":10000,"benchmark":13884.55582614222475},{"day":"2024-12-20","equity":10000,"benchmark":14403.71778210096455},{"day":"2024-12-22","equity":10000,"benchmark":14554.03489422542035},{"day":"2024-12-24","equity":10000,"benchmark":14697.16746367907995},{"day":"2024-12-26","equity":10000,"benchmark":14892.85635804921375},{"day":"2024-12-28","equity":10000,"benchmark":15233.46347303107255},{"day":"2024-12-30","equity":10000,"benchmark":15322.29434112244635},{"day":"2025-01-01","equity":10000,"benchmark":15521.20125107445835},{"day":"2025-01-03","equity":10000,"benchmark":15902.59412020775775},{"day":"2025-01-05","equity":10000,"benchmark":16108.11659703202715},{"day":"2025-01-07","equity":10000,"benchmark":16274.04530443450275},{"day":"2025-01-09","equity":10000,"benchmark":16903.30467687856155},{"day":"2025-01-11","equity":10000,"benchmark":17178.27183830122495},{"day":"2025-01-13","equity":10000,"benchmark":17597.67567819312695},{"day":"2025-01-15","equity":10000,"benchmark":17782.21919682747695},{"day":"2025-01-17","equity":10000,"benchmark":17982.94674199781715},{"day":"2025-01-19","equity":10000,"benchmark":18429.17809538452535},{"day":"2025-01-21","equity":10000,"benchmark":18529.76911657232415},{"day":"2025-01-23","equity":10000,"benchmark":18482.15025562597495},{"day":"2025-01-25","equity":10000,"benchmark":18675.84935886298975},{"day":"2025-01-27","equity":10000,"benchmark":18727.69171080163475},{"day":"2025-01-29","equity":10000,"benchmark":18705.43795611730895},{"day":"2025-01-31","equity":10000,"benchmark":18785.42461821279395},{"day":"2025-02-02","equity":10000,"benchmark":18516.95617332919235},{"day":"2025-02-04","equity":10000,"benchmark":18809.79130045006635},{"day":"2025-02-06","equity":10000,"benchmark":18828.53617973611755},{"day":"2025-02-08","equity":10000,"benchmark":18875.76709837915235},{"day":"2025-02-10","equity":10000,"benchmark":18822.64722654382095},{"day":"2025-02-12","equity":10000,"benchmark":19126.02517311091315},{"day":"2025-02-14","equity":10000,"benchmark":18988.76430257136195},{"day":"2025-02-16","equity":10000,"benchmark":18933.52783449426575},{"day":"2025-02-18","equity":10000,"benchmark":19145.91512752033815},{"day":"2025-02-20","equity":10000,"benchmark":19442.41340280273255},{"day":"2025-02-22","equity":10000,"benchmark":19562.56048994469715},{"day":"2025-02-24","equity":10000,"benchmark":19739.03378972462255},{"day":"2025-02-26","equity":10000,"benchmark":20059.97659828877215},{"day":"2025-02-28","equity":10000,"benchmark":20060.25395515768355},{"day":"2025-03-02","equity":10000,"benchmark":20560.56663867309615},{"day":"2025-03-04","equity":10000,"benchmark":20884.13022845138435},{"day":"2025-03-06","equity":10000,"benchmark":21185.44447329028255},{"day":"2025-03-08","equity":10000,"benchmark":21081.90988626701375},{"day":"2025-03-10","equity":10000,"benchmark":20907.52944433937595},{"day":"2025-03-12","equity":10000,"benchmark":20641.11270309802875},{"day":"2025-03-14","equity":10000,"benchmark":20691.55980076901055},{"day":"2025-03-16","equity":10000,"benchmark":20709.33161483885515},{"day":"2025-03-18","equity":10000,"benchmark":20756.78130740579275},{"day":"2025-03-20","equity":10000,"benchmark":20701.25862899120715},{"day":"2025-03-22","equity":10000,"benchmark":20835.97106793280895},{"day":"2025-03-24","equity":10000,"benchmark":20702.65980237481455},{"day":"2025-03-26","equity":10000,"benchmark":20825.35877775020335},{"day":"2025-03-28","equity":10000,"benchmark":20824.85106694712255},{"day":"2025-03-30","equity":10000,"benchmark":20946.11600865367895},{"day":"2025-04-01","equity":10000,"benchmark":20681.54925317024335},{"day":"2025-04-03","equity":10000,"benchmark":20666.29181893974535},{"day":"2025-04-05","equity":10000,"benchmark":20456.63384127660735},{"day":"2025-04-07","equity":10000,"benchmark":20554.11641386850975},{"day":"2025-04-09","equity":10000,"benchmark":20437.34718640147955},{"day":"2025-04-11","equity":10000,"benchmark":20607.72475293738955},{"day":"2025-04-13","equity":10000,"benchmark":20746.89426520950895},{"day":"2025-04-15","equity":10000,"benchmark":20814.49987733338395},{"day":"2025-04-17","equity":10000,"benchmark":20835.57139613419715},{"day":"2025-04-19","equity":10000,"benchmark":20958.74210172605075},{"day":"2025-04-21","equity":10000,"benchmark":21205.51436694431895},{"day":"2025-04-23","equity":10000,"benchmark":21420.31049343072755},{"day":"2025-04-25","equity":10000,"benchmark":21284.58345146691535},{"day":"2025-04-27","equity":10000,"benchmark":21134.33914033798095},{"day":"2025-04-29","equity":10000,"benchmark":21315.01315441857475},{"day":"2025-05-01","equity":10000,"benchmark":21415.11964451805855},{"day":"2025-05-03","equity":10000,"benchmark":21363.34282016620435},{"day":"2025-05-05","equity":10000,"benchmark":21653.21048077425735},{"day":"2025-05-07","equity":10000,"benchmark":21637.85833851690435},{"day":"2025-05-09","equity":10000,"benchmark":21643.45007780883975},{"day":"2025-05-11","equity":10000,"benchmark":21665.01149015306495},{"day":"2025-05-13","equity":10000,"benchmark":21674.53894541874015},{"day":"2025-05-15","equity":10000,"benchmark":21890.62815196753835},{"day":"2025-05-17","equity":10000,"benchmark":21874.54480977471735},{"day":"2025-05-19","equity":10000,"benchmark":22125.81133803262795},{"day":"2025-05-21","equity":10000,"benchmark":22490.29448028294975},{"day":"2025-05-23","equity":10000,"benchmark":22623.53201481411295},{"day":"2025-05-25","equity":10000,"benchmark":22752.00328480571995},{"day":"2025-05-27","equity":10000,"benchmark":23460.48994810421795},{"day":"2025-05-29","equity":10000,"benchmark":23292.62156638242675},{"day":"2025-05-31","equity":10000,"benchmark":23770.63640465624375},{"day":"2025-06-02","equity":10000,"benchmark":23959.90863113037735},{"day":"2025-06-04","equity":10000,"benchmark":24119.95976963573755},{"day":"2025-06-06","equity":10000,"benchmark":24693.41514966851515},{"day":"2025-06-08","equity":10000,"benchmark":25085.07023874109395},{"day":"2025-06-10","equity":10000,"benchmark":25467.54241773078935},{"day":"2025-06-12","equity":10000,"benchmark":25491.28156153201795},{"day":"2025-06-14","equity":10000,"benchmark":26263.26491215652315},{"day":"2025-06-16","equity":10000,"benchmark":26711.45941856803295},{"day":"2025-06-18","equity":10000,"benchmark":26682.57868457456475},{"day":"2025-06-20","equity":10000,"benchmark":27173.60389174312515},{"day":"2025-06-22","equity":10000,"benchmark":27486.75944827197635},{"day":"2025-06-24","equity":10000,"benchmark":28033.67935187702435},{"day":"2025-06-26","equity":10000,"benchmark":28113.80193164041335},{"day":"2025-06-28","equity":10000,"benchmark":28543.47700980468295},{"day":"2025-06-30","equity":10000,"benchmark":29596.77775891008315},{"day":"2025-07-02","equity":10000,"benchmark":30045.44119366583215},{"day":"2025-07-04","equity":10000,"benchmark":30376.99412314501695},{"day":"2025-07-06","equity":10000,"benchmark":30712.50771047561875},{"day":"2025-07-08","equity":10000,"benchmark":30761.54097866212075},{"day":"2025-07-10","equity":10000,"benchmark":31380.22777122511135},{"day":"2025-07-12","equity":10000,"benchmark":31877.81784013342115},{"day":"2025-07-14","equity":10000,"benchmark":31926.39091648614695},{"day":"2025-07-16","equity":10000,"benchmark":31941.84032318128695},{"day":"2025-07-18","equity":10000,"benchmark":31861.11003687009115},{"day":"2025-07-20","equity":10000,"benchmark":32674.81556943673795},{"day":"2025-07-22","equity":10000,"benchmark":32614.44051742483815},{"day":"2025-07-24","equity":10000,"benchmark":32338.01652268711615},{"day":"2025-07-26","equity":10000,"benchmark":32428.34923964113035},{"day":"2025-07-28","equity":10000,"benchmark":32726.12008805816195},{"day":"2025-07-30","equity":10000,"benchmark":32838.66929403229175},{"day":"2025-08-01","equity":10000,"benchmark":32533.78260028314655},{"day":"2025-08-03","equity":10000,"benchmark":32989.89317241360015},{"day":"2025-08-05","equity":10000,"benchmark":33201.45981080853175},{"day":"2025-08-07","equity":10000,"benchmark":33170.31042375747655},{"day":"2025-08-09","equity":10000,"benchmark":33704.36528121542995},{"day":"2025-08-11","equity":10000,"benchmark":33993.05000868008475},{"day":"2025-08-13","equity":10000,"benchmark":34355.95564313577235},{"day":"2025-08-15","equity":10000,"benchmark":34244.40967837351195},{"day":"2025-08-17","equity":10000,"benchmark":34631.38918927392735},{"day":"2025-08-19","equity":10000,"benchmark":35018.82039822752335},{"day":"2025-08-21","equity":10000,"benchmark":34978.72636818901555},{"day":"2025-08-23","equity":10000,"benchmark":35242.81837664679615},{"day":"2025-08-25","equity":10000,"benchmark":35696.35934466947975},{"day":"2025-08-27","equity":10000,"benchmark":36118.52934282933915},{"day":"2025-08-29","equity":10000,"benchmark":36752.85065470959115},{"day":"2025-08-31","equity":10000,"benchmark":36599.17724795318195},{"day":"2025-09-02","equity":10000,"benchmark":37098.00970760069135},{"day":"2025-09-04","equity":10000,"benchmark":37088.37084547296075},{"day":"2025-09-06","equity":10000,"benchmark":36798.64721510006195},{"day":"2025-09-08","equity":10000,"benchmark":36594.16740490890175},{"day":"2025-09-10","equity":10000,"benchmark":37206.69187412068555},{"day":"2025-09-12","equity":10000,"benchmark":37164.24727461483255},{"day":"2025-09-14","equity":10000,"benchmark":37646.97998586448735},{"day":"2025-09-16","equity":10000,"benchmark":38012.29600680423915},{"day":"2025-09-18","equity":10000,"benchmark":38253.47743503075515},{"day":"2025-09-20","equity":10000,"benchmark":37641.65541084490855},{"day":"2025-09-22","equity":10000,"benchmark":37888.22691552201055},{"day":"2025-09-24","equity":10000,"benchmark":38505.35246602859715},{"day":"2025-09-26","equity":10000,"benchmark":38327.61965286259375},{"day":"2025-09-28","equity":10000,"benchmark":38557.84837512835235},{"day":"2025-09-30","equity":10000,"benchmark":38402.46521329452375},{"day":"2025-10-02","equity":10000,"benchmark":38103.43951439701395},{"day":"2025-10-04","equity":10000,"benchmark":38521.30822346748775},{"day":"2025-10-06","equity":10000,"benchmark":38955.01202778714755},{"day":"2025-10-08","equity":10000,"benchmark":39098.82214015427735},{"day":"2025-10-10","equity":10000,"benchmark":39758.52382084159015},{"day":"2025-10-12","equity":10000,"benchmark":39936.48226654747495},{"day":"2025-10-14","equity":10000,"benchmark":40008.85256968566335},{"day":"2025-10-16","equity":10000,"benchmark":39967.89383950147895},{"day":"2025-10-18","equity":10000,"benchmark":39984.04812025585395},{"day":"2025-10-20","equity":10000,"benchmark":39213.57922465204735},{"day":"2025-10-22","equity":10000,"benchmark":39651.79401176732455},{"day":"2025-10-24","equity":10000,"benchmark":39920.83199336328915},{"day":"2025-10-26","equity":10000,"benchmark":39493.23790947959995},{"day":"2025-10-28","equity":10000,"benchmark":38852.34028812445155},{"day":"2025-10-30","equity":10000,"benchmark":38740.10789304065795},{"day":"2025-11-01","equity":10000,"benchmark":39033.25820137804755},{"day":"2025-11-03","equity":10000,"benchmark":38795.96840954161035},{"day":"2025-11-05","equity":10000,"benchmark":38764.94571171283815},{"day":"2025-11-07","equity":10000,"benchmark":39031.63468040389395},{"day":"2025-11-09","equity":10000,"benchmark":39653.38582236662355},{"day":"2025-11-11","equity":10000,"benchmark":38901.85966177969755},{"day":"2025-11-13","equity":10000,"benchmark":38335.66109076747195},{"day":"2025-11-15","equity":10000,"benchmark":38370.22223960356115},{"day":"2025-11-17","equity":10000,"benchmark":38648.65694863801455},{"day":"2025-11-19","equity":10000,"benchmark":38730.10197166200855},{"day":"2025-11-21","equity":10000,"benchmark":38639.38965039019015},{"day":"2025-11-23","equity":10000,"benchmark":38883.07560155775595},{"day":"2025-11-25","equity":10000,"benchmark":39105.16323589847555},{"day":"2025-11-27","equity":10000,"benchmark":39284.69845255663255},{"day":"2025-11-29","equity":10000,"benchmark":39216.52188563015875},{"day":"2025-12-01","equity":10000,"benchmark":39134.14613435015055},{"day":"2025-12-03","equity":10043.2059957012142,"benchmark":40447.99389736322655},{"day":"2025-12-05","equity":10112.7581097308268,"benchmark":41589.39156144602435},{"day":"2025-12-07","equity":10198.9766353773880,"benchmark":42634.44200478790935},{"day":"2025-12-09","equity":10275.8882783787870,"benchmark":43231.27577792839715},{"day":"2025-12-11","equity":10404.5457626835593,"benchmark":44218.67406814119435},{"day":"2025-12-13","equity":10557.9236488818359,"benchmark":45278.49058531575335},{"day":"2025-12-15","equity":10678.5048965790675,"benchmark":46028.27269875863635},{"day":"2025-12-17","equity":10755.77333565645899725,"benchmark":46510.98401731521955},{"day":"2025-12-19","equity":10883.12396784021599725,"benchmark":47442.89051134539075},{"day":"2025-12-21","equity":11019.10058900580719725,"benchmark":48452.76219166626395},{"day":"2025-12-23","equity":11100.00850017079219725,"benchmark":49342.40668694350955},{"day":"2025-12-25","equity":11151.73464747812519725,"benchmark":49677.65558147250755},{"day":"2025-12-27","equity":11275.75662663133799725,"benchmark":50478.19376232384175},{"day":"2025-12-29","equity":11304.83461042665541285,"benchmark":50767.63425148260335},{"day":"2025-12-31","equity":11331.10279399256161285,"benchmark":51003.69143985236835},{"day":"2026-01-02","equity":11404.42495545170621285,"benchmark":51532.07578253508635},{"day":"2026-01-04","equity":11498.66875936374801285,"benchmark":52087.51876299808975},{"day":"2026-01-06","equity":11604.16363492382121285,"benchmark":52888.75675470875215},{"day":"2026-01-08","equity":11812.30452910041321285,"benchmark":54269.06489741627195},{"day":"2026-01-10","equity":12091.61778475727501285,"benchmark":56152.42759169254655},{"day":"2026-01-12","equity":12232.14962515276881285,"benchmark":57151.99706477700435},{"day":"2026-01-14","equity":12410.86287907507701285,"benchmark":58433.89066325964495},{"day":"2026-01-16","equity":12370.11581655321581285,"benchmark":58071.88150942281095},{"day":"2026-01-18","equity":12538.50741466591721285,"benchmark":58774.64317749573275},{"day":"2026-01-20","equity":12713.72608924551741285,"benchmark":59703.86828857752655},{"day":"2026-01-22","equity":12743.03267047237641285,"benchmark":59598.95949872813695},{"day":"2026-01-24","equity":12746.32885130399916757,"benchmark":59472.96183802359015},{"day":"2026-01-26","equity":12898.80840528352716757,"benchmark":60132.02698414218115},{"day":"2026-01-28","equity":13136.62999654604796757,"benchmark":61322.78258148467175},{"day":"2026-01-30","equity":13372.95436972449636757,"benchmark":62114.32350080932775},{"day":"2026-02-01","equity":13387.12425068643776757,"benchmark":61662.79543129120555},{"day":"2026-02-03","equity":13585.72413106572336757,"benchmark":62860.81542824564215},{"day":"2026-02-05","equity":13888.19953919921676757,"benchmark":63818.59304168104155},{"day":"2026-02-07","equity":13987.09883333399876757,"benchmark":64047.15211551853435},{"day":"2026-02-09","equity":14087.24704804270836757,"benchmark":64452.39971871095895},{"day":"2026-02-11","equity":14360.92716355296876757,"benchmark":65155.46583485929715},{"day":"2026-02-13","equity":14538.66861032258676757,"benchmark":65916.09137131943235},{"day":"2026-02-15","equity":14649.91448232392816757,"benchmark":66380.83481564620315},{"day":"2026-02-17","equity":14755.85418460780836757,"benchmark":67079.03094716258175},{"day":"2026-02-19","equity":15009.16878940401118957,"benchmark":68090.61895654366015},{"day":"2026-02-21","equity":15328.59701624526378957,"benchmark":69226.70009086052635},{"day":"2026-02-23","equity":15349.84850077869218957,"benchmark":68927.15245288391495},{"day":"2026-02-25","equity":15609.34945273219318957,"benchmark":69867.91763897099255},{"day":"2026-02-27","equity":15989.85343658747198957,"benchmark":71320.70146046296095},{"day":"2026-03-01","equity":15933.61941553470078957,"benchmark":70854.52623846701635},{"day":"2026-03-03","equity":15836.89835116542698957,"benchmark":70183.79622477874095},{"day":"2026-03-05","equity":15782.07778393962598957,"benchmark":69872.57342593429715},{"day":"2026-03-07","equity":15884.25114485230158957,"benchmark":69843.05837477132135},{"day":"2026-03-09","equity":15930.10999899172302457,"benchmark":69886.13337307483055},{"day":"2026-03-11","equity":15943.53851502320317329,"benchmark":69577.41834083331215},{"day":"2026-03-13","equity":16214.17566408962751769,"benchmark":71419.15450235141375},{"day":"2026-03-15","equity":16203.22408708959371769,"benchmark":71368.08290948770415},{"day":"2026-03-17","equity":16349.36004188963991769,"benchmark":72558.57749117356295},{"day":"2026-03-19","equity":16425.54877514810571769,"benchmark":72310.91208228496955},{"day":"2026-03-21","equity":16355.83146021215110399,"benchmark":71213.69984312353755},{"day":"2026-03-23","equity":16604.68588241876250399,"benchmark":71322.19146506409635},{"day":"2026-03-25","equity":16735.89138377331550399,"benchmark":71374.57831471705715},{"day":"2026-03-27","equity":16811.68138938960110399,"benchmark":71211.84979202736435},{"day":"2026-03-29","equity":17039.52707572977350399,"benchmark":71780.21359067205795},{"day":"2026-03-31","equity":17101.19667517556578869,"benchmark":70865.40388207004035},{"day":"2026-04-02","equity":17147.81228532449458869,"benchmark":69749.32445443944055},{"day":"2026-04-04","equity":17200.69087710907878869,"benchmark":69299.83048964734195},{"day":"2026-04-06","equity":17489.34298008909538869,"benchmark":70588.34801154845435},{"day":"2026-04-08","equity":17577.35004838521905069,"benchmark":69683.81576313992455},{"day":"2026-04-10","equity":17922.52754258323945069,"benchmark":70675.89860466374295},{"day":"2026-04-12","equity":17838.91628119293781069,"benchmark":69864.71336326000295},{"day":"2026-04-14","equity":18145.48735852340219664,"benchmark":71466.66144371131135},{"day":"2026-04-16","equity":18371.61271538363079664,"benchmark":73391.09860443846415},{"day":"2026-04-18","equity":18281.33031622985239664,"benchmark":73003.70280722176355},{"day":"2026-04-20","equity":18302.71259694268239664,"benchmark":73336.31958625211995},{"day":"2026-04-22","equity":18222.68703773812089664,"benchmark":72997.71629657019735},{"day":"2026-04-24","equity":18146.54712053562578289,"benchmark":72721.94769280481315},{"day":"2026-04-26","equity":17945.92569367107803714,"benchmark":71582.97586798338995},{"day":"2026-04-28","equity":18040.23088973950343714,"benchmark":72162.26157689166495},{"day":"2026-04-30","equity":18167.92465436992108714,"benchmark":72433.38077343249695},{"day":"2026-05-02","equity":18345.47714162649248714,"benchmark":72778.97610361151495},{"day":"2026-05-04","equity":18411.51400088675848714,"benchmark":73233.73164413946195},{"day":"2026-05-06","equity":18333.19167021249478714,"benchmark":71123.07894352415475},{"day":"2026-05-08","equity":18425.61971237599298714,"benchmark":70937.16146444475035},{"day":"2026-05-10","equity":18562.20179515295115804,"benchmark":71120.44278322352875},{"day":"2026-05-12","equity":18621.46938602774715804,"benchmark":71070.42537642689035},{"day":"2026-05-14","equity":18743.31658020857775804,"benchmark":70852.68977910040815},{"day":"2026-05-16","equity":18780.03845744686149104,"benchmark":70826.28020105341435},{"day":"2026-05-18","equity":18756.38952657819289104,"benchmark":69880.86671526829255},{"day":"2026-05-20","equity":18854.12294604035649104,"benchmark":69879.79826391676575},{"day":"2026-05-22","equity":18885.38369495274889104,"benchmark":69680.10899442853575},{"day":"2026-05-24","equity":19023.79095128977249104,"benchmark":69735.75697852792455},{"day":"2026-05-26","equity":19147.61373183309629104,"benchmark":69275.49772270534595},{"day":"2026-05-28","equity":19292.64501303259709104,"benchmark":69986.79451947424315},{"day":"2026-05-30","equity":19481.10215382649531354,"benchmark":71447.34877145831735},{"day":"2026-06-01","equity":19411.87620234930169354,"benchmark":71628.24353561449015},{"day":"2026-06-03","equity":19691.15530995871829354,"benchmark":73972.60340029849955},{"day":"2026-06-05","equity":19811.47880880828845434,"benchmark":75512.68412261733615},{"day":"2026-06-07","equity":19984.97612809557085434,"benchmark":76625.80764351961415},{"day":"2026-06-09","equity":20182.93329123395305434,"benchmark":78036.22699460417395},{"day":"2026-06-11","equity":20185.70273320664174544,"benchmark":78355.93263353967655},{"day":"2026-06-13","equity":20262.60456852770237384,"benchmark":78584.84507408365695},{"day":"2026-06-15","equity":20445.01864166860917384,"benchmark":80006.92600105995015},{"day":"2026-06-17","equity":20417.22061388917177384,"benchmark":79637.21551034166075},{"day":"2026-06-19","equity":20602.08403601718989589,"benchmark":81092.30881264387255},{"day":"2026-06-21","equity":20867.40587444718469589,"benchmark":83561.54335835540335},{"day":"2026-06-23","equity":21228.54570008573779589,"benchmark":86106.87704861394875},{"day":"2026-06-25","equity":21339.06525064459239589,"benchmark":86953.96854482383155},{"day":"2026-06-27","equity":21511.80813709949039589,"benchmark":88171.35065006665095},{"day":"2026-06-29","equity":21734.50342384174629589,"benchmark":89648.27305062377715},{"day":"2026-07-01","equity":22148.57889365706659589,"benchmark":92153.36869512097775},{"day":"2026-07-03","equity":22237.05969819185439589,"benchmark":92644.11893792912055},{"day":"2026-07-05","equity":22423.77402223330479589,"benchmark":93858.58185760531575},{"day":"2026-07-07","equity":22641.43212809889179589,"benchmark":95275.62968543694035},{"day":"2026-07-09","equity":22842.87605961973982099,"benchmark":96447.31553300244775},{"day":"2026-07-11","equity":23430.65311033902236379,"benchmark":99877.07728884446015},{"day":"2026-07-13","equity":23586.75099687314956379,"benchmark":100667.64295221047495},{"day":"2026-07-15","equity":23522.53311052436656379,"benchmark":100932.14965813101595},{"day":"2026-07-17","equity":23701.34253794422276379,"benchmark":102405.48492150291595},{"day":"2026-07-19","equity":23821.20077238089461379,"benchmark":102853.19338052379275},{"day":"2026-07-21","equity":23945.24180431923301379,"benchmark":103356.13760867426215},{"day":"2026-07-23","equity":24104.49519423587418735,"benchmark":103424.11448331857015},{"day":"2026-07-25","equity":24232.62578483571318735,"benchmark":103463.44650255353655},{"day":"2026-07-27","equity":24476.54974725502258735,"benchmark":103656.28966019508595},{"day":"2026-07-29","equity":24538.26675342133978735,"benchmark":103105.93343270884155},{"day":"2026-07-31","equity":24987.10749951005618735,"benchmark":104231.53694307718955},{"day":"2026-08-02","equity":25521.29534594303758735,"benchmark":106653.41188426152895},{"day":"2026-08-04","equity":26063.44684197688198735,"benchmark":109277.97257045663135},{"day":"2026-08-06","equity":26312.01690588666118735,"benchmark":110107.50376639502215},{"day":"2026-08-08","equity":27147.00594995574778735,"benchmark":113946.12204312267275},{"day":"2026-08-10","equity":27199.59866664930898735,"benchmark":113676.22073977581735},{"day":"2026-08-12","equity":27353.75445819682998735,"benchmark":113485.94754396056715},{"day":"2026-08-14","equity":27805.28905249763538735,"benchmark":115282.70812734407615},{"day":"2026-08-16","equity":28405.84527195945598735,"benchmark":118373.01964887169855},{"day":"2026-08-18","equity":28650.62884089441738735,"benchmark":119384.93684138753615},{"day":"2026-08-20","equity":29191.60962855732158735,"benchmark":121730.22633837126495},{"day":"2026-08-22","equity":29844.00964558613638735,"benchmark":124053.28251272895935},{"day":"2026-08-24","equity":30030.57941072844198735,"benchmark":125016.29243581108435},{"day":"2026-08-26","equity":30591.83073566436178735,"benchmark":127765.39124902104735},{"day":"2026-08-28","equity":31105.63117742583098735,"benchmark":129812.22659229293275},{"day":"2026-08-30","equity":30879.34296813168998735,"benchmark":128663.45852662609075},{"day":"2026-09-01","equity":30748.38987635882698735,"benchmark":127021.54793817295875},{"day":"2026-09-03","equity":30719.90456160193898735,"benchmark":125981.39329733101895},{"day":"2026-09-05","equity":30337.23407232865174200,"benchmark":122730.51980725733275},{"day":"2026-09-07","equity":30708.85069980629574200,"benchmark":125585.43717181814375},{"day":"2026-09-09","equity":30819.40379857693219200,"benchmark":124773.89407966497415},{"day":"2026-09-11","equity":30831.31440410827583350,"benchmark":126216.96953208298935},{"day":"2026-09-13","equity":31156.02917461356313350,"benchmark":125116.15986791909935},{"day":"2026-09-15","equity":31173.52401887917736000,"benchmark":122744.56917757469655},{"day":"2026-09-17","equity":31691.16578825032456000,"benchmark":124024.96461161439015},{"day":"2026-09-19","equity":31710.72082908613576000,"benchmark":122212.45282830319835},{"day":"2026-09-21","equity":31757.85745663853243925,"benchmark":121380.17124314854415},{"day":"2026-09-23","equity":31614.23869395636773925,"benchmark":120188.00964849802935},{"day":"2026-09-25","equity":31613.36102401252832945,"benchmark":120221.93050599439595},{"day":"2026-09-27","equity":31706.45943192496522945,"benchmark":121017.68031943879735},{"day":"2026-09-29","equity":32124.62555180927022945,"benchmark":123579.23978335586475},{"day":"2026-10-01","equity":32330.69553502287518115,"benchmark":123670.04465137336295},{"day":"2026-10-03","equity":32684.78476342321711795,"benchmark":125676.53845875914315},{"day":"2026-10-05","equity":33062.06951867935711795,"benchmark":128259.12630929546135},{"day":"2026-10-07","equity":33366.26224716009746795,"benchmark":128780.97086412745535},{"day":"2026-10-09","equity":33689.10642303770946795,"benchmark":130381.25696189837775},{"day":"2026-10-11","equity":33979.64390904852813805,"benchmark":132401.06607658030055},{"day":"2026-10-13","equity":33435.65512836677853805,"benchmark":128154.69898270005135},{"day":"2026-10-15","equity":33191.07862429035933805,"benchmark":126644.32517228572655},{"day":"2026-10-17","equity":33286.34858659383824605,"benchmark":127358.69077860059395},{"day":"2026-10-19","equity":33566.42748325956217855,"benchmark":128610.81863514657875},{"day":"2026-10-21","equity":33323.84416054500277855,"benchmark":127641.26225877472295},{"day":"2026-10-23","equity":33138.61034534978075875,"benchmark":125993.70728521449115},{"day":"2026-10-25","equity":33343.52459474075653195,"benchmark":125262.54207487285955},{"day":"2026-10-27","equity":33517.90726019689093195,"benchmark":124783.67349684385555},{"day":"2026-10-29","equity":33705.68266214197633195,"benchmark":125758.62566102109655},{"day":"2026-10-31","equity":33766.00080082445263195,"benchmark":126867.14122513152295},{"day":"2026-11-02","equity":33953.28416286476073195,"benchmark":127058.32392197621955},{"day":"2026-11-04","equity":34111.36944395598883195,"benchmark":127521.56626038677935},{"day":"2026-11-06","equity":34337.99793199447263195,"benchmark":125962.61604378853715},{"day":"2026-11-08","equity":34333.49510727056805695,"benchmark":124536.08778082201835},{"day":"2026-11-10","equity":34379.94354455112296020,"benchmark":124145.60374689314435},{"day":"2026-11-12","equity":34541.67238311769676020,"benchmark":122898.53336356099815},{"day":"2026-11-14","equity":34770.36490412902556020,"benchmark":124413.92049414531535},{"day":"2026-11-16","equity":34827.90748918155296020,"benchmark":123383.10639854423875},{"day":"2026-11-18","equity":34904.38872657392127640,"benchmark":121298.58013017927155},{"day":"2026-11-20","equity":35126.61578859058407640,"benchmark":121505.82878291667395},{"day":"2026-11-22","equity":35126.24323154284391000,"benchmark":120600.40662174475555},{"day":"2026-11-24","equity":35255.48723471105756000,"benchmark":120479.64587317970195},{"day":"2026-11-26","equity":35406.96813611968408160,"benchmark":120850.18276023420915},{"day":"2026-11-28","equity":35624.46587014664948160,"benchmark":122508.94586031425055},{"day":"2026-11-30","equity":36132.75629490401848160,"benchmark":125870.76061541132115},{"day":"2026-12-02","equity":36540.71790022666328160,"benchmark":128965.72138668877635},{"day":"2026-12-04","equity":36861.98119112610598160,"benchmark":130679.20919237131535},{"day":"2026-12-06","equity":37074.31876059528718160,"benchmark":132082.77971864639375},{"day":"2026-12-08","equity":37484.99215440853038160,"benchmark":134445.07409990212975},{"day":"2026-12-10","equity":37526.43572305468806535,"benchmark":134397.01236399036135},{"day":"2026-12-12","equity":38107.48954536251006535,"benchmark":138151.56912202321615},{"day":"2026-12-14","equity":38431.96351961519026535,"benchmark":140131.00991486140755},{"day":"2026-12-16","equity":38661.14951231865886535,"benchmark":142246.99966869658015},{"day":"2026-12-18","equity":38982.16202949000225780,"benchmark":143721.40509693710495},{"day":"2026-12-20","equity":39438.00630612435285780,"benchmark":147046.44836621112635},{"day":"2026-12-22","equity":39919.88089197092808660,"benchmark":150832.28011990058395},{"day":"2026-12-24","equity":40225.46608152108148660,"benchmark":152878.11720832438695},{"day":"2026-12-26","equity":40766.53629610537780250,"benchmark":155675.25974011339755},{"day":"2026-12-28","equity":41719.54465643412340250,"benchmark":161002.49774276756795},{"day":"2026-12-30","equity":42537.44926732154480250,"benchmark":166223.07263782288135},{"day":"2026-12-31","equity":42498.58399720671700250,"benchmark":166213.82941437167155}],"trades":[{"symbol":"SOLEUR","opened":"2025-12-02","closed":"2026-01-24","invested":1938.5177753340168,"result":568.58686542790775472,"fees":8.90129334778611888,"is_closed":true},{"symbol":"ETHEUR","opened":"2025-12-03","closed":"2026-03-11","invested":2364.0371055672642,"result":2476.70951510869918372,"fees":14.42896924254928468,"is_closed":true},{"symbol":"BTCEUR","opened":"2025-12-06","closed":"2025-12-17","invested":804.7189028672475,"result":14.27826887116999725,"fees":3.25071470300587275,"is_closed":true},{"symbol":"BTCEUR","opened":"2025-12-23","closed":"2026-04-26","invested":3148.7417618921016,"result":4712.8915620003756249,"fees":22.0522597239695283,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-02-18","closed":"2026-02-18","invested":638.7607602831567,"result":-6.379156107576778,"fees":2.5448193245253914,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-03-13","closed":"2026-03-13","invested":690.0869928819105,"result":-9.9285725612270556,"fees":2.7432169122581766,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-03-14","closed":"2026-03-20","invested":1624.6914786174240,"result":-16.9799792312290137,"fees":6.4712496894717117,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-03-30","closed":"2026-03-30","invested":393.895122048456,"result":-5.9547465695755153,"fees":1.5652258662990773,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-07","closed":"2026-04-07","invested":815.7258459584325,"result":-15.054654822256338,"fees":3.236003177159703,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-14","closed":"2026-04-14","invested":912.88855602342675,"result":-17.50382643885241405,"fees":3.62013528756704255,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-16","closed":"2026-07-22","invested":2744.1059042104710,"result":2764.18275870791483436,"fees":16.52686644352792764,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-21","closed":"2026-04-23","invested":835.2773620758549,"result":-7.25203792338961375,"fees":3.32992411123079855,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-26","closed":"2026-04-26","invested":819.8037787218405,"result":-19.98580443711359505,"fees":3.24244918927680105,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-29","closed":"2026-05-09","invested":1587.00661467205905,"result":-7.6605561784792791,"fees":6.3390353906538972,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-16","closed":"2026-05-16","invested":825.8167425068433,"result":-11.796199605299267,"fees":3.2829371782031536,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-29","closed":"2026-05-29","invested":908.96419952517645,"result":-10.6703434491663775,"fees":3.6181164873790304,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-31","closed":"2026-06-01","invested":1824.810649862256,"result":-29.25458737393257,"fees":7.247930042186082,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-01","closed":"2026-06-10","invested":1424.54953480990095,"result":5.3120784018855411,"fees":5.7145532043127608,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-06-03","closed":"2026-09-05","invested":4562.8726936379196,"result":5522.09719625689935465,"fees":29.33610588806705955,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-12","closed":"2026-06-13","invested":381.76111757110245,"result":-5.7854240017877716,"fees":1.5169805388883265,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-19","closed":"2026-06-19","invested":395.8907247575592,"result":-5.79032459117347795,"fees":1.57354577850587135,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-22","closed":"2026-07-11","invested":3379.1380028260935,"result":91.6291088342996679,"fees":13.7137211192000691,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-07-16","closed":"2026-10-23","invested":5122.59094655104275,"result":6957.4654788688021382,"fees":34.4537118037630973,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-08","closed":"2026-09-10","invested":1238.67705026372655,"result":-9.6745245342079085,"fees":4.9402850138130616,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-12","closed":"2026-09-15","invested":2478.44913003178470,"result":-30.3280834707480735,"fees":9.8629524615886929,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-20","closed":"2026-09-20","invested":2630.069710402368,"result":-45.18300363985692075,"fees":10.44027310169153175,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-23","closed":"2026-10-03","invested":8029.8578901330246,"result":-143.6362484856787254,"fees":31.8637671663328746,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-09-29","closed":"2026-09-30","invested":1226.108383930056,"result":-10.3484120888237959,"fees":4.8886094970008579,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-10-06","invested":6989.50012358611305,"result":5096.3100024855242537,"fees":19.0252497193500724,"is_closed":false},{"symbol":"ETHEUR","opened":"2026-10-19","closed":"2026-10-19","invested":681.07568759146575,"result":-13.1773073866572675,"fees":2.7006250830081990,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-10-24","closed":"2026-10-24","invested":1334.03179769006625,"result":-26.7339100179146268,"fees":5.2878990416169093,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-10-30","closed":"2026-11-07","invested":2785.94147937898830,"result":-41.547288219186875,"fees":11.0716709169940516,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-10","closed":"2026-11-10","invested":1452.02976340757595,"result":-30.76761585574189675,"fees":5.75228026339197365,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-17","closed":"2026-11-17","invested":1479.427812203985,"result":-22.9021037256404838,"fees":5.8777448197553538,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-23","invested":9324.26445534510930,"result":4979.9650762589253716,"fees":21.5756674366197470,"is_closed":false},{"symbol":"BTCEUR","opened":"2026-12-01","closed":"2026-12-10","invested":2924.4677820828717,"result":17.66176610233098375,"fees":11.74498676293368465,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-17","closed":"2026-12-17","invested":1647.8658102675615,"result":-16.86705235257020755,"fees":6.56426620553510555,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-20","closed":"2026-12-21","invested":4968.2749175939916,"result":-94.2029717984971712,"fees":19.7042290852791544,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-22","invested":8531.1941134824792,"result":-53.1409452514346841,"fees":26.8000179590054925,"is_closed":false}],"notes":{"adjusted:crypto_regime_below_average":10,"adjusted:crypto_regime_high_volatility":39,"adjusted:trade_risk_limit":28,"residue_written_off":36,"below_min_notional":3},"computed_at":"2027-01-05T02:10:00+00:00","seconds":0,"expected_slippage_bp":5,"expected_path_p5":[-0.0022,-0.0014,-0.0009,-0.0009,-0.0009,-0.0011,-0.0007,-0.0007,-0.0002,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.0002,0.0006,0.0019,0.0022,0.0039,0.0043,0.0055,0.0066,0.007,0.0073,0.0074,0.0081,0.0095,0.0101,0.0107,0.011,0.011,0.0109,0.011,0.0125,0.0135,0.0135,0.0136,0.0146,0.0164,0.0164,0.017,0.0187,0.0199,0.0205,0.0217,0.0227,0.0233,0.0241,0.0241,0.0241,0.0248,0.0252,0.0251,0.0266,0.0261,0.027,0.0276,0.0289,0.0301,0.0305,0.0319,0.0326,0.0347,0.0348,0.0369,0.0393,0.0399,0.0426,0.0445,0.0447,0.0447,0.0453,0.0469,0.047,0.0497,0.0507,0.0507,0.0512,0.0512,0.0519,0.0532,0.0532,0.0532,0.0538,0.056,0.0565,0.0599,0.0632,0.0633,0.0648,0.065,0.0651,0.0669,0.0717,0.0728,0.0733,0.0743,0.0752,0.0752,0.0756,0.0778,0.0782,0.0792,0.0799,0.0817,0.0839,0.0839,0.0843,0.0846,0.0864,0.0874,0.09,0.0919,0.0936,0.0966,0.0979,0.099,0.099,0.1013,0.1012,0.1034,0.1043,0.1057,0.1071,0.109,0.1126,0.1137,0.1137,0.1138,0.115,0.1178,0.1197,0.1214,0.1214,0.1217,0.1232,0.1237,0.1237,0.1237,0.1253,0.1259,0.1291,0.1297,0.1315,0.132,0.1324,0.1335,0.1337,0.1337,0.1349,0.1346,0.1363,0.1383,0.1401,0.1394,0.1427,0.1453,0.1467,0.1485,0.1485,0.1499,0.1499,0.1499,0.152,0.1533,0.1577,0.1579,0.1622,0.1622,0.1623,0.1647,0.1664,0.1673,0.1675,0.1675,0.1709,0.1716,0.1738,0.1755,0.1784,0.1792,0.1813,0.1819,0.1836,0.1846,0.1855,0.1855,0.1876,0.1884,0.1926,0.1943,0.1948,0.1955,0.1948,0.1979,0.1976,0.1985,0.2008,0.2025,0.2043,0.2081,0.2067,0.2114,0.2122,0.2122,0.2144,0.2153,0.2173,0.2175,0.2175,0.2184,0.2206,0.2208,0.2208,0.2208,0.2242,0.2254,0.2269,0.2274,0.2274,0.23,0.2304,0.23,0.2304,0.2326,0.2322,0.2333,0.2413,0.2435,0.2446,0.2447,0.2514,0.2536,0.2533,0.2572,0.2588,0.2588,0.2599,0.2621,0.2607,0.2634,0.2651,0.2678,0.2689,0.2711,0.27,0.2775,0.2789,0.2798,0.2827,0.2857,0.2827,0.2839,0.2872,0.2875,0.2875,0.2909,0.2936,0.2935,0.2929,0.2953,0.2988,0.2997,0.3004,0.3057,0.3108,0.3108,0.3131,0.3149,0.3161,0.3131,0.3162,0.3162,0.3162,0.3162,0.3215,0.3236,0.3286,0.3307,0.3334,0.3364,0.3403,0.342,0.3462,0.3462,0.3462,0.3462,0.3462,0.3467,0.3501]} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/golden/crypto_trend_judged.report.json b/tests/Anubis.Tests/Fixtures/golden/crypto_trend_judged.report.json new file mode 100644 index 0000000..e643b57 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/golden/crypto_trend_judged.report.json @@ -0,0 +1 @@ +{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"crypto_trend","strategy_name":"Trend crypto","strategy_version":"1","plan_hash":"11f428e680695b378647e6aaa13aea82e3b18da3782d1a1d834aa7948a38d695","data_fingerprint":"c642391a4ac6bb996b606faa124a920f145d7e48348fd9992e8dc8847e7f5210","currency":"EUR","periods_per_year":365,"sessions":800,"instruments":[{"symbol":"BTCEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"ETHEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"},{"symbol":"SOLEUR","venue":"binance_eur","first":"2024-10-23","last":"2026-12-31","bars":800,"actions":0,"source":"storico Binance convertito in euro"}],"chosen":"coin_vol=10;max_stop=10","metrics":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":42515.803080578265635540,"total_return":3.251580308057827,"annual_return":0.9379015078266391,"volatility":0.07852841581547972,"sharpe":8.465947304810848,"daily_sharpe":0.44312793467261424,"max_drawdown":0.035651925733458024,"drawdown_peak":"2026-08-28","drawdown_low":"2026-09-05","trades":35,"winners":10,"profit_factor":30.15635208816501,"average_win":2264.676659182941375404,"average_loss":-30.039132751361173816,"fees":441.799860621142987760,"exposure":0.26147000965005857,"years":[{"year":2024,"start":10000,"end":10000,"result":0,"return":0},{"year":2025,"start":10000,"end":11099.7845636557723395,"result":1099.7845636557723395,"return":0.10997845636557724},{"year":2026,"start":11099.7845636557723395,"end":42515.803080578265635540,"result":31416.018516922493296040,"return":2.8303268713690657}],"net_result":32515.803080578265635540,"win_rate":0.2857142857142857},"benchmark":{"from":"2024-10-23","to":"2026-12-31","initial_capital":10000,"final_equity":166213.82941437167155,"total_return":15.621382941437169,"annual_return":2.6141681851348806,"volatility":0.14608381895658237,"sharpe":8.877533265620782,"daily_sharpe":0.46467132848163395,"max_drawdown":0.09004021309394361,"drawdown_peak":"2026-10-11","drawdown_low":"2026-11-24","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.9099499956572297,"exposure":0.9974278743768157,"years":[{"year":2024,"start":10000,"end":15368.88961128832475,"result":5368.88961128832475,"return":0.5368889611288326},{"year":2025,"start":15368.88961128832475,"end":51003.69143985236835,"result":35634.80182856404360,"return":2.3186321673096395},{"year":2026,"start":51003.69143985236835,"end":166213.82941437167155,"result":115210.13797451930320,"return":2.2588588143739425}],"net_result":156213.82941437167155,"win_rate":0},"costs":[{"multiplier":1,"net_result":32515.803080578265635540,"total_return":3.251580308057827,"sharpe":8.465947304810848,"max_drawdown":0.035651925733458024,"fees":441.799860621142987760},{"multiplier":2,"net_result":31604.7097350250246126,"total_return":3.1604709735025027,"sharpe":8.331667571175304,"max_drawdown":0.03575808521269184,"fees":872.5110473917330314},{"multiplier":3,"net_result":31012.068464926335629035,"total_return":3.1012068464926337,"sharpe":8.222893267893769,"max_drawdown":0.03586474574965844,"fees":1296.530436665625798465}],"variants":[{"parameters":"coin_vol=10;max_stop=10","sharpe":0.48044252607481563,"plateau_score":0.4653655889498502,"net_result":32498.58399720671700250,"max_drawdown":0.026175829689565357,"trades":36,"chosen":true,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=15","sharpe":0.445931236512579,"plateau_score":0.445931236512579,"net_result":26183.75750214343511961,"max_drawdown":0.029641772278433863,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=10;max_stop=20","sharpe":0.4223858225329875,"plateau_score":0.4223858225329875,"net_result":24328.79097386721189274,"max_drawdown":0.029754173892141213,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=10","sharpe":0.4930869429792893,"plateau_score":0.4639457230048902,"net_result":50498.43419278263970438,"max_drawdown":0.025774756298243173,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=15","sharpe":0.4420016502327168,"plateau_score":0.4420016502327168,"net_result":38197.30057159239968207,"max_drawdown":0.033017070317847674,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=15;max_stop=20","sharpe":0.41763453843434895,"plateau_score":0.41763453843434895,"net_result":33625.32347837452987842,"max_drawdown":0.03612622409318185,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=10","sharpe":0.48560767004198907,"plateau_score":0.46432514386048657,"net_result":51112.96885923040428466,"max_drawdown":0.026505594831178845,"trades":36,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=15","sharpe":0.4366043121879511,"plateau_score":0.4366043121879511,"net_result":38707.024288553773908135,"max_drawdown":0.03625399850714449,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=20;max_stop=20","sharpe":0.40635067102248235,"plateau_score":0.40635067102248235,"net_result":33305.24937534011635522,"max_drawdown":0.041135914790743626,"trades":35,"chosen":false,"outside_grid":false},{"parameters":"coin_vol=12;max_stop=15","sharpe":0.44312793467261424,"plateau_score":0,"net_result":32515.803080578265635540,"max_drawdown":0.035651925733458024,"trades":35,"chosen":false,"outside_grid":true}],"walk_forward":{"windows":[{"window":1,"train_from":"2024-10-24","train_to":"2025-03-23","test_from":"2025-04-01","test_to":"2025-09-06","chosen":"coin_vol=10;max_stop=10","return":0,"sharpe":0},{"window":2,"train_from":"2024-10-24","train_to":"2025-08-29","test_from":"2025-09-07","test_to":"2026-02-12","chosen":"coin_vol=10;max_stop=10","return":0.4423158345662517,"sharpe":0.6154747036989195},{"window":3,"train_from":"2024-10-24","train_to":"2026-02-04","test_from":"2026-02-13","test_to":"2026-07-21","chosen":"coin_vol=10;max_stop=10","return":0.6601940594738362,"sharpe":0.7122429008759283},{"window":4,"train_from":"2024-10-24","train_to":"2026-07-13","test_from":"2026-07-22","test_to":"2026-12-31","chosen":"coin_vol=10;max_stop=10","return":0.7748237559890154,"sharpe":0.6998269304595159}],"purge":8,"return":3.2498583997207255,"sharpe":0.5528375496854625},"combinatorial":{"groups":6,"test_groups":2,"splits":15,"purge":8,"embargo":8,"path_sharpes":[0.48099859422597113,0.48099859422597113,0.48099859422597113,0.47685720494377715,0.48099859422597113],"mean_sharpe":0.4801703163695324,"worst_sharpe":0.47685720494377715,"positive_share":1},"overfitting":{"groups":16,"combinations":12870,"variants":9,"probability":0.0056721056721056725},"deflated_sharpe":{"sharpe":0.44312793467261424,"benchmark":0.04803769136054648,"observations":799,"skewness":1.0218754882394872,"kurtosis":4.852070020162542,"trials":9,"sharpe_variance":0.0009977747366630469,"value":1},"trials_counted":9,"look_ahead":{"cutoffs":["2025-02-14","2025-06-08","2025-09-30","2026-01-22","2026-05-16","2026-09-07"],"decisions":2400,"changed":0,"examples":[],"passed":true},"checks":[{"key":"double_costs","name":"Risultato netto con costi doppi","value":31604.709735025022,"comparison":"\u003E","threshold":0,"unit":"money","passed":true},{"key":"deflated_sharpe","name":"Deflated Sharpe Ratio","value":1,"comparison":"\u2265","threshold":0.9,"unit":"ratio","passed":true},{"key":"overfitting","name":"Probabilit\u00E0 di sovra-adattamento (PBO)","value":0.0056721056721056725,"comparison":"\u2264","threshold":0.4,"unit":"ratio","passed":true},{"key":"drawdown","name":"Calo massimo","value":0.035651925733458024,"comparison":"\u2264","threshold":0.25,"unit":"percent","passed":true},{"key":"look_ahead","name":"Decisioni cambiate aggiungendo dati successivi","value":0,"comparison":"=","threshold":0,"unit":"count","passed":true}],"passed":true,"limitations":["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\u0027apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.","Sharpe e volatilit\u00E0 sono calcolati senza tasso privo di rischio.","Limiti di rischio e regime crypto applicati come dal vivo. La strategia \u00E8 il 40% del bot: il resto conta come liquidit\u00E0 ferma. Ogni chiusura vale come un giorno; se scatta l\u0027interruttore, supponiamo che tu riparta dopo sette giorni. Et\u00E0 dei prezzi, prezzo dell\u0027ordine 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: \u00E8 un\u0027approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si pu\u00F2 misurare: l\u0027universo sono le monete con pi\u00F9 scambi, passo di prezzo e quantit\u00E0 minima sono stime, i costi sono quelli di OKX.","La variante in uso non \u00E8 nella griglia: \u00E8 giudicata lo stesso, senza contare come un tentativo in pi\u00F9."],"curve":[{"day":"2024-10-23","equity":10000,"benchmark":10000},{"day":"2024-10-25","equity":10000,"benchmark":9907.39294975227535},{"day":"2024-10-27","equity":10000,"benchmark":10100.99059585040975},{"day":"2024-10-29","equity":10000,"benchmark":10107.02811245373975},{"day":"2024-10-31","equity":10000,"benchmark":10121.44293143056055},{"day":"2024-11-02","equity":10000,"benchmark":10200.24564608361075},{"day":"2024-11-04","equity":10000,"benchmark":10407.52283344629535},{"day":"2024-11-06","equity":10000,"benchmark":10427.26983677752695},{"day":"2024-11-08","equity":10000,"benchmark":10736.75287602973955},{"day":"2024-11-10","equity":10000,"benchmark":10761.71396343938175},{"day":"2024-11-12","equity":10000,"benchmark":10916.86585963190935},{"day":"2024-11-14","equity":10000,"benchmark":10932.22286615293895},{"day":"2024-11-16","equity":10000,"benchmark":10945.20411382255095},{"day":"2024-11-18","equity":10000,"benchmark":11167.01859878092235},{"day":"2024-11-20","equity":10000,"benchmark":11408.96099153841835},{"day":"2024-11-22","equity":10000,"benchmark":11574.22987531692555},{"day":"2024-11-24","equity":10000,"benchmark":11806.02949883897415},{"day":"2024-11-26","equity":10000,"benchmark":12166.58149447871575},{"day":"2024-11-28","equity":10000,"benchmark":12269.01175081692975},{"day":"2024-11-30","equity":10000,"benchmark":12234.30746049562435},{"day":"2024-12-02","equity":10000,"benchmark":12484.33490641317755},{"day":"2024-12-04","equity":10000,"benchmark":12687.25334945991115},{"day":"2024-12-06","equity":10000,"benchmark":12803.46745301810455},{"day":"2024-12-08","equity":10000,"benchmark":12966.46505918465275},{"day":"2024-12-10","equity":10000,"benchmark":13292.63493996667735},{"day":"2024-12-12","equity":10000,"benchmark":13588.57572205340475},{"day":"2024-12-14","equity":10000,"benchmark":13768.89243879303395},{"day":"2024-12-16","equity":10000,"benchmark":13751.94033706368815},{"day":"2024-12-18","equity":10000,"benchmark":13884.55582614222475},{"day":"2024-12-20","equity":10000,"benchmark":14403.71778210096455},{"day":"2024-12-22","equity":10000,"benchmark":14554.03489422542035},{"day":"2024-12-24","equity":10000,"benchmark":14697.16746367907995},{"day":"2024-12-26","equity":10000,"benchmark":14892.85635804921375},{"day":"2024-12-28","equity":10000,"benchmark":15233.46347303107255},{"day":"2024-12-30","equity":10000,"benchmark":15322.29434112244635},{"day":"2025-01-01","equity":10000,"benchmark":15521.20125107445835},{"day":"2025-01-03","equity":10000,"benchmark":15902.59412020775775},{"day":"2025-01-05","equity":10000,"benchmark":16108.11659703202715},{"day":"2025-01-07","equity":10000,"benchmark":16274.04530443450275},{"day":"2025-01-09","equity":10000,"benchmark":16903.30467687856155},{"day":"2025-01-11","equity":10000,"benchmark":17178.27183830122495},{"day":"2025-01-13","equity":10000,"benchmark":17597.67567819312695},{"day":"2025-01-15","equity":10000,"benchmark":17782.21919682747695},{"day":"2025-01-17","equity":10000,"benchmark":17982.94674199781715},{"day":"2025-01-19","equity":10000,"benchmark":18429.17809538452535},{"day":"2025-01-21","equity":10000,"benchmark":18529.76911657232415},{"day":"2025-01-23","equity":10000,"benchmark":18482.15025562597495},{"day":"2025-01-25","equity":10000,"benchmark":18675.84935886298975},{"day":"2025-01-27","equity":10000,"benchmark":18727.69171080163475},{"day":"2025-01-29","equity":10000,"benchmark":18705.43795611730895},{"day":"2025-01-31","equity":10000,"benchmark":18785.42461821279395},{"day":"2025-02-02","equity":10000,"benchmark":18516.95617332919235},{"day":"2025-02-04","equity":10000,"benchmark":18809.79130045006635},{"day":"2025-02-06","equity":10000,"benchmark":18828.53617973611755},{"day":"2025-02-08","equity":10000,"benchmark":18875.76709837915235},{"day":"2025-02-10","equity":10000,"benchmark":18822.64722654382095},{"day":"2025-02-12","equity":10000,"benchmark":19126.02517311091315},{"day":"2025-02-14","equity":10000,"benchmark":18988.76430257136195},{"day":"2025-02-16","equity":10000,"benchmark":18933.52783449426575},{"day":"2025-02-18","equity":10000,"benchmark":19145.91512752033815},{"day":"2025-02-20","equity":10000,"benchmark":19442.41340280273255},{"day":"2025-02-22","equity":10000,"benchmark":19562.56048994469715},{"day":"2025-02-24","equity":10000,"benchmark":19739.03378972462255},{"day":"2025-02-26","equity":10000,"benchmark":20059.97659828877215},{"day":"2025-02-28","equity":10000,"benchmark":20060.25395515768355},{"day":"2025-03-02","equity":10000,"benchmark":20560.56663867309615},{"day":"2025-03-04","equity":10000,"benchmark":20884.13022845138435},{"day":"2025-03-06","equity":10000,"benchmark":21185.44447329028255},{"day":"2025-03-08","equity":10000,"benchmark":21081.90988626701375},{"day":"2025-03-10","equity":10000,"benchmark":20907.52944433937595},{"day":"2025-03-12","equity":10000,"benchmark":20641.11270309802875},{"day":"2025-03-14","equity":10000,"benchmark":20691.55980076901055},{"day":"2025-03-16","equity":10000,"benchmark":20709.33161483885515},{"day":"2025-03-18","equity":10000,"benchmark":20756.78130740579275},{"day":"2025-03-20","equity":10000,"benchmark":20701.25862899120715},{"day":"2025-03-22","equity":10000,"benchmark":20835.97106793280895},{"day":"2025-03-24","equity":10000,"benchmark":20702.65980237481455},{"day":"2025-03-26","equity":10000,"benchmark":20825.35877775020335},{"day":"2025-03-28","equity":10000,"benchmark":20824.85106694712255},{"day":"2025-03-30","equity":10000,"benchmark":20946.11600865367895},{"day":"2025-04-01","equity":10000,"benchmark":20681.54925317024335},{"day":"2025-04-03","equity":10000,"benchmark":20666.29181893974535},{"day":"2025-04-05","equity":10000,"benchmark":20456.63384127660735},{"day":"2025-04-07","equity":10000,"benchmark":20554.11641386850975},{"day":"2025-04-09","equity":10000,"benchmark":20437.34718640147955},{"day":"2025-04-11","equity":10000,"benchmark":20607.72475293738955},{"day":"2025-04-13","equity":10000,"benchmark":20746.89426520950895},{"day":"2025-04-15","equity":10000,"benchmark":20814.49987733338395},{"day":"2025-04-17","equity":10000,"benchmark":20835.57139613419715},{"day":"2025-04-19","equity":10000,"benchmark":20958.74210172605075},{"day":"2025-04-21","equity":10000,"benchmark":21205.51436694431895},{"day":"2025-04-23","equity":10000,"benchmark":21420.31049343072755},{"day":"2025-04-25","equity":10000,"benchmark":21284.58345146691535},{"day":"2025-04-27","equity":10000,"benchmark":21134.33914033798095},{"day":"2025-04-29","equity":10000,"benchmark":21315.01315441857475},{"day":"2025-05-01","equity":10000,"benchmark":21415.11964451805855},{"day":"2025-05-03","equity":10000,"benchmark":21363.34282016620435},{"day":"2025-05-05","equity":10000,"benchmark":21653.21048077425735},{"day":"2025-05-07","equity":10000,"benchmark":21637.85833851690435},{"day":"2025-05-09","equity":10000,"benchmark":21643.45007780883975},{"day":"2025-05-11","equity":10000,"benchmark":21665.01149015306495},{"day":"2025-05-13","equity":10000,"benchmark":21674.53894541874015},{"day":"2025-05-15","equity":10000,"benchmark":21890.62815196753835},{"day":"2025-05-17","equity":10000,"benchmark":21874.54480977471735},{"day":"2025-05-19","equity":10000,"benchmark":22125.81133803262795},{"day":"2025-05-21","equity":10000,"benchmark":22490.29448028294975},{"day":"2025-05-23","equity":10000,"benchmark":22623.53201481411295},{"day":"2025-05-25","equity":10000,"benchmark":22752.00328480571995},{"day":"2025-05-27","equity":10000,"benchmark":23460.48994810421795},{"day":"2025-05-29","equity":10000,"benchmark":23292.62156638242675},{"day":"2025-05-31","equity":10000,"benchmark":23770.63640465624375},{"day":"2025-06-02","equity":10000,"benchmark":23959.90863113037735},{"day":"2025-06-04","equity":10000,"benchmark":24119.95976963573755},{"day":"2025-06-06","equity":10000,"benchmark":24693.41514966851515},{"day":"2025-06-08","equity":10000,"benchmark":25085.07023874109395},{"day":"2025-06-10","equity":10000,"benchmark":25467.54241773078935},{"day":"2025-06-12","equity":10000,"benchmark":25491.28156153201795},{"day":"2025-06-14","equity":10000,"benchmark":26263.26491215652315},{"day":"2025-06-16","equity":10000,"benchmark":26711.45941856803295},{"day":"2025-06-18","equity":10000,"benchmark":26682.57868457456475},{"day":"2025-06-20","equity":10000,"benchmark":27173.60389174312515},{"day":"2025-06-22","equity":10000,"benchmark":27486.75944827197635},{"day":"2025-06-24","equity":10000,"benchmark":28033.67935187702435},{"day":"2025-06-26","equity":10000,"benchmark":28113.80193164041335},{"day":"2025-06-28","equity":10000,"benchmark":28543.47700980468295},{"day":"2025-06-30","equity":10000,"benchmark":29596.77775891008315},{"day":"2025-07-02","equity":10000,"benchmark":30045.44119366583215},{"day":"2025-07-04","equity":10000,"benchmark":30376.99412314501695},{"day":"2025-07-06","equity":10000,"benchmark":30712.50771047561875},{"day":"2025-07-08","equity":10000,"benchmark":30761.54097866212075},{"day":"2025-07-10","equity":10000,"benchmark":31380.22777122511135},{"day":"2025-07-12","equity":10000,"benchmark":31877.81784013342115},{"day":"2025-07-14","equity":10000,"benchmark":31926.39091648614695},{"day":"2025-07-16","equity":10000,"benchmark":31941.84032318128695},{"day":"2025-07-18","equity":10000,"benchmark":31861.11003687009115},{"day":"2025-07-20","equity":10000,"benchmark":32674.81556943673795},{"day":"2025-07-22","equity":10000,"benchmark":32614.44051742483815},{"day":"2025-07-24","equity":10000,"benchmark":32338.01652268711615},{"day":"2025-07-26","equity":10000,"benchmark":32428.34923964113035},{"day":"2025-07-28","equity":10000,"benchmark":32726.12008805816195},{"day":"2025-07-30","equity":10000,"benchmark":32838.66929403229175},{"day":"2025-08-01","equity":10000,"benchmark":32533.78260028314655},{"day":"2025-08-03","equity":10000,"benchmark":32989.89317241360015},{"day":"2025-08-05","equity":10000,"benchmark":33201.45981080853175},{"day":"2025-08-07","equity":10000,"benchmark":33170.31042375747655},{"day":"2025-08-09","equity":10000,"benchmark":33704.36528121542995},{"day":"2025-08-11","equity":10000,"benchmark":33993.05000868008475},{"day":"2025-08-13","equity":10000,"benchmark":34355.95564313577235},{"day":"2025-08-15","equity":10000,"benchmark":34244.40967837351195},{"day":"2025-08-17","equity":10000,"benchmark":34631.38918927392735},{"day":"2025-08-19","equity":10000,"benchmark":35018.82039822752335},{"day":"2025-08-21","equity":10000,"benchmark":34978.72636818901555},{"day":"2025-08-23","equity":10000,"benchmark":35242.81837664679615},{"day":"2025-08-25","equity":10000,"benchmark":35696.35934466947975},{"day":"2025-08-27","equity":10000,"benchmark":36118.52934282933915},{"day":"2025-08-29","equity":10000,"benchmark":36752.85065470959115},{"day":"2025-08-31","equity":10000,"benchmark":36599.17724795318195},{"day":"2025-09-02","equity":10000,"benchmark":37098.00970760069135},{"day":"2025-09-04","equity":10000,"benchmark":37088.37084547296075},{"day":"2025-09-06","equity":10000,"benchmark":36798.64721510006195},{"day":"2025-09-08","equity":10000,"benchmark":36594.16740490890175},{"day":"2025-09-10","equity":10000,"benchmark":37206.69187412068555},{"day":"2025-09-12","equity":10000,"benchmark":37164.24727461483255},{"day":"2025-09-14","equity":10000,"benchmark":37646.97998586448735},{"day":"2025-09-16","equity":10000,"benchmark":38012.29600680423915},{"day":"2025-09-18","equity":10000,"benchmark":38253.47743503075515},{"day":"2025-09-20","equity":10000,"benchmark":37641.65541084490855},{"day":"2025-09-22","equity":10000,"benchmark":37888.22691552201055},{"day":"2025-09-24","equity":10000,"benchmark":38505.35246602859715},{"day":"2025-09-26","equity":10000,"benchmark":38327.61965286259375},{"day":"2025-09-28","equity":10000,"benchmark":38557.84837512835235},{"day":"2025-09-30","equity":10000,"benchmark":38402.46521329452375},{"day":"2025-10-02","equity":10000,"benchmark":38103.43951439701395},{"day":"2025-10-04","equity":10000,"benchmark":38521.30822346748775},{"day":"2025-10-06","equity":10000,"benchmark":38955.01202778714755},{"day":"2025-10-08","equity":10000,"benchmark":39098.82214015427735},{"day":"2025-10-10","equity":10000,"benchmark":39758.52382084159015},{"day":"2025-10-12","equity":10000,"benchmark":39936.48226654747495},{"day":"2025-10-14","equity":10000,"benchmark":40008.85256968566335},{"day":"2025-10-16","equity":10000,"benchmark":39967.89383950147895},{"day":"2025-10-18","equity":10000,"benchmark":39984.04812025585395},{"day":"2025-10-20","equity":10000,"benchmark":39213.57922465204735},{"day":"2025-10-22","equity":10000,"benchmark":39651.79401176732455},{"day":"2025-10-24","equity":10000,"benchmark":39920.83199336328915},{"day":"2025-10-26","equity":10000,"benchmark":39493.23790947959995},{"day":"2025-10-28","equity":10000,"benchmark":38852.34028812445155},{"day":"2025-10-30","equity":10000,"benchmark":38740.10789304065795},{"day":"2025-11-01","equity":10000,"benchmark":39033.25820137804755},{"day":"2025-11-03","equity":10000,"benchmark":38795.96840954161035},{"day":"2025-11-05","equity":10000,"benchmark":38764.94571171283815},{"day":"2025-11-07","equity":10000,"benchmark":39031.63468040389395},{"day":"2025-11-09","equity":10000,"benchmark":39653.38582236662355},{"day":"2025-11-11","equity":10000,"benchmark":38901.85966177969755},{"day":"2025-11-13","equity":10000,"benchmark":38335.66109076747195},{"day":"2025-11-15","equity":10000,"benchmark":38370.22223960356115},{"day":"2025-11-17","equity":10000,"benchmark":38648.65694863801455},{"day":"2025-11-19","equity":10000,"benchmark":38730.10197166200855},{"day":"2025-11-21","equity":10000,"benchmark":38639.38965039019015},{"day":"2025-11-23","equity":10000,"benchmark":38883.07560155775595},{"day":"2025-11-25","equity":10000,"benchmark":39105.16323589847555},{"day":"2025-11-27","equity":10000,"benchmark":39284.69845255663255},{"day":"2025-11-29","equity":10000,"benchmark":39216.52188563015875},{"day":"2025-12-01","equity":10000,"benchmark":39134.14613435015055},{"day":"2025-12-03","equity":10066.3288171059070,"benchmark":40447.99389736322655},{"day":"2025-12-05","equity":10167.4671926531318,"benchmark":41589.39156144602435},{"day":"2025-12-07","equity":10245.1209029974237,"benchmark":42634.44200478790935},{"day":"2025-12-09","equity":10300.9730670862769,"benchmark":43231.27577792839715},{"day":"2025-12-11","equity":10402.8010436957780,"benchmark":44218.67406814119435},{"day":"2025-12-13","equity":10518.5098173084330,"benchmark":45278.49058531575335},{"day":"2025-12-15","equity":10603.3687586603318,"benchmark":46028.27269875863635},{"day":"2025-12-17","equity":10655.8610908171895893,"benchmark":46510.98401731521955},{"day":"2025-12-19","equity":10758.0942536097489893,"benchmark":47442.89051134539075},{"day":"2025-12-21","equity":10867.1371780351089893,"benchmark":48452.76219166626395},{"day":"2025-12-23","equity":10931.2782217759901893,"benchmark":49342.40668694350955},{"day":"2025-12-25","equity":10957.9650294484788893,"benchmark":49677.65558147250755},{"day":"2025-12-27","equity":11063.0104843989104893,"benchmark":50478.19376232384175},{"day":"2025-12-29","equity":11084.7079715898297395,"benchmark":50767.63425148260335},{"day":"2025-12-31","equity":11099.7845636557723395,"benchmark":51003.69143985236835},{"day":"2026-01-02","equity":11156.5265261113797395,"benchmark":51532.07578253508635},{"day":"2026-01-04","equity":11240.2270883112919395,"benchmark":52087.51876299808975},{"day":"2026-01-06","equity":11325.5689163739163395,"benchmark":52888.75675470875215},{"day":"2026-01-08","equity":11486.3371881617947395,"benchmark":54269.06489741627195},{"day":"2026-01-10","equity":11704.6561031481161395,"benchmark":56152.42759169254655},{"day":"2026-01-12","equity":11825.5272602028067395,"benchmark":57151.99706477700435},{"day":"2026-01-14","equity":11976.6771282411349395,"benchmark":58433.89066325964495},{"day":"2026-01-16","equity":11954.0020764537203395,"benchmark":58071.88150942281095},{"day":"2026-01-18","equity":12110.3147103634873395,"benchmark":58774.64317749573275},{"day":"2026-01-20","equity":12269.4431365980253395,"benchmark":59703.86828857752655},{"day":"2026-01-22","equity":12323.4785223206381395,"benchmark":59598.95949872813695},{"day":"2026-01-24","equity":12296.0215942849397395,"benchmark":59472.96183802359015},{"day":"2026-01-26","equity":12446.9918202560713395,"benchmark":60132.02698414218115},{"day":"2026-01-28","equity":12689.8526298971615395,"benchmark":61322.78258148467175},{"day":"2026-01-30","equity":12845.0437161831321395,"benchmark":62114.32350080932775},{"day":"2026-02-01","equity":12809.07410404748267785,"benchmark":61662.79543129120555},{"day":"2026-02-03","equity":12984.97805978510447785,"benchmark":62860.81542824564215},{"day":"2026-02-05","equity":13262.40969023424727785,"benchmark":63818.59304168104155},{"day":"2026-02-07","equity":13352.34971879327287785,"benchmark":64047.15211551853435},{"day":"2026-02-09","equity":13482.87618313307447785,"benchmark":64452.39971871095895},{"day":"2026-02-11","equity":13758.80339306485867785,"benchmark":65155.46583485929715},{"day":"2026-02-13","equity":13969.14755572517547785,"benchmark":65916.09137131943235},{"day":"2026-02-15","equity":14089.89333188096367785,"benchmark":66380.83481564620315},{"day":"2026-02-17","equity":14197.26494279093867785,"benchmark":67079.03094716258175},{"day":"2026-02-19","equity":14442.70001373341067785,"benchmark":68090.61895654366015},{"day":"2026-02-21","equity":14737.23107305288747785,"benchmark":69226.70009086052635},{"day":"2026-02-23","equity":14780.02977378301347785,"benchmark":68927.15245288391495},{"day":"2026-02-25","equity":15035.83015749505987785,"benchmark":69867.91763897099255},{"day":"2026-02-27","equity":15392.15616740182827785,"benchmark":71320.70146046296095},{"day":"2026-03-01","equity":15325.35425189036287785,"benchmark":70854.52623846701635},{"day":"2026-03-03","equity":15269.82439829118227785,"benchmark":70183.79622477874095},{"day":"2026-03-05","equity":15249.57838060056467785,"benchmark":69872.57342593429715},{"day":"2026-03-07","equity":15410.03019570676842785,"benchmark":69843.05837477132135},{"day":"2026-03-09","equity":15495.65822694679242785,"benchmark":69886.13337307483055},{"day":"2026-03-11","equity":15529.62494401572042785,"benchmark":69577.41834083331215},{"day":"2026-03-13","equity":15898.75288068379720955,"benchmark":71419.15450235141375},{"day":"2026-03-15","equity":15912.24315312577920955,"benchmark":71368.08290948770415},{"day":"2026-03-17","equity":16097.81172414257320955,"benchmark":72558.57749117356295},{"day":"2026-03-19","equity":16144.38670752634120955,"benchmark":72310.91208228496955},{"day":"2026-03-21","equity":15957.81334660334320955,"benchmark":71213.69984312353755},{"day":"2026-03-23","equity":16073.78173119471720955,"benchmark":71322.19146506409635},{"day":"2026-03-25","equity":16172.56886526502720955,"benchmark":71374.57831471705715},{"day":"2026-03-27","equity":16167.47423883991520955,"benchmark":71211.84979202736435},{"day":"2026-03-29","equity":16297.76720754788720955,"benchmark":71780.21359067205795},{"day":"2026-03-31","equity":16161.21005028981951481,"benchmark":70865.40388207004035},{"day":"2026-04-02","equity":16205.94125833262751481,"benchmark":69749.32445443944055},{"day":"2026-04-04","equity":16256.68227153764951481,"benchmark":69299.83048964734195},{"day":"2026-04-06","equity":16533.66582338095551481,"benchmark":70588.34801154845435},{"day":"2026-04-08","equity":16615.48280740148506081,"benchmark":69683.81576313992455},{"day":"2026-04-10","equity":16888.35873780819826081,"benchmark":70675.89860466374295},{"day":"2026-04-12","equity":16810.44651501201826081,"benchmark":69864.71336326000295},{"day":"2026-04-14","equity":17105.33671685686619616,"benchmark":71466.66144371131135},{"day":"2026-04-16","equity":17327.13663733514309616,"benchmark":73391.09860443846415},{"day":"2026-04-18","equity":17245.20857310993129616,"benchmark":73003.70280722176355},{"day":"2026-04-20","equity":17276.09403592152529616,"benchmark":73336.31958625211995},{"day":"2026-04-22","equity":17210.05624215770689616,"benchmark":72997.71629657019735},{"day":"2026-04-24","equity":17147.75239626841020751,"benchmark":72721.94769280481315},{"day":"2026-04-26","equity":16899.85981640154068206,"benchmark":71582.97586798338995},{"day":"2026-04-28","equity":16923.44691125466298446,"benchmark":72162.26157689166495},{"day":"2026-04-30","equity":16928.98320100313251107,"benchmark":72433.38077343249695},{"day":"2026-05-02","equity":17129.68660286974691107,"benchmark":72778.97610361151495},{"day":"2026-05-04","equity":17204.33285275660371107,"benchmark":73233.73164413946195},{"day":"2026-05-06","equity":17116.16982201507321107,"benchmark":71123.07894352415475},{"day":"2026-05-08","equity":17221.02963154272021107,"benchmark":70937.16146444475035},{"day":"2026-05-10","equity":17375.91242579326969002,"benchmark":71120.44278322352875},{"day":"2026-05-12","equity":17443.00597343596969002,"benchmark":71070.42537642689035},{"day":"2026-05-14","equity":17556.14873397446926962,"benchmark":70852.68977910040815},{"day":"2026-05-16","equity":17588.63827490780207262,"benchmark":70826.28020105341435},{"day":"2026-05-18","equity":17566.33936660640707262,"benchmark":69880.86671526829255},{"day":"2026-05-20","equity":17658.49357732617707262,"benchmark":69879.79826391676575},{"day":"2026-05-22","equity":17687.96977552310707262,"benchmark":69680.10899442853575},{"day":"2026-05-24","equity":17818.47591698237707262,"benchmark":69735.75697852792455},{"day":"2026-05-26","equity":17935.23015184791207262,"benchmark":69275.49772270534595},{"day":"2026-05-28","equity":18071.98217917047207262,"benchmark":69986.79451947424315},{"day":"2026-05-30","equity":18247.74804860197484262,"benchmark":71447.34877145831735},{"day":"2026-06-01","equity":18176.62982234020566182,"benchmark":71628.24353561449015},{"day":"2026-06-03","equity":18431.89649255986832362,"benchmark":73972.60340029849955},{"day":"2026-06-05","equity":18563.03857990022202362,"benchmark":75512.68412261733615},{"day":"2026-06-07","equity":18739.78280603121902362,"benchmark":76625.80764351961415},{"day":"2026-06-09","equity":18972.16450236485222362,"benchmark":78036.22699460417395},{"day":"2026-06-11","equity":18992.95822733198120342,"benchmark":78355.93263353967655},{"day":"2026-06-13","equity":19083.01667344729075462,"benchmark":78584.84507408365695},{"day":"2026-06-15","equity":19326.23827669806155462,"benchmark":80006.92600105995015},{"day":"2026-06-17","equity":19306.50824254034495462,"benchmark":79637.21551034166075},{"day":"2026-06-19","equity":19529.36457308134253387,"benchmark":81092.30881264387255},{"day":"2026-06-21","equity":19830.37165622431173387,"benchmark":83561.54335835540335},{"day":"2026-06-23","equity":20243.03697621979223387,"benchmark":86106.87704861394875},{"day":"2026-06-25","equity":20410.55276695546933387,"benchmark":86953.96854482383155},{"day":"2026-06-27","equity":20621.13600131117173387,"benchmark":88171.35065006665095},{"day":"2026-06-29","equity":20870.14967399705733387,"benchmark":89648.27305062377715},{"day":"2026-07-01","equity":21364.55744697100013387,"benchmark":92153.36869512097775},{"day":"2026-07-03","equity":21466.52496873607413387,"benchmark":92644.11893792912055},{"day":"2026-07-05","equity":21662.84321807690453387,"benchmark":93858.58185760531575},{"day":"2026-07-07","equity":21888.48786968415773387,"benchmark":95275.62968543694035},{"day":"2026-07-09","equity":22125.54909902389309197,"benchmark":96447.31553300244775},{"day":"2026-07-11","equity":22758.12511853102074517,"benchmark":99877.07728884446015},{"day":"2026-07-13","equity":22927.39492132270154517,"benchmark":100667.64295221047495},{"day":"2026-07-15","equity":22850.05667433854654517,"benchmark":100932.14965813101595},{"day":"2026-07-17","equity":23100.11589475200194517,"benchmark":102405.48492150291595},{"day":"2026-07-19","equity":23271.20780499479599517,"benchmark":102853.19338052379275},{"day":"2026-07-21","equity":23427.15091874909879517,"benchmark":103356.13760867426215},{"day":"2026-07-23","equity":23545.66865224200439517,"benchmark":103424.11448331857015},{"day":"2026-07-25","equity":23586.67511177174139517,"benchmark":103463.44650255353655},{"day":"2026-07-27","equity":23814.607788893594528825,"benchmark":103656.28966019508595},{"day":"2026-07-29","equity":23886.500378014303328825,"benchmark":103105.93343270884155},{"day":"2026-07-31","equity":24409.374544763960928825,"benchmark":104231.53694307718955},{"day":"2026-08-02","equity":25030.740777143081528825,"benchmark":106653.41188426152895},{"day":"2026-08-04","equity":25659.949252665579128825,"benchmark":109277.97257045663135},{"day":"2026-08-06","equity":25947.688761934075928825,"benchmark":110107.50376639502215},{"day":"2026-08-08","equity":26918.027203424365328825,"benchmark":113946.12204312267275},{"day":"2026-08-10","equity":26979.038686066680128825,"benchmark":113676.22073977581735},{"day":"2026-08-12","equity":27158.911336132583128825,"benchmark":113485.94754396056715},{"day":"2026-08-14","equity":27684.370649172851728825,"benchmark":115282.70812734407615},{"day":"2026-08-16","equity":28382.558725264965128825,"benchmark":118373.01964887169855},{"day":"2026-08-18","equity":28668.337544229647728825,"benchmark":119384.93684138753615},{"day":"2026-08-20","equity":29299.321710947655528825,"benchmark":121730.22633837126495},{"day":"2026-08-22","equity":30059.662327112346728825,"benchmark":124053.28251272895935},{"day":"2026-08-24","equity":30274.385514871649128825,"benchmark":125016.29243581108435},{"day":"2026-08-26","equity":30927.101504461219328825,"benchmark":127765.39124902104735},{"day":"2026-08-28","equity":31523.864759544958128825,"benchmark":129812.22659229293275},{"day":"2026-08-30","equity":31262.430108882055128825,"benchmark":128663.45852662609075},{"day":"2026-09-01","equity":31113.842156741730128825,"benchmark":127021.54793817295875},{"day":"2026-09-03","equity":31084.439489055466128825,"benchmark":125981.39329733101895},{"day":"2026-09-05","equity":30399.978274306086928825,"benchmark":122730.51980725733275},{"day":"2026-09-07","equity":30958.169752192464365925,"benchmark":125585.43717181814375},{"day":"2026-09-09","equity":30907.930340058061715925,"benchmark":124773.89407966497415},{"day":"2026-09-11","equity":31077.964672794580728225,"benchmark":126216.96953208298935},{"day":"2026-09-13","equity":31055.216619649322622390,"benchmark":125116.15986791909935},{"day":"2026-09-15","equity":31074.612491984098771440,"benchmark":122744.56917757469655},{"day":"2026-09-17","equity":31680.025162498979571440,"benchmark":124024.96461161439015},{"day":"2026-09-19","equity":31702.895939540056371440,"benchmark":122212.45282830319835},{"day":"2026-09-21","equity":31756.662761566846158940,"benchmark":121380.17124314854415},{"day":"2026-09-23","equity":31586.916217063849758940,"benchmark":120188.00964849802935},{"day":"2026-09-25","equity":31586.076180307703801240,"benchmark":120221.93050599439595},{"day":"2026-09-27","equity":31695.314769411381801240,"benchmark":121017.68031943879735},{"day":"2026-09-29","equity":32184.566922701161001240,"benchmark":123579.23978335586475},{"day":"2026-10-01","equity":32424.908232415315213240,"benchmark":123670.04465137336295},{"day":"2026-10-03","equity":32751.745897483681481890,"benchmark":125676.53845875914315},{"day":"2026-10-05","equity":33119.175750192391481890,"benchmark":128259.12630929546135},{"day":"2026-10-07","equity":33414.439563237443031890,"benchmark":128780.97086412745535},{"day":"2026-10-09","equity":33704.701333109757831890,"benchmark":130381.25696189837775},{"day":"2026-10-11","equity":34017.033539621115004690,"benchmark":132401.06607658030055},{"day":"2026-10-13","equity":33494.543062184583804690,"benchmark":128154.69898270005135},{"day":"2026-10-15","equity":33252.067254872249404690,"benchmark":126644.32517228572655},{"day":"2026-10-17","equity":33332.733690299286404690,"benchmark":127358.69077860059395},{"day":"2026-10-19","equity":33609.760369772168546690,"benchmark":128610.81863514657875},{"day":"2026-10-21","equity":33330.325202618100346690,"benchmark":127641.26225877472295},{"day":"2026-10-23","equity":32932.798850091341346690,"benchmark":125993.70728521449115},{"day":"2026-10-25","equity":32958.308881732541720690,"benchmark":125262.54207487285955},{"day":"2026-10-27","equity":32914.311254443664707340,"benchmark":124783.67349684385555},{"day":"2026-10-29","equity":33087.452976705596507340,"benchmark":125758.62566102109655},{"day":"2026-10-31","equity":33149.619241713549607340,"benchmark":126867.14122513152295},{"day":"2026-11-02","equity":33325.386429483553207340,"benchmark":127058.32392197621955},{"day":"2026-11-04","equity":33472.516561357982157340,"benchmark":127521.56626038677935},{"day":"2026-11-06","equity":33668.808903553547057340,"benchmark":125962.61604378853715},{"day":"2026-11-08","equity":33655.720639629906505840,"benchmark":124536.08778082201835},{"day":"2026-11-10","equity":33690.728380117782208090,"benchmark":124145.60374689314435},{"day":"2026-11-12","equity":33839.853395209096808090,"benchmark":122898.53336356099815},{"day":"2026-11-14","equity":34050.723490792246408090,"benchmark":124413.92049414531535},{"day":"2026-11-16","equity":34103.781677201092208090,"benchmark":123383.10639854423875},{"day":"2026-11-18","equity":34168.508453027927806290,"benchmark":121298.58013017927155},{"day":"2026-11-20","equity":34373.416954632555406290,"benchmark":121505.82878291667395},{"day":"2026-11-22","equity":34377.334573532727006290,"benchmark":120600.40662174475555},{"day":"2026-11-24","equity":34522.374780238343406290,"benchmark":120479.64587317970195},{"day":"2026-11-26","equity":34690.458565700825382090,"benchmark":120850.18276023420915},{"day":"2026-11-28","equity":34941.714128372194120390,"benchmark":122508.94586031425055},{"day":"2026-11-30","equity":35483.122287310127320390,"benchmark":125870.76061541132115},{"day":"2026-12-02","equity":35934.011274717092320390,"benchmark":128965.72138668877635},{"day":"2026-12-04","equity":36255.580333776265420390,"benchmark":130679.20919237131535},{"day":"2026-12-06","equity":36495.486917315798220390,"benchmark":132082.77971864639375},{"day":"2026-12-08","equity":36935.449446736623820390,"benchmark":134445.07409990212975},{"day":"2026-12-10","equity":36977.869213335936303640,"benchmark":134397.01236399036135},{"day":"2026-12-12","equity":37596.690402627719703640,"benchmark":138151.56912202321615},{"day":"2026-12-14","equity":38000.751000539314103640,"benchmark":140131.00991486140755},{"day":"2026-12-16","equity":38293.262802759648703640,"benchmark":142246.99966869658015},{"day":"2026-12-18","equity":38631.700085154974636940,"benchmark":143721.40509693710495},{"day":"2026-12-20","equity":39140.765593687094636940,"benchmark":147046.44836621112635},{"day":"2026-12-22","equity":39665.574234193239145540,"benchmark":150832.28011990058395},{"day":"2026-12-24","equity":40030.962464816715745540,"benchmark":152878.11720832438695},{"day":"2026-12-26","equity":40619.553535464985235540,"benchmark":155675.25974011339755},{"day":"2026-12-28","equity":41626.681037068493435540,"benchmark":161002.49774276756795},{"day":"2026-12-30","equity":42541.274292685601435540,"benchmark":166223.07263782288135},{"day":"2026-12-31","equity":42515.803080578265635540,"benchmark":166213.82941437167155}],"trades":[{"symbol":"ETHEUR","opened":"2025-12-02","closed":"2026-03-31","invested":2525.25302952470385,"result":1293.63305529843509436,"fees":12.70358438534828334,"is_closed":true},{"symbol":"SOLEUR","opened":"2025-12-02","closed":"2026-02-01","invested":2139.94446689278905,"result":359.31426831618233835,"fees":9.28842347328251475,"is_closed":true},{"symbol":"BTCEUR","opened":"2025-12-06","closed":"2025-12-17","invested":966.9016036372200,"result":17.2627795034531893,"fees":3.9060765201816007,"is_closed":true},{"symbol":"BTCEUR","opened":"2025-12-23","closed":"2026-04-30","invested":3661.1715494878743,"result":4792.76333458192586671,"fees":24.26409637366472689,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-02-18","closed":"2026-02-18","invested":737.5047558864963,"result":-7.3652876625884,"fees":2.9382148589150926,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-03-13","closed":"2026-03-13","invested":809.88588274858875,"result":-11.6521677172507058,"fees":3.2194385290870333,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-03-30","closed":"2026-03-30","invested":452.097827129592,"result":-6.8346288865206391,"fees":1.7965066727823731,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-07","closed":"2026-04-07","invested":925.38879458571,"result":-17.078543965270454,"fees":3.671038612458874,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-14","closed":"2026-04-14","invested":1032.59890845080865,"result":-19.79916632704006465,"fees":4.09485661875285695,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-04-16","closed":"2026-07-26","invested":3106.4736049459869,"result":2527.533067917739775055,"fees":17.503541744689021245,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-21","closed":"2026-04-23","invested":946.1143749999114,"result":-8.21434883931708865,"fees":3.77178792066233645,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-26","closed":"2026-04-26","invested":929.62803402544965,"result":-22.66318437136552545,"fees":3.67682089701699975,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-04-29","closed":"2026-05-09","invested":1778.6483641888233,"result":-8.23413213817702105,"fees":7.10522104110439265,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-16","closed":"2026-05-16","invested":928.21153614565725,"result":-13.258833591642197,"fees":3.6899956224997615,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-29","closed":"2026-05-29","invested":1021.740252560871,"result":-11.99422577459223,"fees":4.067019636957972,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-05-31","closed":"2026-06-01","invested":2051.1412991381088,"result":-32.8830195609141808,"fees":8.1468883689719984,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-01","closed":"2026-06-10","invested":1601.0717820345057,"result":5.9687448561770798,"fees":6.4226656620463316,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-06-03","closed":"2026-09-13","invested":5032.7243775934785,"result":6081.314215540833731265,"fees":32.338071186317843235,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-12","closed":"2026-06-13","invested":431.051677019445,"result":-6.5323979118124488,"fees":1.7128433923307388,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-19","closed":"2026-06-19","invested":449.5768145980644,"result":-6.57554444222122075,"fees":1.78693172570082455,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-06-22","closed":"2026-07-11","invested":3866.7258151488198,"result":103.9273106959738113,"fees":15.6906723233733783,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-07-16","closed":"2026-10-27","invested":5991.30226706960655,"result":7444.26125114625108465,"fees":38.90758152455175345,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-08","closed":"2026-09-10","invested":1498.47415488021705,"result":-11.7036375850578377,"fees":5.9764483444200718,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-12","closed":"2026-09-15","invested":2984.47651750389570,"result":-36.44889461783035095,"fees":11.87682402275541735,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-20","closed":"2026-09-20","invested":3155.31754937952,"result":-54.2064478446706125,"fees":12.5252866048409025,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-09-23","closed":"2026-10-03","invested":9512.0520297582840,"result":-171.18187986118558865,"fees":37.74328271662498165,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-09-29","closed":"2026-09-30","invested":1473.7436961930984,"result":-12.4384579958666972,"fees":5.8759548036030940,"is_closed":true},{"symbol":"SOLEUR","opened":"2026-10-06","invested":6620.50213234909065,"result":4821.8922917852374611,"fees":18.3940101066035202,"is_closed":false},{"symbol":"ETHEUR","opened":"2026-10-19","closed":"2026-10-19","invested":817.9055435299662,"result":-15.824663053019058,"fees":3.2431876010417904,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-10-24","closed":"2026-10-24","invested":1590.9223194969345,"result":-31.8819850580846652,"fees":6.3061739665266342,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-10-30","closed":"2026-11-07","invested":3280.49970150898665,"result":-48.9276451092462015,"fees":13.0370957084282748,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-10","closed":"2026-11-10","invested":1707.9645829120992,"result":-36.19072474132989775,"fees":6.76617737859127115,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-17","closed":"2026-11-17","invested":1738.4223361905054,"result":-26.9114401858740018,"fees":6.9067262275005126,"is_closed":true},{"symbol":"ETHEUR","opened":"2026-11-23","invested":10969.61254438147095,"result":5861.4540489166785758,"fees":25.3743583581669161,"is_closed":false},{"symbol":"BTCEUR","opened":"2026-12-01","closed":"2026-12-10","invested":3451.1493644770755,"result":20.78856397244178325,"fees":13.86009016873274275,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-17","closed":"2026-12-17","invested":1958.645306768766,"result":-20.0480974830236667,"fees":7.8022549608035487,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-20","closed":"2026-12-21","invested":5913.3301752726894,"result":-112.1289640601285914,"fees":23.4523140804302702,"is_closed":true},{"symbol":"BTCEUR","opened":"2026-12-22","invested":10186.7991231563109,"result":-63.331533169034810,"fees":31.9573984813763318,"is_closed":false}],"notes":{"adjusted:crypto_regime_below_average":11,"adjusted:trade_risk_limit":98,"adjusted:crypto_regime_high_volatility":36,"residue_written_off":35,"below_min_notional":2},"computed_at":"2027-01-05T02:10:00+00:00","seconds":0,"expected_slippage_bp":5,"expected_path_p5":[-0.0033,-0.0023,-0.0023,-0.0032,-0.0031,-0.0039,-0.0041,-0.0039,-0.0044,-0.0037,-0.0031,-0.0018,-0.002,-0.0017,-0.0012,-0.0006,-0.0006,-0.0006,-0.0007,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.0006,0.0006,0.001,0.001,0.0025,0.0039,0.0051,0.0061,0.0065,0.006,0.0071,0.0071,0.0085,0.0084,0.009,0.0093,0.0095,0.0095,0.0103,0.0119,0.0124,0.0137,0.0145,0.0145,0.0151,0.0163,0.0161,0.0161,0.0169,0.0181,0.0183,0.0186,0.0206,0.0215,0.0215,0.0219,0.0219,0.0223,0.0242,0.0247,0.0248,0.0259,0.0301,0.0301,0.0304,0.0315,0.0318,0.0319,0.0337,0.0341,0.0363,0.0373,0.0389,0.0396,0.0406,0.0412,0.0412,0.0426,0.0432,0.0445,0.0453,0.0463,0.046,0.0465,0.0479,0.0503,0.0515,0.0553,0.0563,0.0577,0.0586,0.0587,0.0618,0.0623,0.0639,0.0641,0.0705,0.0697,0.0716,0.0716,0.0724,0.0728,0.0728,0.0734,0.0735,0.074,0.0749,0.0752,0.0757,0.0775,0.0782,0.0788,0.0805,0.0805,0.0826,0.0833,0.0849,0.0857,0.0885,0.0895,0.092,0.0906,0.092,0.0936,0.0961,0.0959,0.0977,0.0985,0.0995,0.1002,0.1011,0.1033,0.1051,0.1051,0.1075,0.1076,0.1082,0.1082,0.1098,0.1094,0.1109,0.1109,0.1113,0.1113,0.112,0.1165,0.119,0.12,0.1207,0.1205,0.1231,0.1249,0.1249,0.1253,0.1275,0.1275,0.1306,0.1323,0.1362,0.1392,0.1399,0.1412,0.1414,0.1414,0.1419,0.1427,0.1452,0.1495,0.1483,0.1514,0.1546,0.1556,0.1571,0.1571,0.1573,0.1596,0.1619,0.1623,0.1637,0.1659,0.1661,0.1676,0.17,0.1709,0.1717,0.1726,0.174,0.1788,0.1805,0.1841,0.1855,0.1871,0.1906,0.1908,0.1922,0.1951,0.1973,0.1964,0.1964,0.1973,0.1973,0.1973,0.1982,0.1996,0.1998,0.2003,0.2005,0.2005,0.2018,0.2028,0.2036,0.2063,0.2079,0.2079,0.2095,0.2104,0.2119,0.2111,0.2145,0.2149,0.215,0.215,0.2152,0.2152,0.2162,0.2156,0.2174,0.2202,0.2227,0.2229,0.2276,0.2277,0.2303,0.2299,0.234,0.2368,0.2384,0.2422,0.2436,0.2481,0.2468,0.2461,0.2478,0.2516,0.2536,0.2538,0.2577,0.2576,0.2578,0.2599,0.2637,0.2648,0.2648,0.268,0.2712,0.2721,0.2721,0.2729,0.2751,0.2755,0.2756,0.2803,0.2875,0.2899,0.29,0.29,0.29,0.2934,0.2934,0.2948,0.2964,0.2992,0.3099,0.3114,0.3088,0.3123,0.3129,0.3134,0.3146,0.3147,0.3168,0.321,0.3221,0.3221,0.3225,0.3239,0.3261,0.3275,0.33,0.3315,0.3302],"judged":"coin_vol=12;max_stop=15"} \ No newline at end of file diff --git a/tests/Anubis.Tests/Fixtures/golden/sma_cross.report.json b/tests/Anubis.Tests/Fixtures/golden/sma_cross.report.json new file mode 100644 index 0000000..e37a987 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/golden/sma_cross.report.json @@ -0,0 +1 @@ +{"trial_id":"6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12","strategy":"sma_cross","strategy_name":"Incrocio di medie (esempio)","strategy_version":"1","plan_hash":"990e63ec6f56622482e7a01e5c394a50b7c4ab71e49ae5648525cacf566ae1b1","data_fingerprint":"4d526d1396e3809f960d671c57f9ca3017f7cdc7198fa4781519169ba9630644","currency":"EUR","periods_per_year":365,"sessions":1349,"instruments":[{"symbol":"BTC-EUR","venue":"okx","first":"2018-01-01","last":"2022-02-08","bars":1500,"actions":0,"source":""}],"chosen":"fast=10;slow=50","metrics":{"from":"2018-06-01","to":"2022-02-08","initial_capital":10000,"final_equity":6285.4325248044152,"total_return":-0.3714567475195585,"annual_return":-0.11822555620871933,"volatility":0.35324063837526276,"sharpe":-0.17944546690357913,"daily_sharpe":-0.009392605017770376,"max_drawdown":0.6890295232626155,"drawdown_peak":"2018-12-05","drawdown_low":"2020-08-01","trades":16,"winners":7,"profit_factor":0.2622557627792188,"average_win":255.25905750743714285714285714,"average_loss":-757.02749255855977777777777778,"fees":409.512752353050,"exposure":0.40622683231406903,"years":[{"year":2018,"start":10000,"end":8685.755700826393,"result":-1314.244299173607,"return":-0.1314244299173607},{"year":2019,"start":8685.755700826393,"end":4374.272033425322,"result":-4311.483667401071,"return":-0.4963855553744001},{"year":2020,"start":4374.272033425322,"end":4271.497995114922,"result":-102.774038310400,"return":-0.02349511816482097},{"year":2021,"start":4271.497995114922,"end":5482.2471804670268,"result":1210.7491853521048,"return":0.2834483796402978},{"year":2022,"start":5482.2471804670268,"end":6285.4325248044152,"result":803.1853443373884,"return":0.14650659080077566}],"net_result":-3714.5674751955848,"win_rate":0.4375},"benchmark":{"from":"2018-06-01","to":"2022-02-08","initial_capital":10000,"final_equity":1428.644570017173,"total_return":-0.8571355429982828,"annual_return":-0.40977062822712385,"volatility":0.5265283233161793,"sharpe":-0.7366093915972111,"daily_sharpe":-0.038555897716660306,"max_drawdown":0.9147532355023699,"drawdown_peak":"2018-06-10","drawdown_low":"2021-11-10","trades":0,"winners":0,"average_win":0,"average_loss":0,"fees":19.91001444273,"exposure":0.9753449358029199,"years":[{"year":2018,"start":10000,"end":6350.615563974605,"result":-3649.384436025395,"return":-0.36493844360253946},{"year":2019,"start":6350.615563974605,"end":2391.41269070224,"result":-3959.202873272365,"return":-0.6234360800757482},{"year":2020,"start":2391.41269070224,"end":1717.725401513074,"result":-673.687289189166,"return":-0.28171101199238735},{"year":2021,"start":1717.725401513074,"end":1251.834328409172,"result":-465.891073103902,"return":-0.27122558279310394},{"year":2022,"start":1251.834328409172,"end":1428.644570017173,"result":176.810241608001,"return":0.14124092748973505}],"net_result":-8571.355429982827,"win_rate":0},"costs":[{"multiplier":1,"net_result":-3714.5674751955848,"total_return":-0.3714567475195585,"sharpe":-0.17944546690357913,"max_drawdown":0.6890295232626155,"fees":409.512752353050},{"multiplier":2,"net_result":-4213.435391198960,"total_return":-0.42134353911989597,"sharpe":-0.24253938590781685,"max_drawdown":0.701247870371674,"fees":793.032851375020},{"multiplier":3,"net_result":-4673.1546177568774,"total_return":-0.4673154617756877,"sharpe":-0.30535037551200916,"max_drawdown":0.7129997025296625,"fees":1152.407422350312}],"variants":[{"parameters":"fast=10;slow=50","sharpe":-0.009392605017770376,"plateau_score":-0.014421152695077044,"net_result":-3714.5674751955848,"max_drawdown":0.6890295232626155,"trades":16,"chosen":true,"outside_grid":false},{"parameters":"fast=10;slow=100","sharpe":-0.012439903845665106,"plateau_score":-0.018249437198971447,"net_result":-3759.8615550387032,"max_drawdown":0.49358888719810523,"trades":9,"chosen":false,"outside_grid":false},{"parameters":"fast=10;slow=150","sharpe":-0.01960343681733535,"plateau_score":-0.01960343681733535,"net_result":-4456.3707526755608,"max_drawdown":0.5566227548691635,"trades":7,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=50","sharpe":-0.022543401299485562,"plateau_score":-0.022543401299485562,"net_result":-5457.5870981397256,"max_drawdown":0.6584030293650209,"trades":16,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=100","sharpe":-0.013308700617387134,"plateau_score":-0.024154091365139782,"net_result":-3932.8860477973112,"max_drawdown":0.5226121704934336,"trades":7,"chosen":false,"outside_grid":false},{"parameters":"fast=20;slow=150","sharpe":-0.03220857559618516,"plateau_score":-0.03220857559618516,"net_result":-5699.2247211905662,"max_drawdown":0.6560257168475645,"trades":6,"chosen":false,"outside_grid":false},{"parameters":"fast=30;slow=50","sharpe":-0.02809129797366409,"plateau_score":-0.02809129797366409,"net_result":-6052.8336160531412,"max_drawdown":0.7113621829037103,"trades":16,"chosen":false,"outside_grid":false},{"parameters":"fast=30;slow=100","sharpe":-0.03083313673334694,"plateau_score":-0.03083313673334694,"net_result":-5920.8577557581702,"max_drawdown":0.6737518382530776,"trades":8,"chosen":false,"outside_grid":false},{"parameters":"fast=30;slow=150","sharpe":-0.04896576438541832,"plateau_score":-0.04896576438541832,"net_result":-6955.4214078149296,"max_drawdown":0.7564958245704758,"trades":6,"chosen":false,"outside_grid":false}],"walk_forward":{"windows":[{"window":1,"train_from":"2018-06-02","train_to":"2019-02-11","test_from":"2019-02-26","test_to":"2019-11-21","chosen":"fast=30;slow=50","return":-0.3849912838042354,"sharpe":-0.12350764461411874},{"window":2,"train_from":"2018-06-02","train_to":"2019-11-07","test_from":"2019-11-22","test_to":"2020-08-16","chosen":"fast=30;slow=150","return":-0.3100318094054273,"sharpe":-0.1282083929756568},{"window":3,"train_from":"2018-06-02","train_to":"2020-08-02","test_from":"2020-08-17","test_to":"2021-05-12","chosen":"fast=20;slow=150","return":0.013007846478391372,"sharpe":0.013572013555750492},{"window":4,"train_from":"2018-06-02","train_to":"2021-04-28","test_from":"2021-05-13","test_to":"2022-02-08","chosen":"fast=10;slow=150","return":-0.19617302222488264,"sharpe":-0.02629689959328206}],"purge":14,"return":-0.6544700264303343,"sharpe":-0.04564918977670254},"combinatorial":{"groups":6,"test_groups":2,"splits":15,"purge":14,"embargo":14,"path_sharpes":[-0.035594575917200756,-0.035594575917200756,-0.035594575917200756,0.00023664262558358172,-0.029302886395026248],"mean_sharpe":-0.027169994304208987,"worst_sharpe":-0.035594575917200756,"positive_share":0.2},"overfitting":{"groups":16,"combinations":12870,"variants":9,"probability":0.6278166278166278},"deflated_sharpe":{"sharpe":-0.009392605017770376,"benchmark":0.5824850053822396,"observations":1348,"skewness":0.13579462415443572,"kurtosis":7.4475714108695845,"trials":27,"sharpe_variance":0.08236606488858376,"value":8.730517376249099E-105},"trials_counted":27,"look_ahead":{"cutoffs":["2018-12-10","2019-06-21","2019-12-30","2020-07-10","2021-01-18","2021-07-30"],"decisions":4047,"changed":0,"examples":[],"passed":true},"checks":[{"key":"double_costs","name":"Risultato netto con costi doppi","value":-4213.43539119896,"comparison":"\u003E","threshold":0,"unit":"money","passed":false},{"key":"deflated_sharpe","name":"Deflated Sharpe Ratio","value":8.730517376249099E-105,"comparison":"\u2265","threshold":0.9,"unit":"ratio","passed":false},{"key":"overfitting","name":"Probabilit\u00E0 di sovra-adattamento (PBO)","value":0.6278166278166278,"comparison":"\u2264","threshold":0.4,"unit":"ratio","passed":false},{"key":"drawdown","name":"Calo massimo","value":0.6890295232626155,"comparison":"\u2264","threshold":0.25,"unit":"percent","passed":false},{"key":"look_ahead","name":"Decisioni cambiate aggiungendo dati successivi","value":0,"comparison":"=","threshold":0,"unit":"count","passed":true}],"passed":false,"limitations":["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\u0027apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.","Sharpe e volatilit\u00E0 sono calcolati senza tasso privo di rischio.","Strategia d\u0027esempio: correttivi e limiti di rischio non si applicano, ogni intenzione passa cos\u00EC com\u0027\u00E8.","L\u0027incrocio di medie \u00E8 una strategia d\u0027esempio per provare il laboratorio, non una delle strategie di base."],"curve":[{"day":"2018-06-01","equity":10000,"benchmark":10000},{"day":"2018-06-04","equity":9865.642387051994,"benchmark":9866.246899079142},{"day":"2018-06-07","equity":10228.213059281468,"benchmark":10026.453843356087},{"day":"2018-06-10","equity":10228.213059281468,"benchmark":10402.563861139539},{"day":"2018-06-13","equity":10228.213059281468,"benchmark":9756.891094537543},{"day":"2018-06-16","equity":10228.213059281468,"benchmark":9480.524818804972},{"day":"2018-06-19","equity":10228.213059281468,"benchmark":9906.377437060839},{"day":"2018-06-22","equity":10228.213059281468,"benchmark":9518.618902869144},{"day":"2018-06-25","equity":10228.213059281468,"benchmark":9337.771170015963},{"day":"2018-06-28","equity":10228.213059281468,"benchmark":9105.905839455047},{"day":"2018-07-01","equity":10228.213059281468,"benchmark":8961.430944398356},{"day":"2018-07-04","equity":10228.213059281468,"benchmark":8480.79948659056},{"day":"2018-07-07","equity":10228.213059281468,"benchmark":8920.960407153907},{"day":"2018-07-10","equity":10228.213059281468,"benchmark":8129.835247614808},{"day":"2018-07-13","equity":10228.213059281468,"benchmark":8599.777978599838},{"day":"2018-07-16","equity":10228.213059281468,"benchmark":8610.516288648422},{"day":"2018-07-19","equity":10228.213059281468,"benchmark":8601.385891779936},{"day":"2018-07-22","equity":10228.213059281468,"benchmark":8774.133850529848},{"day":"2018-07-25","equity":10228.213059281468,"benchmark":8854.780967322825},{"day":"2018-07-28","equity":10228.213059281468,"benchmark":8894.911505304522},{"day":"2018-07-31","equity":10228.213059281468,"benchmark":8627.997917408254},{"day":"2018-08-03","equity":10228.213059281468,"benchmark":8386.637399103191},{"day":"2018-08-06","equity":10228.213059281468,"benchmark":7413.764925328213},{"day":"2018-08-09","equity":10228.213059281468,"benchmark":6981.987111587095},{"day":"2018-08-12","equity":10228.213059281468,"benchmark":7107.20246507248},{"day":"2018-08-15","equity":10228.213059281468,"benchmark":6705.808543780835},{"day":"2018-08-18","equity":10228.213059281468,"benchmark":7041.270941370488},{"day":"2018-08-21","equity":10228.213059281468,"benchmark":7371.16230937359},{"day":"2018-08-24","equity":10228.213059281468,"benchmark":7386.281651589093},{"day":"2018-08-27","equity":10228.213059281468,"benchmark":7256.851723909178},{"day":"2018-08-30","equity":10228.213059281468,"benchmark":6885.143988246567},{"day":"2018-09-02","equity":10228.213059281468,"benchmark":6765.216331628773},{"day":"2018-09-05","equity":10228.213059281468,"benchmark":6533.340376090896},{"day":"2018-09-08","equity":10228.213059281468,"benchmark":6603.4368907616},{"day":"2018-09-11","equity":10228.213059281468,"benchmark":5959.676620012584},{"day":"2018-09-14","equity":10228.213059281468,"benchmark":6249.040784227445},{"day":"2018-09-17","equity":10228.213059281468,"benchmark":5877.000132620056},{"day":"2018-09-20","equity":10228.213059281468,"benchmark":5865.982031511499},{"day":"2018-09-23","equity":10228.213059281468,"benchmark":5773.700564946227},{"day":"2018-09-26","equity":10228.213059281468,"benchmark":5868.439942848477},{"day":"2018-09-29","equity":10228.213059281468,"benchmark":5674.179947411527},{"day":"2018-10-02","equity":10228.213059281468,"benchmark":5455.879170770821},{"day":"2018-10-05","equity":10228.213059281468,"benchmark":5487.835559810522},{"day":"2018-10-08","equity":10228.213059281468,"benchmark":5404.383449099841},{"day":"2018-10-11","equity":10228.213059281468,"benchmark":5751.52623802862},{"day":"2018-10-14","equity":10228.213059281468,"benchmark":5916.0008813849},{"day":"2018-10-17","equity":10228.213059281468,"benchmark":5909.827769770559},{"day":"2018-10-20","equity":10228.213059281468,"benchmark":5960.735576049697},{"day":"2018-10-23","equity":10306.8413997189016,"benchmark":5955.681628675248},{"day":"2018-10-26","equity":10275.5300206176136,"benchmark":5937.725417611158},{"day":"2018-10-29","equity":10287.7272540939536,"benchmark":5944.720194110483},{"day":"2018-11-01","equity":9223.671484690144,"benchmark":5334.513600604305},{"day":"2018-11-04","equity":10097.6295104811832,"benchmark":5835.704388831636},{"day":"2018-11-07","equity":9259.431769394940,"benchmark":5683.405969072662},{"day":"2018-11-10","equity":9259.431769394940,"benchmark":5679.690768795299},{"day":"2018-11-13","equity":9259.431769394940,"benchmark":5645.163135331036},{"day":"2018-11-16","equity":9259.431769394940,"benchmark":5689.681788797626},{"day":"2018-11-19","equity":9351.924491237122,"benchmark":5783.638460063749},{"day":"2018-11-22","equity":9222.3455067312076,"benchmark":5798.871135366836},{"day":"2018-11-25","equity":10254.2869390348954,"benchmark":6442.705780954579},{"day":"2018-11-28","equity":10257.5793606376114,"benchmark":6444.759943167039},{"day":"2018-12-01","equity":9662.349270989350,"benchmark":6073.39220676718},{"day":"2018-12-04","equity":10435.216859282080,"benchmark":6555.58907784723},{"day":"2018-12-07","equity":10391.4617114997784,"benchmark":6528.289970375434},{"day":"2018-12-10","equity":10077.0638313852514,"benchmark":6332.135187380439},{"day":"2018-12-13","equity":9650.769029490142,"benchmark":6066.1672224337},{"day":"2018-12-16","equity":9277.1189137046674,"benchmark":5833.044602932399},{"day":"2018-12-19","equity":8863.4715520351636,"benchmark":5574.967454208696},{"day":"2018-12-22","equity":8841.280294032886,"benchmark":5892.576348844882},{"day":"2018-12-25","equity":8841.280294032886,"benchmark":6079.196985846873},{"day":"2018-12-28","equity":8841.280294032886,"benchmark":6330.962898255742},{"day":"2018-12-31","equity":8685.755700826393,"benchmark":6350.615563974605},{"day":"2019-01-03","equity":8068.6644097870594,"benchmark":5902.624035391001},{"day":"2019-01-06","equity":7628.9310060902848,"benchmark":5583.389519279782},{"day":"2019-01-09","equity":7609.846240512886,"benchmark":5616.858196706932},{"day":"2019-01-12","equity":7609.846240512886,"benchmark":5713.690695070499},{"day":"2019-01-15","equity":7609.846240512886,"benchmark":5741.50334309541},{"day":"2019-01-18","equity":7609.846240512886,"benchmark":6246.267665240624},{"day":"2019-01-21","equity":7609.846240512886,"benchmark":6416.447921224961},{"day":"2019-01-24","equity":7551.8286882409102,"benchmark":6383.737158821029},{"day":"2019-01-27","equity":7344.6073827874316,"benchmark":6209.802744310472},{"day":"2019-01-30","equity":7000.7139406447464,"benchmark":5921.150453551998},{"day":"2019-02-02","equity":7478.1824447234698,"benchmark":6321.921042861931},{"day":"2019-02-05","equity":7424.7853316426168,"benchmark":6277.101348381446},{"day":"2019-02-08","equity":7901.1525598213716,"benchmark":6676.947564695772},{"day":"2019-02-11","equity":7747.033006096264,"benchmark":6547.58492853661},{"day":"2019-02-14","equity":7297.2525190887818,"benchmark":6170.054705499371},{"day":"2019-02-17","equity":7448.8530624220072,"benchmark":6297.302971243294},{"day":"2019-02-20","equity":7215.0998686198598,"benchmark":6101.098605022481},{"day":"2019-02-23","equity":7173.5383068777498,"benchmark":6066.213264000531},{"day":"2019-02-26","equity":7004.381752979626,"benchmark":5838.845840353105},{"day":"2019-03-01","equity":7004.381752979626,"benchmark":5997.63612103525},{"day":"2019-03-04","equity":7004.381752979626,"benchmark":5644.60355321109},{"day":"2019-03-07","equity":7004.381752979626,"benchmark":5165.250634297601},{"day":"2019-03-10","equity":7004.381752979626,"benchmark":5156.261903788595},{"day":"2019-03-13","equity":7004.381752979626,"benchmark":5043.474231688593},{"day":"2019-03-16","equity":7004.381752979626,"benchmark":5491.915550963546},{"day":"2019-03-19","equity":7004.381752979626,"benchmark":5214.660318825238},{"day":"2019-03-22","equity":7004.381752979626,"benchmark":5130.138627100483},{"day":"2019-03-25","equity":7004.381752979626,"benchmark":4785.283749877306},{"day":"2019-03-28","equity":7004.381752979626,"benchmark":4854.817140769077},{"day":"2019-03-31","equity":7004.381752979626,"benchmark":4749.789243509592},{"day":"2019-04-03","equity":7004.381752979626,"benchmark":4660.620895193893},{"day":"2019-04-06","equity":7004.381752979626,"benchmark":5065.662725242148},{"day":"2019-04-09","equity":7004.381752979626,"benchmark":4864.723160955716},{"day":"2019-04-12","equity":7004.381752979626,"benchmark":4725.373046453214},{"day":"2019-04-15","equity":7004.381752979626,"benchmark":4730.391577237793},{"day":"2019-04-18","equity":7004.381752979626,"benchmark":4458.505500123777},{"day":"2019-04-21","equity":7004.381752979626,"benchmark":4342.781792723552},{"day":"2019-04-24","equity":7004.381752979626,"benchmark":4598.061030847525},{"day":"2019-04-27","equity":7004.381752979626,"benchmark":4484.334819115968},{"day":"2019-04-30","equity":7004.381752979626,"benchmark":4471.259014135964},{"day":"2019-05-03","equity":7004.381752979626,"benchmark":4041.159946754684},{"day":"2019-05-06","equity":7004.381752979626,"benchmark":3718.266896909894},{"day":"2019-05-09","equity":7004.381752979626,"benchmark":3710.687746677714},{"day":"2019-05-12","equity":7004.381752979626,"benchmark":3765.866793695174},{"day":"2019-05-15","equity":7004.381752979626,"benchmark":3732.699157281919},{"day":"2019-05-18","equity":7004.381752979626,"benchmark":3640.810814864204},{"day":"2019-05-21","equity":7004.381752979626,"benchmark":3765.32846152915},{"day":"2019-05-24","equity":7004.381752979626,"benchmark":3823.829584676416},{"day":"2019-05-27","equity":7004.381752979626,"benchmark":3830.186862558081},{"day":"2019-05-30","equity":7004.381752979626,"benchmark":3531.773759631435},{"day":"2019-06-02","equity":7004.381752979626,"benchmark":3527.5060605521},{"day":"2019-06-05","equity":7004.381752979626,"benchmark":3660.573272011664},{"day":"2019-06-08","equity":7004.381752979626,"benchmark":3662.01826887836},{"day":"2019-06-11","equity":7004.381752979626,"benchmark":3647.968507676931},{"day":"2019-06-14","equity":7004.381752979626,"benchmark":3467.361607634866},{"day":"2019-06-17","equity":7004.381752979626,"benchmark":3525.154398984732},{"day":"2019-06-20","equity":7004.381752979626,"benchmark":3481.811576301826},{"day":"2019-06-23","equity":7004.381752979626,"benchmark":3461.269954177226},{"day":"2019-06-26","equity":7004.381752979626,"benchmark":3718.249188614959},{"day":"2019-06-29","equity":7004.381752979626,"benchmark":3742.240386592897},{"day":"2019-07-02","equity":7005.854066095588,"benchmark":3784.216128906821},{"day":"2019-07-05","equity":7006.690163667352,"benchmark":3784.662377939183},{"day":"2019-07-08","equity":6924.898586924788,"benchmark":3741.007889265421},{"day":"2019-07-11","equity":6949.351123051378,"benchmark":3754.058902632516},{"day":"2019-07-14","equity":6877.440096184660,"benchmark":3715.677944190397},{"day":"2019-07-17","equity":6336.007197212344,"benchmark":3426.699820805119},{"day":"2019-07-20","equity":6098.325082634226,"benchmark":3218.652146931778},{"day":"2019-07-23","equity":6098.325082634226,"benchmark":3236.52335818018},{"day":"2019-07-26","equity":6098.325082634226,"benchmark":3237.996688318772},{"day":"2019-07-29","equity":6098.325082634226,"benchmark":2842.311921314171},{"day":"2019-08-01","equity":6098.325082634226,"benchmark":2570.783551757842},{"day":"2019-08-04","equity":6098.325082634226,"benchmark":2553.687963827593},{"day":"2019-08-07","equity":6098.325082634226,"benchmark":2635.649036104747},{"day":"2019-08-10","equity":6098.325082634226,"benchmark":2629.19967508942},{"day":"2019-08-13","equity":6098.325082634226,"benchmark":2710.222207735019},{"day":"2019-08-16","equity":6098.325082634226,"benchmark":2696.629320542913},{"day":"2019-08-19","equity":6098.325082634226,"benchmark":2659.640234082685},{"day":"2019-08-22","equity":6098.325082634226,"benchmark":2631.257378960867},{"day":"2019-08-25","equity":6098.325082634226,"benchmark":2496.231630081492},{"day":"2019-08-28","equity":6098.325082634226,"benchmark":2545.481939954714},{"day":"2019-08-31","equity":6098.325082634226,"benchmark":2518.816789441591},{"day":"2019-09-03","equity":6098.325082634226,"benchmark":2566.68939396887},{"day":"2019-09-06","equity":6098.325082634226,"benchmark":2563.615233968154},{"day":"2019-09-09","equity":6098.325082634226,"benchmark":2673.321662749466},{"day":"2019-09-12","equity":6098.325082634226,"benchmark":2827.415703614849},{"day":"2019-09-15","equity":6393.3310648040052,"benchmark":3043.247943941616},{"day":"2019-09-18","equity":5851.6068106222644,"benchmark":2789.197661486132},{"day":"2019-09-21","equity":6330.966166417890,"benchmark":3014.00092402697},{"day":"2019-09-24","equity":5682.3123171466596,"benchmark":2709.804291974553},{"day":"2019-09-27","equity":5804.6027990510388,"benchmark":2767.154375951044},{"day":"2019-09-30","equity":5784.4539072014196,"benchmark":2757.705229773728},{"day":"2019-10-03","equity":5889.3368944606068,"benchmark":2806.891789785184},{"day":"2019-10-06","equity":5866.2653560046148,"benchmark":2796.072021579899},{"day":"2019-10-09","equity":5903.9048151419844,"benchmark":2813.723649971107},{"day":"2019-10-12","equity":5527.313870249514,"benchmark":2637.115282925365},{"day":"2019-10-15","equity":5239.012368837378,"benchmark":2485.107279203325},{"day":"2019-10-18","equity":5239.012368837378,"benchmark":2401.347044160775},{"day":"2019-10-21","equity":5239.012368837378,"benchmark":2276.726689385206},{"day":"2019-10-24","equity":5239.012368837378,"benchmark":2285.046046345669},{"day":"2019-10-27","equity":5239.012368837378,"benchmark":2565.173563922434},{"day":"2019-10-30","equity":5239.012368837378,"benchmark":2557.137539680931},{"day":"2019-11-02","equity":5239.012368837378,"benchmark":2577.888119685764},{"day":"2019-11-05","equity":5239.012368837378,"benchmark":2559.457326317416},{"day":"2019-11-08","equity":5239.012368837378,"benchmark":2475.303967127309},{"day":"2019-11-11","equity":5239.012368837378,"benchmark":2557.222539496619},{"day":"2019-11-14","equity":5239.012368837378,"benchmark":2560.271907884426},{"day":"2019-11-17","equity":5239.012368837378,"benchmark":2770.940409408147},{"day":"2019-11-20","equity":5068.936675931286,"benchmark":2799.76597190334},{"day":"2019-11-23","equity":4833.0723065303618,"benchmark":2671.582708186849},{"day":"2019-11-26","equity":4819.862650608618,"benchmark":2664.4037654202},{"day":"2019-11-29","equity":4965.3122364583466,"benchmark":2743.450052351053},{"day":"2019-12-02","equity":4831.918823995508,"benchmark":2670.95583454615},{"day":"2019-12-05","equity":5201.6002011404318,"benchmark":2871.863523901699},{"day":"2019-12-08","equity":5363.5178681516042,"benchmark":2959.859583092701},{"day":"2019-12-11","equity":5729.2500339060116,"benchmark":3158.621027102128},{"day":"2019-12-14","equity":5968.5357498086208,"benchmark":3288.663661786794},{"day":"2019-12-17","equity":5003.5661487724246,"benchmark":2764.239590604743},{"day":"2019-12-20","equity":4854.3758907475204,"benchmark":2683.160391415352},{"day":"2019-12-23","equity":4534.8612285930178,"benchmark":2509.516392941729},{"day":"2019-12-26","equity":4374.272033425322,"benchmark":2448.302359010421},{"day":"2019-12-29","equity":4374.272033425322,"benchmark":2297.420602846247},{"day":"2020-01-01","equity":4374.272033425322,"benchmark":2258.660686892519},{"day":"2020-01-04","equity":4374.272033425322,"benchmark":2242.740929745954},{"day":"2020-01-07","equity":4374.272033425322,"benchmark":2266.778169290723},{"day":"2020-01-10","equity":4374.272033425322,"benchmark":2157.55694779063},{"day":"2020-01-13","equity":4374.272033425322,"benchmark":2247.979043387727},{"day":"2020-01-16","equity":4374.272033425322,"benchmark":2178.569610560501},{"day":"2020-01-19","equity":4374.272033425322,"benchmark":2091.377507959548},{"day":"2020-01-22","equity":4374.272033425322,"benchmark":2087.400224917147},{"day":"2020-01-25","equity":4374.272033425322,"benchmark":2120.238487044611},{"day":"2020-01-28","equity":4374.272033425322,"benchmark":2112.801003171911},{"day":"2020-01-31","equity":4374.272033425322,"benchmark":2028.059728589962},{"day":"2020-02-03","equity":4374.272033425322,"benchmark":1964.979240372505},{"day":"2020-02-06","equity":4374.272033425322,"benchmark":1944.253451980581},{"day":"2020-02-09","equity":4374.272033425322,"benchmark":1939.705961841273},{"day":"2020-02-12","equity":4374.272033425322,"benchmark":1780.458807149805},{"day":"2020-02-15","equity":4374.272033425322,"benchmark":1723.923304740324},{"day":"2020-02-18","equity":4374.272033425322,"benchmark":1614.631250060491},{"day":"2020-02-21","equity":4374.272033425322,"benchmark":1642.518272924129},{"day":"2020-02-24","equity":4374.272033425322,"benchmark":1607.898556326204},{"day":"2020-02-27","equity":4374.272033425322,"benchmark":1664.122392744829},{"day":"2020-03-01","equity":4374.272033425322,"benchmark":1651.992210714354},{"day":"2020-03-04","equity":4374.272033425322,"benchmark":1607.569182040413},{"day":"2020-03-07","equity":4374.272033425322,"benchmark":1507.814815012571},{"day":"2020-03-10","equity":4374.272033425322,"benchmark":1517.855418240716},{"day":"2020-03-13","equity":4374.272033425322,"benchmark":1509.490019713422},{"day":"2020-03-16","equity":4374.272033425322,"benchmark":1437.477467530751},{"day":"2020-03-19","equity":4374.272033425322,"benchmark":1518.917915936816},{"day":"2020-03-22","equity":4374.272033425322,"benchmark":1383.144877011184},{"day":"2020-03-25","equity":4374.272033425322,"benchmark":1319.554389899599},{"day":"2020-03-28","equity":4374.272033425322,"benchmark":1361.579715439341},{"day":"2020-03-31","equity":4374.272033425322,"benchmark":1395.027142912569},{"day":"2020-04-03","equity":4374.272033425322,"benchmark":1458.128881083948},{"day":"2020-04-06","equity":4374.272033425322,"benchmark":1321.282719485255},{"day":"2020-04-09","equity":4374.272033425322,"benchmark":1242.81726462827},{"day":"2020-04-12","equity":4374.272033425322,"benchmark":1310.4275346901},{"day":"2020-04-15","equity":4374.272033425322,"benchmark":1205.980469504483},{"day":"2020-04-18","equity":4374.272033425322,"benchmark":1242.119557807831},{"day":"2020-04-21","equity":4374.272033425322,"benchmark":1224.956678356829},{"day":"2020-04-24","equity":4374.272033425322,"benchmark":1217.21107015226},{"day":"2020-04-27","equity":4374.272033425322,"benchmark":1187.546134477148},{"day":"2020-04-30","equity":4374.272033425322,"benchmark":1271.904909888501},{"day":"2020-05-03","equity":4374.272033425322,"benchmark":1358.222222719665},{"day":"2020-05-06","equity":4374.272033425322,"benchmark":1328.953952851097},{"day":"2020-05-09","equity":4390.029520814420,"benchmark":1351.97119460761},{"day":"2020-05-12","equity":4276.361981880107,"benchmark":1318.130642986825},{"day":"2020-05-15","equity":4216.9170114923768,"benchmark":1300.432973028786},{"day":"2020-05-18","equity":4307.8153542445574,"benchmark":1327.494789348453},{"day":"2020-05-21","equity":3996.5292745696052,"benchmark":1234.820198635624},{"day":"2020-05-24","equity":3741.805238909544,"benchmark":1150.089549030636},{"day":"2020-05-27","equity":3741.805238909544,"benchmark":1139.737279811635},{"day":"2020-05-30","equity":3741.805238909544,"benchmark":1177.583447746717},{"day":"2020-06-02","equity":3741.805238909544,"benchmark":1130.854799072239},{"day":"2020-06-05","equity":3741.805238909544,"benchmark":1117.169828746471},{"day":"2020-06-08","equity":3741.805238909544,"benchmark":1105.273396209138},{"day":"2020-06-11","equity":3741.805238909544,"benchmark":1135.883954833779},{"day":"2020-06-14","equity":3741.805238909544,"benchmark":1082.904278047246},{"day":"2020-06-17","equity":3741.805238909544,"benchmark":1087.030310767101},{"day":"2020-06-20","equity":3741.805238909544,"benchmark":1099.071951322901},{"day":"2020-06-23","equity":3741.805238909544,"benchmark":1000.482790101782},{"day":"2020-06-26","equity":3741.805238909544,"benchmark":1043.304988913599},{"day":"2020-06-29","equity":3741.805238909544,"benchmark":1140.682902761164},{"day":"2020-07-02","equity":3741.805238909544,"benchmark":1060.84682587621},{"day":"2020-07-05","equity":3741.805238909544,"benchmark":1047.533729744077},{"day":"2020-07-08","equity":3741.805238909544,"benchmark":1135.731663497338},{"day":"2020-07-11","equity":3741.805238909544,"benchmark":1098.74257703711},{"day":"2020-07-14","equity":3741.805238909544,"benchmark":1071.910968551598},{"day":"2020-07-17","equity":3715.784384368974,"benchmark":1102.78006828229},{"day":"2020-07-20","equity":3507.458348096612,"benchmark":1070.883887445368},{"day":"2020-07-23","equity":3507.458348096612,"benchmark":1105.280479527112},{"day":"2020-07-26","equity":3507.458348096612,"benchmark":1124.451479623743},{"day":"2020-07-29","equity":3622.8527724115628,"benchmark":1162.789938158018},{"day":"2020-08-01","equity":3349.2453970047236,"benchmark":1078.370954543886},{"day":"2020-08-04","equity":3554.1295236885914,"benchmark":1141.586025802849},{"day":"2020-08-07","equity":3367.232591049971,"benchmark":1083.920734176515},{"day":"2020-08-10","equity":3549.9856965983972,"benchmark":1140.307486908542},{"day":"2020-08-13","equity":3583.9168680073004,"benchmark":1150.776630874114},{"day":"2020-08-16","equity":3791.4984998606852,"benchmark":1214.823991995022},{"day":"2020-08-19","equity":3728.4342726209984,"benchmark":1195.366117520444},{"day":"2020-08-22","equity":3826.038044775905,"benchmark":1225.480843886905},{"day":"2020-08-25","equity":3982.5277808440976,"benchmark":1273.764280856676},{"day":"2020-08-28","equity":4201.9784354433572,"benchmark":1341.473717370142},{"day":"2020-08-31","equity":3989.724954211277,"benchmark":1275.984901041525},{"day":"2020-09-03","equity":4196.6522975767364,"benchmark":1339.830387600174},{"day":"2020-09-06","equity":4340.4924562117046,"benchmark":1384.210916366271},{"day":"2020-09-09","equity":4542.5757690174356,"benchmark":1446.561822832406},{"day":"2020-09-12","equity":4417.6984977869018,"benchmark":1408.032114712833},{"day":"2020-09-15","equity":4206.2485287329756,"benchmark":1342.791214513306},{"day":"2020-09-18","equity":4052.5022128159088,"benchmark":1295.354234041428},{"day":"2020-09-21","equity":3973.0119009056738,"benchmark":1270.828245556453},{"day":"2020-09-24","equity":3800.325655074977,"benchmark":1217.547527756025},{"day":"2020-09-27","equity":3853.497957938308,"benchmark":1269.985330717547},{"day":"2020-09-30","equity":3853.497957938308,"benchmark":1249.305583892454},{"day":"2020-10-03","equity":3853.497957938308,"benchmark":1331.596030455399},{"day":"2020-10-06","equity":3842.2199731137256,"benchmark":1371.103236455384},{"day":"2020-10-09","equity":4022.2573334973316,"benchmark":1433.241643382299},{"day":"2020-10-12","equity":4125.2311101544696,"benchmark":1468.782191316844},{"day":"2020-10-15","equity":4124.4717619260064,"benchmark":1468.520108551806},{"day":"2020-10-18","equity":4257.4192706823472,"benchmark":1514.405842387378},{"day":"2020-10-21","equity":4434.8194351914256,"benchmark":1575.634042954634},{"day":"2020-10-24","equity":4448.9699920434628,"benchmark":1580.517990697707},{"day":"2020-10-27","equity":4079.752308147052,"benchmark":1453.08555868646},{"day":"2020-10-30","equity":4371.947454167182,"benchmark":1553.934298341285},{"day":"2020-11-02","equity":4562.246277097588,"benchmark":1619.6143642552},{"day":"2020-11-05","equity":4588.3514378166472,"benchmark":1628.624344718128},{"day":"2020-11-08","equity":4604.677424728606,"benchmark":1634.259124166445},{"day":"2020-11-11","equity":4153.0909809690316,"benchmark":1478.397795466549},{"day":"2020-11-14","equity":4074.775498811854,"benchmark":1451.367854077765},{"day":"2020-11-17","equity":4060.6865107350976,"benchmark":1446.505156288614},{"day":"2020-11-20","equity":4050.496449494308,"benchmark":1444.918493062438},{"day":"2020-11-23","equity":4050.496449494308,"benchmark":1376.964682078869},{"day":"2020-11-26","equity":4050.496449494308,"benchmark":1402.284002176932},{"day":"2020-11-29","equity":4050.496449494308,"benchmark":1556.873875300495},{"day":"2020-12-02","equity":4050.496449494308,"benchmark":1518.648749853804},{"day":"2020-12-05","equity":4050.496449494308,"benchmark":1627.211222782315},{"day":"2020-12-08","equity":4022.182122731203,"benchmark":1620.092488218445},{"day":"2020-12-11","equity":4098.974703440390,"benchmark":1650.164714677062},{"day":"2020-12-14","equity":4555.723696910661,"benchmark":1829.029118497523},{"day":"2020-12-17","equity":4486.274841974158,"benchmark":1801.83271913635},{"day":"2020-12-20","equity":4400.890463870821,"benchmark":1768.395916640083},{"day":"2020-12-23","equity":4340.820234089827,"benchmark":1744.872217648429},{"day":"2020-12-26","equity":4586.527551568003,"benchmark":1841.092009007245},{"day":"2020-12-29","equity":4522.541270974728,"benchmark":1816.03477167422},{"day":"2021-01-01","equity":4218.491127191645,"benchmark":1696.967738190267},{"day":"2021-01-04","equity":4135.892300243464,"benchmark":1664.621766661996},{"day":"2021-01-07","equity":4331.143157024837,"benchmark":1741.082642532339},{"day":"2021-01-10","equity":4387.496303933204,"benchmark":1763.150719680336},{"day":"2021-01-13","equity":4140.260550918595,"benchmark":1666.332387952717},{"day":"2021-01-16","equity":4228.457612168859,"benchmark":1700.870646393941},{"day":"2021-01-19","equity":4417.242010911477,"benchmark":1774.799236088579},{"day":"2021-01-22","equity":4562.244418932958,"benchmark":1831.58265462715},{"day":"2021-01-25","equity":4764.848045484272,"benchmark":1910.922899253924},{"day":"2021-01-28","equity":4619.022633712404,"benchmark":1853.817189747536},{"day":"2021-01-31","equity":4446.399858068045,"benchmark":1786.217544662667},{"day":"2021-02-03","equity":4262.508261841464,"benchmark":1714.204992479996},{"day":"2021-02-06","equity":4353.545138230426,"benchmark":1749.855331843138},{"day":"2021-02-09","equity":4342.635698729636,"benchmark":1606.733350519481},{"day":"2021-02-12","equity":4342.635698729636,"benchmark":1598.22274397372},{"day":"2021-02-15","equity":4342.635698729636,"benchmark":1446.600781081263},{"day":"2021-02-18","equity":4342.635698729636,"benchmark":1347.29620474477},{"day":"2021-02-21","equity":4342.635698729636,"benchmark":1327.714372205647},{"day":"2021-02-24","equity":4342.635698729636,"benchmark":1197.884237060201},{"day":"2021-02-27","equity":4342.635698729636,"benchmark":1202.116519549666},{"day":"2021-03-02","equity":4342.635698729636,"benchmark":1153.808290966986},{"day":"2021-03-05","equity":4342.635698729636,"benchmark":1187.39030148172},{"day":"2021-03-08","equity":4342.635698729636,"benchmark":1225.905842965345},{"day":"2021-03-11","equity":4342.635698729636,"benchmark":1158.224739723775},{"day":"2021-03-14","equity":4342.635698729636,"benchmark":1149.774341380793},{"day":"2021-03-17","equity":4342.635698729636,"benchmark":1129.222094279232},{"day":"2021-03-20","equity":4342.635698729636,"benchmark":1159.025154654837},{"day":"2021-03-23","equity":4342.635698729636,"benchmark":1090.816344224204},{"day":"2021-03-26","equity":4342.635698729636,"benchmark":1124.24252174351},{"day":"2021-03-29","equity":4342.635698729636,"benchmark":1165.96326461037},{"day":"2021-04-01","equity":4342.635698729636,"benchmark":1187.95696691964},{"day":"2021-04-04","equity":4342.635698729636,"benchmark":1125.864601559556},{"day":"2021-04-07","equity":4342.635698729636,"benchmark":1234.937073382195},{"day":"2021-04-10","equity":4352.125634943392,"benchmark":1251.788286842341},{"day":"2021-04-13","equity":4535.410405693592,"benchmark":1302.611093305791},{"day":"2021-04-16","equity":4476.452740064120,"benchmark":1286.262795421799},{"day":"2021-04-19","equity":4253.509487559260,"benchmark":1224.443137803714},{"day":"2021-04-22","equity":4511.385412398740,"benchmark":1295.949232751244},{"day":"2021-04-25","equity":4515.383191718936,"benchmark":1297.057772014175},{"day":"2021-04-28","equity":4245.897102655628,"benchmark":1222.332309047462},{"day":"2021-05-01","equity":4324.805347512404,"benchmark":1244.212678269148},{"day":"2021-05-04","equity":4492.354450139660,"benchmark":1290.672160860614},{"day":"2021-05-07","equity":4846.751839268984,"benchmark":1388.942572772903},{"day":"2021-05-10","equity":4906.756846445600,"benchmark":1405.581286693829},{"day":"2021-05-13","equity":5091.012323995592,"benchmark":1456.673259240291},{"day":"2021-05-16","equity":5020.661625926456,"benchmark":1437.165801539895},{"day":"2021-05-19","equity":5417.310305762516,"benchmark":1547.15202138118},{"day":"2021-05-22","equity":5477.238678191780,"benchmark":1563.769485348184},{"day":"2021-05-25","equity":4991.744781258968,"benchmark":1429.147485593327},{"day":"2021-05-28","equity":5366.667510220736,"benchmark":1533.109343497725},{"day":"2021-05-31","equity":5495.005167119552,"benchmark":1568.695932999101},{"day":"2021-06-03","equity":5257.526857533596,"benchmark":1502.84586745381},{"day":"2021-06-06","equity":5113.249173185564,"benchmark":1462.839287536658},{"day":"2021-06-09","equity":5264.296260216356,"benchmark":1504.72294671692},{"day":"2021-06-12","equity":5187.316656501272,"benchmark":1483.377368002271},{"day":"2021-06-15","equity":4977.848347072472,"benchmark":1425.294160615471},{"day":"2021-06-18","equity":4977.988844109284,"benchmark":1425.333118864328},{"day":"2021-06-21","equity":4804.566419837684,"benchmark":1361.926798020067},{"day":"2021-06-24","equity":4804.566419837684,"benchmark":1242.00268306126},{"day":"2021-06-27","equity":4804.566419837684,"benchmark":1239.73602130958},{"day":"2021-06-30","equity":4804.566419837684,"benchmark":1243.837262416526},{"day":"2021-07-03","equity":4804.566419837684,"benchmark":1221.453977618686},{"day":"2021-07-06","equity":4804.566419837684,"benchmark":1200.979647014839},{"day":"2021-07-09","equity":4804.566419837684,"benchmark":1163.678894563755},{"day":"2021-07-12","equity":4804.566419837684,"benchmark":1175.777201663347},{"day":"2021-07-15","equity":4804.566419837684,"benchmark":1161.532649217633},{"day":"2021-07-18","equity":4804.566419837684,"benchmark":1163.083895853939},{"day":"2021-07-21","equity":4804.566419837684,"benchmark":1155.476412349863},{"day":"2021-07-24","equity":4804.566419837684,"benchmark":1038.987706608446},{"day":"2021-07-27","equity":4804.566419837684,"benchmark":1093.125505883728},{"day":"2021-07-30","equity":4804.566419837684,"benchmark":1170.269921938562},{"day":"2021-08-02","equity":4804.566419837684,"benchmark":1255.843486382456},{"day":"2021-08-05","equity":4804.566419837684,"benchmark":1291.359242704092},{"day":"2021-08-08","equity":5057.8242085425142,"benchmark":1350.175573501201},{"day":"2021-08-11","equity":5398.5506844373466,"benchmark":1438.100799512463},{"day":"2021-08-14","equity":5349.1010150323244,"benchmark":1425.340202182302},{"day":"2021-08-17","equity":5698.240659771253,"benchmark":1515.436465152595},{"day":"2021-08-20","equity":5553.583564148457,"benchmark":1478.107379429615},{"day":"2021-08-23","equity":5658.851109065615,"benchmark":1505.271903859905},{"day":"2021-08-26","equity":5274.2471441094848,"benchmark":1406.023994067204},{"day":"2021-08-29","equity":5100.6449047800022,"benchmark":1361.225549540641},{"day":"2021-09-01","equity":5152.2493335790262,"benchmark":1374.542187331761},{"day":"2021-09-04","equity":5163.1603763703092,"benchmark":1377.357806226426},{"day":"2021-09-07","equity":5059.1966667552542,"benchmark":1350.529739399901},{"day":"2021-09-10","equity":5185.5039960737164,"benchmark":1383.123627057262},{"day":"2021-09-13","equity":4921.0450230608458,"benchmark":1314.879400036759},{"day":"2021-09-16","equity":4973.565969525022,"benchmark":1295.885482889478},{"day":"2021-09-19","equity":4973.565969525022,"benchmark":1239.537688406308},{"day":"2021-09-22","equity":4973.565969525022,"benchmark":1233.980825455705},{"day":"2021-09-25","equity":4973.565969525022,"benchmark":1288.125708048961},{"day":"2021-09-28","equity":4973.565969525022,"benchmark":1280.280933392756},{"day":"2021-10-01","equity":4973.565969525022,"benchmark":1231.806246837687},{"day":"2021-10-04","equity":4973.565969525022,"benchmark":1210.464209782025},{"day":"2021-10-07","equity":4973.565969525022,"benchmark":1198.022361760694},{"day":"2021-10-10","equity":4973.565969525022,"benchmark":1154.102248662907},{"day":"2021-10-13","equity":4973.565969525022,"benchmark":1084.777815651369},{"day":"2021-10-16","equity":4973.565969525022,"benchmark":1082.408445789066},{"day":"2021-10-19","equity":4973.565969525022,"benchmark":987.761151020478},{"day":"2021-10-22","equity":4973.565969525022,"benchmark":988.34906641232},{"day":"2021-10-25","equity":4973.565969525022,"benchmark":1007.707774435262},{"day":"2021-10-28","equity":4973.565969525022,"benchmark":1023.37607379375},{"day":"2021-10-31","equity":4973.565969525022,"benchmark":971.724519127342},{"day":"2021-11-03","equity":4973.565969525022,"benchmark":969.875773136128},{"day":"2021-11-06","equity":4973.565969525022,"benchmark":932.900853311848},{"day":"2021-11-09","equity":4973.565969525022,"benchmark":907.971115702355},{"day":"2021-11-12","equity":4973.565969525022,"benchmark":925.775035430004},{"day":"2021-11-15","equity":4973.565969525022,"benchmark":942.070208429191},{"day":"2021-11-18","equity":4973.565969525022,"benchmark":973.86368115549},{"day":"2021-11-21","equity":4973.565969525022,"benchmark":1007.165900610251},{"day":"2021-11-24","equity":4973.565969525022,"benchmark":1079.946992793101},{"day":"2021-11-27","equity":4863.2427912399968,"benchmark":1115.568998884347},{"day":"2021-11-30","equity":5016.4373278019144,"benchmark":1149.292675758561},{"day":"2021-12-03","equity":5429.2517169682916,"benchmark":1240.168103705994},{"day":"2021-12-06","equity":5807.3632479783932,"benchmark":1323.404173218468},{"day":"2021-12-09","equity":5812.8976861822684,"benchmark":1324.622503909996},{"day":"2021-12-12","equity":5893.5170752509272,"benchmark":1342.369757093853},{"day":"2021-12-15","equity":5926.1445190807496,"benchmark":1349.552241519489},{"day":"2021-12-18","equity":5846.1847578212736,"benchmark":1331.950196354099},{"day":"2021-12-21","equity":5528.2280653120132,"benchmark":1261.956389794018},{"day":"2021-12-24","equity":5419.4216537631528,"benchmark":1238.004150064937},{"day":"2021-12-27","equity":5419.0194416843828,"benchmark":1237.915608590262},{"day":"2021-12-30","equity":5400.6142169598676,"benchmark":1233.863950709134},{"day":"2022-01-02","equity":5387.2768644278544,"benchmark":1230.927915408911},{"day":"2022-01-05","equity":5549.6096594194264,"benchmark":1266.663254587741},{"day":"2022-01-08","equity":5647.057601863822,"benchmark":1288.115083072},{"day":"2022-01-11","equity":5639.978669277470,"benchmark":1286.55675311772},{"day":"2022-01-14","equity":5597.8590203886756,"benchmark":1277.284689889754},{"day":"2022-01-17","equity":5827.6830021978536,"benchmark":1327.877288519049},{"day":"2022-01-20","equity":5652.8816327644116,"benchmark":1289.397163625294},{"day":"2022-01-23","equity":5972.688500836014,"benchmark":1359.79826096888},{"day":"2022-01-26","equity":6019.1520401755244,"benchmark":1370.026572123336},{"day":"2022-01-29","equity":5781.9112676338276,"benchmark":1317.801268701034},{"day":"2022-02-01","equity":5901.657847725232,"benchmark":1344.161836541275},{"day":"2022-02-04","equity":6349.3842453288452,"benchmark":1442.722664490498},{"day":"2022-02-07","equity":6262.3938169324696,"benchmark":1423.572914347789},{"day":"2022-02-08","equity":6285.4325248044152,"benchmark":1428.644570017173}],"trades":[{"symbol":"BTC-EUR","opened":"2018-06-02","closed":"2018-06-06","invested":9999.999984555,"result":228.213059281468,"fees":40.497420898642,"is_closed":true},{"symbol":"BTC-EUR","opened":"2018-10-22","closed":"2018-11-07","invested":10228.213045688,"result":-968.781289886528,"fees":39.012401553904,"is_closed":true},{"symbol":"BTC-EUR","opened":"2018-11-17","closed":"2018-11-19","invested":9259.43174996,"result":92.492721842182,"fees":37.260195106738,"is_closed":true},{"symbol":"BTC-EUR","opened":"2018-11-22","closed":"2018-12-20","invested":9351.924369984,"result":-510.644197204236,"fees":36.421845078204,"is_closed":true},{"symbol":"BTC-EUR","opened":"2018-12-31","closed":"2019-01-07","invested":8841.280142457,"result":-1231.434053520,"fees":32.932752847914,"is_closed":true},{"symbol":"BTC-EUR","opened":"2019-01-22","closed":"2019-02-26","invested":7609.846148667,"result":-605.46448753326,"fees":29.256529293594,"is_closed":true},{"symbol":"BTC-EUR","opened":"2019-07-02","closed":"2019-07-20","invested":7004.38167585,"result":-906.0566703454,"fees":26.2298555471,"is_closed":true},{"symbol":"BTC-EUR","opened":"2019-09-14","closed":"2019-10-14","invested":6098.325005592,"result":-859.312713796848,"fees":22.695672640032,"is_closed":true},{"symbol":"BTC-EUR","opened":"2019-11-19","closed":"2019-12-25","invested":5239.012332793,"result":-864.740335412056,"fees":19.244100812642,"is_closed":true},{"symbol":"BTC-EUR","opened":"2020-05-09","closed":"2020-05-24","invested":4374.272014749,"result":-632.466794515778,"fees":16.247151685276,"is_closed":true},{"symbol":"BTC-EUR","opened":"2020-07-16","closed":"2020-07-19","invested":3741.80521568,"result":-234.346890812932,"fees":14.512585030292,"is_closed":true},{"symbol":"BTC-EUR","opened":"2020-07-27","closed":"2020-09-27","invested":3507.458327055,"result":346.039609841696,"fees":14.737357409414,"is_closed":true},{"symbol":"BTC-EUR","opened":"2020-10-06","closed":"2020-11-18","invested":3853.497929148,"result":196.998491556,"fees":15.824223154296,"is_closed":true},{"symbol":"BTC-EUR","opened":"2020-12-06","closed":"2021-02-07","invested":4050.496446855,"result":292.139249235328,"fees":16.803669639382,"is_closed":true},{"symbol":"BTC-EUR","opened":"2021-04-10","closed":"2021-06-20","invested":4342.63568328,"result":461.930721108048,"fees":18.313660954512,"is_closed":true},{"symbol":"BTC-EUR","opened":"2021-08-07","closed":"2021-09-16","invested":4804.566390631,"result":168.999549687338,"fees":19.576198793924,"is_closed":true},{"symbol":"BTC-EUR","opened":"2021-11-26","invested":4973.565953592,"result":1311.8665552793932,"fees":9.947131907184,"is_closed":false}],"notes":{"no_cash":17,"residue_written_off":16},"computed_at":"2027-01-05T02:10:00+00:00","seconds":0} \ No newline at end of file diff --git a/tests/Anubis.Tests/TrialSeamTests.cs b/tests/Anubis.Tests/TrialSeamTests.cs new file mode 100644 index 0000000..1ed587a --- /dev/null +++ b/tests/Anubis.Tests/TrialSeamTests.cs @@ -0,0 +1,86 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The golden reports of the trial judge (Phase 12, issue #118). They were written before the seam between the judge and the +/// engines, so the seam must leave every byte of the report as it was. Elapsed seconds are the only field set to zero. +/// To rewrite them on purpose: ANUBIS_WRITE_GOLDEN=1, then read the diff. +/// +[TestClass] +public sealed class TrialSeamTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero); + private static readonly Guid Id = new("6d2f3a51-0c4e-4b7a-9a61-3f1e2d0c9b12"); + private static readonly DateOnly Through = new(2026, 12, 31); + + [TestMethod] + [TestCategory(Category.Golden)] + public void TheReportOfTheAverageCrossDoesNotMove() + { + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(1500, 7, start: 20_000, drift: 0.0008, volatility: 0.03)); + var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"], + new DateOnly(2018, 6, 1), new DateOnly(2022, 2, 8), 10_000m), Now).Plan; + var prior = new PriorTrials(2, 18, [0.4, 0.9, -0.1]); + var report = TrialRunner.Run(Id, plan, TrialPlan.Hash(plan.ToJson()), MovingAverageCrossFamily.Instance, data, prior, Now).Report; + Same("sma_cross", report); + } + + [TestMethod] + [TestCategory(Category.Golden)] + public async Task TheReportOfTheCryptoTrendProtocolDoesNotMove() + { + Same("crypto_trend", await CryptoTrendAsync(null).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Golden)] + public async Task TheReportOfAJudgedVariantOutsideTheGridDoesNotMove() + { + Same("crypto_trend_judged", await CryptoTrendAsync("coin_vol=12;max_stop=15").ConfigureAwait(false)); + } + + private static async Task CryptoTrendAsync(string? judged) + { + var folder = TempFolder.Create("golden-report"); + try + { + var store = new ResearchStore(folder); + var seed = 21u; + foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" }) + { + var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), + (decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList(); + await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false); + } + + var plan = Laboratory.BuildPlan(new TrialRequest(StrategyNames.CryptoTrend, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, + CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), Now).Plan with + { Judged = judged }; + var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false); + return TrialRunner.Run(Id, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(StrategyNames.CryptoTrend)!, data, PriorTrials.None, Now).Report; + } + finally + { + TempFolder.Delete(folder); + } + } + + private static void Same(string name, BacktestReport report) + { + var json = (report with { Seconds = 0 }).ToJson(); + var relative = Path.Combine("golden", name + ".report.json"); + if (Environment.GetEnvironmentVariable("ANUBIS_WRITE_GOLDEN") == "1") + { + var target = Path.Combine(Repo.Root.FullName, "tests", "Anubis.Tests", "Fixtures", relative); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.WriteAllText(target, json); + } + + Assert.AreEqual(Fixture.Text(relative), json, $"The report of {name} changed."); + } +} -- 2.54.1 From 88b28836f761761a77ea7e2b0ef5195c6afe6ffb Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 09:32:16 +0100 Subject: [PATCH 2/6] Add the eight currencies and the 28 pairs as one shared list The basket maths and the ECB crosses both read the currency order, the pairs and their pip from here. refs #119 Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Baskets/Currencies.cs | 79 ++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/Anubis/Baskets/Currencies.cs diff --git a/src/Anubis/Baskets/Currencies.cs b/src/Anubis/Baskets/Currencies.cs new file mode 100644 index 0000000..b29590e --- /dev/null +++ b/src/Anubis/Baskets/Currencies.cs @@ -0,0 +1,79 @@ +namespace Anubis.Baskets; + +/// +/// The eight currencies of the research document (section 4.1) in the market naming order: in a pair the currency that comes +/// first is the base. The one home of the currency and pair lists: the basket maths and the ECB crosses both read them here. +/// +public static class Currencies +{ + public const string Eur = "EUR"; + public const string Gbp = "GBP"; + public const string Aud = "AUD"; + public const string Nzd = "NZD"; + public const string Usd = "USD"; + public const string Cad = "CAD"; + public const string Chf = "CHF"; + public const string Jpy = "JPY"; + + private static readonly string[] All = [Eur, Gbp, Aud, Nzd, Usd, Cad, Chf, Jpy]; + + /// EUR, GBP, AUD, NZD, USD, CAD, CHF, JPY. + public static IReadOnlyList Order { get; } = Array.AsReadOnly(All); + + /// Position of a currency in ; -1 when it is not one of the eight. + public static int IndexOf(string currency) => Array.IndexOf(All, currency); +} + +/// A currency pair: the price is how many units of buy one unit of . +public sealed record FxPair(string Base, string Quote) +{ + /// The market name, base then quote: EURUSD. + public string Name => Base + Quote; + + /// The pip: 0.01 when the quote is the yen, 0.0001 otherwise (document, appendix C). + public decimal Pip => Quote == Currencies.Jpy ? 0.01m : 0.0001m; + + public override string ToString() => Name; +} + +/// The 28 pairs of the eight currencies, in the order of the document's appendix A. +public static class FxPairs +{ + /// Every pair whose base comes before its quote in : 8 × 7 / 2 = 28. + public static IReadOnlyList All { get; } = Build(); + + private static readonly Dictionary ByName = All.ToDictionary(p => p.Name, StringComparer.Ordinal); + + /// The pair with this market name (EURUSD), or null when it is not one of the 28. + public static FxPair? Find(string name) => ByName.GetValueOrDefault(name); + + /// The pair with this market name; throws when it is not one of the 28. + public static FxPair Get(string name) => Find(name) ?? throw new ArgumentException($"{name} non è una delle 28 coppie.", nameof(name)); + + /// The pair of two currencies, whichever order they are given in; null when they are the same or unknown. + public static FxPair? Of(string one, string other) + { + var a = Currencies.IndexOf(one); + var b = Currencies.IndexOf(other); + if (a < 0 || b < 0 || a == b) + { + return null; + } + + return a < b ? Find(one + other) : Find(other + one); + } + + private static List Build() + { + var pairs = new List(28); + for (var i = 0; i < Currencies.Order.Count; i++) + { + for (var j = i + 1; j < Currencies.Order.Count; j++) + { + pairs.Add(new FxPair(Currencies.Order[i], Currencies.Order[j])); + } + } + + return pairs; + } +} -- 2.54.1 From f895c54076e57444320895369a578f7bd07199e7 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 09:48:53 +0100 Subject: [PATCH 3/6] Put a seam between the trial judge and the engines The trial judge was tied to daily bars in many places, so the basket engine of Phase 14 could not be judged by it. TrialRunner.Run now has an overload that takes an IResearchFamily and an ITrialEngine (one variant, the window's sessions, periods per year, data fingerprint, instruments, benchmark, look-ahead check, limitations, expectations). The old signature is a wrapper over DailyTrialEngine, which builds the options once and keeps every engine call in today's order, so the golden reports stay byte for byte the same. IResearchFamily is the base of IStrategyFamily without Create; ParameterGrid.Of, StrategyParameters.Of and TrialRunner.Limitations take it. ParameterSpec.Choices marks a choice axis: the plateau rule only averages variants with the same value there, numeric axes keep one step. BacktestRun.Baskets and the report's optional Baskets section (last field, left out when empty) carry units, levels, legs and exit reason. No plan field changes: plan hashes recorded before the seam are checked by a test. refs #118 Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/Engine.cs | 10 + src/Anubis/Backtest/Report.cs | 83 +++--- src/Anubis/Backtest/TrialEngines.cs | 118 ++++++++ src/Anubis/Backtest/Validation.cs | 23 +- src/Anubis/Strategies/Strategy.cs | 23 +- tests/Anubis.Tests/TrialEngineTests.cs | 361 +++++++++++++++++++++++++ 6 files changed, 571 insertions(+), 47 deletions(-) create mode 100644 src/Anubis/Backtest/TrialEngines.cs create mode 100644 tests/Anubis.Tests/TrialEngineTests.cs diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index 99c3fd0..f01cc4f 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -53,6 +53,13 @@ public sealed record BacktestTrade(string Symbol, DateOnly Opened, DateOnly? Clo public bool IsClosed => Closed is not null; } +/// +/// A basket from its first level to its exit: the relation it trades (a pair of symbols or one), the units of each order, +/// how many levels it reached, its legs, why it closed (null while open) and its result net of every cost, in the dataset +/// currency. Only the basket engine writes them. +/// +public sealed record BacktestBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList Legs, string? ExitReason, decimal Result); + /// What the strategy proposed on a day, and what was left after correctives and risk. public sealed record DecisionRecord(DateOnly Day, IReadOnlyList Proposed, IReadOnlyList Final); @@ -80,6 +87,9 @@ public sealed record BacktestRun( /// Value of the leftovers below the minimum written off after an exit (SPEC 7.2). public decimal WrittenOff { get; init; } + /// The baskets of an engine that trades them, in the order they opened; empty for the daily engine. + public IReadOnlyList Baskets { get; init; } = []; + /// Daily returns of the equity, one per session after the first. public double[] DailyReturns() { diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 60e4e1d..c0e1b95 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -10,6 +10,9 @@ namespace Anubis.Backtest; /// An instrument of the report: where its bars come from and what period they cover. public sealed record ReportInstrument(string Symbol, string Venue, DateOnly? First, DateOnly? Last, int Bars, int Actions, string Source); +/// A basket of the judged variant (), as the report shows it. +public sealed record ReportBasket(string Relation, DateTimeOffset Opened, DateTimeOffset? Closed, decimal Units, int Levels, IReadOnlyList Legs, string? ExitReason, decimal Result); + /// A point of the equity curve of the chosen variant and of buy and hold, on the same day. public sealed record ReportPoint(DateOnly Day, decimal Equity, decimal Benchmark); @@ -95,6 +98,9 @@ public sealed record BacktestReport( /// The variant in use, when the figures, the checks and the curve are its own (); null when they are those of the chosen one. public string? Judged { get; init; } + /// The last baskets of the judged variant, at most ; null (left out) for an engine without baskets. + public IReadOnlyList? Baskets { get; init; } + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); public static BacktestReport FromJson(string text) => JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Empty report"); @@ -105,7 +111,8 @@ public sealed record BacktestReport( /// low-priority thread). Every variant of the grid runs once on the whole period; the validations work on their daily /// returns; the chosen variant (plateau rule on the whole period) is then run again with doubled and tripled costs. A plan /// that names the variant to judge has the figures, the checks and the curve of that one: the grid still gives the choice, -/// the overfitting and the number of tries. +/// the overfitting and the number of tries. The engine that runs the variants is an : the daily one +/// () unless the caller gives another. /// public static class TrialRunner { @@ -113,6 +120,7 @@ public static class TrialRunner public const int MaxTrades = 300; + /// A trial of a daily family on daily data: the judge with the . public static (BacktestReport Report, TrialSummary Summary) Run( Guid trialId, TrialPlan plan, string planHash, IStrategyFamily family, BacktestDataset data, PriorTrials prior, DateTimeOffset now, Action? progress = null, CancellationToken cancellationToken = default) @@ -121,8 +129,20 @@ public static class TrialRunner ArgumentNullException.ThrowIfNull(family); ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(prior); + return Run(trialId, plan, planHash, family, new DailyTrialEngine(plan, family, data), prior, now, progress, cancellationToken); + } + + /// A trial of any family on any engine: the same validations, checks and report whatever the engine. + public static (BacktestReport Report, TrialSummary Summary) Run( + Guid trialId, TrialPlan plan, string planHash, IResearchFamily family, ITrialEngine engine, PriorTrials prior, DateTimeOffset now, + Action? progress = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(family); + ArgumentNullException.ThrowIfNull(engine); + ArgumentNullException.ThrowIfNull(prior); var watch = Stopwatch.StartNew(); - var sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + var sessions = engine.Sessions; if (sessions < 30) { throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30."); @@ -134,15 +154,12 @@ public static class TrialRunner throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri."); } - // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. - var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } }; - var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); progress?.Invoke($"variante {i + 1} di {variants.Count}"); - runs[i] = BacktestEngine.Run(family.Create(variants[i].Parameters), data, options); + runs[i] = engine.Run(variants[i].Parameters); } var returns = runs.Select(r => r.DailyReturns()).ToArray(); @@ -157,21 +174,22 @@ public static class TrialRunner progress?.Invoke("variante in uso"); } - var run = judgedIndex < 0 ? BacktestEngine.Run(family.Create(judged), data, options) : runs[judgedIndex]; + var run = judgedIndex < 0 ? engine.Run(judged) : runs[judgedIndex]; var judgedReturns = judgedIndex < 0 ? run.DailyReturns() : returns[judgedIndex]; - var metrics = BacktestMetrics.Of(run, data.PeriodsPerYear); + var year = engine.PeriodsPerYear; + var metrics = BacktestMetrics.Of(run, year); progress?.Invoke("costi doppi e tripli, comprare e tenere"); var costs = new List(); foreach (var multiplier in plan.CostMultipliers.Distinct().Order()) { - var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(judged), data, options with { Costs = options.Costs with { Multiplier = multiplier } }); - var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear); + var costed = multiplier == 1m ? run : engine.Run(judged, multiplier); + var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, year); costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } - var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, plain); - var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); + var benchmarkRun = engine.Benchmark(); + var benchmark = BacktestMetrics.Of(benchmarkRun, year); cancellationToken.ThrowIfCancellationRequested(); progress?.Invoke("convalide"); @@ -195,7 +213,7 @@ public static class TrialRunner var dsr = SharpeTests.Deflated(judgedReturns, trials, spread * spread); progress?.Invoke("test anti sguardo in avanti"); - var look = LookAheadCheck.Run(_ => family.Create(judged), data, options, v.LookAheadCuts); + var look = engine.LookAhead(judged, v.LookAheadCuts); var lookAhead = new ReportLookAhead(look.Cutoffs, look.Decisions, look.Mismatches.Count, [.. look.Mismatches.Take(5).Select(m => $"{m.Day:yyyy-MM-dd}: {m.Full} / {m.Cut}")]); @@ -226,18 +244,17 @@ public static class TrialRunner family.Name, family.Version, planHash, - data.Fingerprint(), - data.Currency, - data.PeriodsPerYear, + engine.Fingerprint(), + engine.Currency, + year, sessions, - [.. data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, - i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))], + engine.Instruments(), chosen.ToString(), metrics, benchmark, costs, [.. variants.Select((x, i) => new ReportVariant(x.ToString(), sharpes[i], scores[i], runs[i].NetResult, - Metrics(runs[i], data).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)), + BacktestMetrics.Of(runs[i], year).MaxDrawdown, runs[i].Trades.Count(tr => tr.IsClosed), i == chosenIndex)), .. judgedIndex >= 0 ? Array.Empty() : [new ReportVariant(judged.ToString(), Moments.Of(judgedReturns).Sharpe, 0, run.NetResult, metrics.MaxDrawdown, metrics.Trades, false) { OutsideGrid = true }]], walkForward, @@ -248,36 +265,28 @@ public static class TrialRunner lookAhead, checks, passed, - judgedIndex >= 0 ? Limitations(plan, family, data) - : [.. Limitations(plan, family, data), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."], + judgedIndex >= 0 ? engine.Limitations() + : [.. engine.Limitations(), "La variante in uso non è nella griglia: è giudicata lo stesso, senza contare come un tentativo in più."], curve, [.. run.Trades.TakeLast(MaxTrades)], run.Notes.GroupBy(n => n.Reason).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal), now, watch.Elapsed.TotalSeconds) - { Judged = plan.Judged is null ? null : judged.ToString() }; - if (StrategyPipeline.ResearchShare(family.Id) is not null) { - var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); - var table = plan.Slippage ?? SlippageTable.Standard; - var traded = run.Trades.Sum(x => x.Invested); - report = report with - { - ExpectedSlippageBp = traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null), - ExpectedPathP5 = [.. PathBootstrap.Percentile(judgedReturns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) - .Select(x => Math.Round(x, 4))], - }; - } + Judged = plan.Judged is null ? null : judged.ToString(), + Baskets = run.Baskets.Count == 0 ? null + : [.. run.Baskets.TakeLast(MaxTrades).Select(b => new ReportBasket(b.Relation, b.Opened, b.Closed, b.Units, b.Levels, b.Legs, b.ExitReason, b.Result))], + }; + var expected = engine.Expected(run, judgedReturns); + report = report with { ExpectedSlippageBp = expected.SlippageBp, ExpectedPathP5 = expected.PathP5 }; - var summary = new TrialSummary(data.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, + var summary = new TrialSummary(engine.Currency, judged.ToString(), run.NetResult, metrics.TotalReturn, metrics.Sharpe, metrics.MaxDrawdown, metrics.Trades, dsr.Value, pbo?.Probability, sharpes); return (report, summary); } - private static BacktestMetrics Metrics(BacktestRun run, BacktestDataset data) => BacktestMetrics.Of(run, data.PeriodsPerYear); - /// What this backtest does not model, in plain Italian (SPEC 12.1: the report declares it). - public static IReadOnlyList Limitations(TrialPlan plan, IStrategyFamily family, BacktestDataset data) + public static IReadOnlyList Limitations(TrialPlan plan, IResearchFamily family, BacktestDataset data) { ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(family); diff --git a/src/Anubis/Backtest/TrialEngines.cs b/src/Anubis/Backtest/TrialEngines.cs new file mode 100644 index 0000000..fbc1313 --- /dev/null +++ b/src/Anubis/Backtest/TrialEngines.cs @@ -0,0 +1,118 @@ +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// What an engine expects of the judged variant once it trades for real: the mean slippage in basis points and the 5th +/// percentile of the expected path (SPEC 12.3). Null where the engine has nothing to expect (the examples). +/// +public sealed record TrialExpectations(decimal? SlippageBp, IReadOnlyList? PathP5) +{ + public static TrialExpectations None { get; } = new(null, null); +} + +/// +/// What the trial judge () asks of an engine, so the same judge, with the same validations and the +/// same report, works on daily bars and on baskets. The engine is built for one plan and one dataset; the judge calls it in +/// a fixed order: every variant, the judged one outside the grid, the costed runs, the benchmark, the look-ahead check. +/// +public interface ITrialEngine +{ + /// The currency of the money in the runs and in the report. + string Currency { get; } + + /// Periods in a year, to annualise the returns of the runs. + int PeriodsPerYear { get; } + + /// The sessions of the plan's window, both ends included: fewer than 30 and there is no trial. + int Sessions { get; } + + /// A hash of the data the runs read, for the report. + string Fingerprint(); + + /// The instruments of the data, with the period they cover. + IReadOnlyList Instruments(); + + /// One variant over the whole window, with costs multiplied by . + BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m); + + /// The term of comparison of the report: buy and hold for the daily engine, its own for an engine that is not. + BacktestRun Benchmark(); + + /// The check of SPEC 12.2 point 2: a decision must not change when data after it is added. + LookAheadResult LookAhead(StrategyParameters parameters, int cuts); + + /// What this engine does not model, in plain Italian (SPEC 12.1). + IReadOnlyList Limitations(); + + /// What the judged variant should give once it trades, from its run and its returns. + TrialExpectations Expected(BacktestRun run, double[] returns); +} + +/// +/// The daily engine of the trial judge: on daily closes, the strategy through its correctives and +/// the risk engine, buy and hold as the comparison. The options are built once, so every run shares the same risk state as it +/// always did. +/// +public sealed class DailyTrialEngine : ITrialEngine +{ + private readonly TrialPlan _plan; + private readonly IStrategyFamily _family; + private readonly BacktestDataset _data; + private readonly BacktestOptions _plain; + private readonly BacktestOptions _options; + + public DailyTrialEngine(TrialPlan plan, IStrategyFamily family, BacktestDataset data) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(family); + ArgumentNullException.ThrowIfNull(data); + _plan = plan; + _family = family; + _data = data; + + // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. + _plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } }; + _options = StrategyPipeline.For(family.Id, data, _plain, plan.ReferenceShare); + Sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + } + + public string Currency => _data.Currency; + + public int PeriodsPerYear => _data.PeriodsPerYear; + + public int Sessions { get; } + + public string Fingerprint() => _data.Fingerprint(); + + public IReadOnlyList Instruments() => + [.. _data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, + i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))]; + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) => + BacktestEngine.Run(_family.Create(parameters), _data, costMultiplier == 1m ? _options : _options with { Costs = _options.Costs with { Multiplier = costMultiplier } }); + + public BacktestRun Benchmark() => BacktestEngine.Run(new BuyAndHold(_data.Tradable.Count()), _data, _plain); + + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) => LookAheadCheck.Run(_ => _family.Create(parameters), _data, _options, cuts); + + public IReadOnlyList Limitations() => TrialRunner.Limitations(_plan, _family, _data); + + public TrialExpectations Expected(BacktestRun run, double[] returns) + { + ArgumentNullException.ThrowIfNull(run); + ArgumentNullException.ThrowIfNull(returns); + if (StrategyPipeline.ResearchShare(_family.Id) is null) + { + return TrialExpectations.None; + } + + var specs = _data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var table = _plan.Slippage ?? SlippageTable.Standard; + var traded = run.Trades.Sum(x => x.Invested); + return new TrialExpectations( + traded > 0m ? Math.Round(run.Trades.Sum(x => x.Invested * table.Bp(specs.GetValueOrDefault(x.Symbol))) / traded, 2) : table.Bp(null), + [.. PathBootstrap.Percentile(returns, CryptoTrendProtocol.PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed).Select(x => Math.Round(x, 4))]); + } +} diff --git a/src/Anubis/Backtest/Validation.cs b/src/Anubis/Backtest/Validation.cs index 840bbaf..2c5fd2e 100644 --- a/src/Anubis/Backtest/Validation.cs +++ b/src/Anubis/Backtest/Validation.cs @@ -5,6 +5,12 @@ namespace Anubis.Backtest; /// One point of a parameter grid: its parameters and its place on each parameter's grid (for neighbours). public sealed record Variant(int Index, StrategyParameters Parameters, IReadOnlyList Position) { + /// + /// For each axis, in the order of , whether it is a choice axis (); + /// null when none is. + /// + public IReadOnlyList? Choices { get; init; } + public override string ToString() => Parameters.ToString(); } @@ -15,12 +21,14 @@ public static class ParameterGrid /// The Cartesian product of the grids (the family's own, or where given), without the /// points the family rejects. A family without parameters has one variant. /// - public static IReadOnlyList Of(IStrategyFamily family, IReadOnlyDictionary>? grids = null) + public static IReadOnlyList Of(IResearchFamily family, IReadOnlyDictionary>? grids = null) { ArgumentNullException.ThrowIfNull(family); var axes = family.Parameters .Select(p => (p.Name, Values: (IReadOnlyList)[.. (grids?.GetValueOrDefault(p.Name) ?? p.Grid).Distinct().Order()])) .ToList(); + bool[] marks = [.. family.Parameters.Select(p => p.Choices)]; + var choices = marks.Any(c => c) ? marks : null; if (axes.Any(a => a.Values.Count == 0)) { throw new ArgumentException("Every parameter needs at least one value on its grid", nameof(grids)); @@ -33,7 +41,7 @@ public static class ParameterGrid var parameters = new StrategyParameters(axes.Select((a, i) => KeyValuePair.Create(a.Name, a.Values[position[i]]))); if (family.Accepts(parameters)) { - result.Add(new Variant(result.Count, parameters, [.. position])); + result.Add(new Variant(result.Count, parameters, [.. position]) { Choices = choices }); } // Next point: the last parameter moves fastest. @@ -116,7 +124,8 @@ public sealed record OverfittingResult(int Groups, int Combinations, int Variant public static class Validation { /// - /// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every axis. + /// Each variant's value, capped at the mean of its zone: itself and the variants one step away on every numeric axis + /// with the same value on every choice axis (). /// public static double[] PlateauScores(IReadOnlyList variants, IReadOnlyList values) { @@ -129,7 +138,7 @@ public static class Validation var count = 0; for (var j = 0; j < variants.Count; j++) { - if (Neighbours(variants[i].Position, variants[j].Position)) + if (Neighbours(variants[i].Position, variants[j].Position, variants[i].Choices)) { sum += values[j]; count++; @@ -436,11 +445,13 @@ public static class Validation return sums; } - private static bool Neighbours(IReadOnlyList a, IReadOnlyList b) + /// One step at most on every numeric axis; on a choice axis only the same value. + private static bool Neighbours(IReadOnlyList a, IReadOnlyList b, IReadOnlyList? choices) { for (var k = 0; k < a.Count; k++) { - if (Math.Abs(a[k] - b[k]) > 1) + var limit = choices is not null && choices[k] ? 0 : 1; + if (Math.Abs(a[k] - b[k]) > limit) { return false; } diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index 3623a9a..5addd05 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -212,7 +212,7 @@ public sealed class StrategyParameters public static StrategyParameters None { get; } = new([]); /// The parameters a text such as fast=20;slow=100 gives to a family: its defaults where the text says nothing, or nothing it accepts. - public static StrategyParameters Of(IStrategyFamily family, string? text) + public static StrategyParameters Of(IResearchFamily family, string? text) { ArgumentNullException.ThrowIfNull(family); var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal); @@ -328,10 +328,21 @@ public interface IStrategy /// A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results). /// parameters take only whole numbers, such as a number of days. /// -public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max, bool Whole = false); +public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList Grid, decimal Min, decimal Max, bool Whole = false) +{ + /// + /// True for a choice axis: its values name different rules (a signal, a relation, a style), not points on a scale. The + /// plateau rule never averages two variants that differ on a choice axis. + /// + public bool Choices { get; init; } +} -/// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. -public interface IStrategyFamily +/// +/// What the laboratory needs to judge a family of rules: its name, its version and its parameters. A family judged by an +/// engine of its own (baskets) stops here; adds the strategies the daily engine and the live +/// bot run. +/// +public interface IResearchFamily { string Id { get; } @@ -350,7 +361,11 @@ public interface IStrategyFamily /// False for a point of the grid that makes no sense (a short average longer than the long one). bool Accepts(StrategyParameters parameters) => true; +} +/// A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid. +public interface IStrategyFamily : IResearchFamily +{ IStrategy Create(StrategyParameters parameters); } diff --git a/tests/Anubis.Tests/TrialEngineTests.cs b/tests/Anubis.Tests/TrialEngineTests.cs new file mode 100644 index 0000000..068bf0e --- /dev/null +++ b/tests/Anubis.Tests/TrialEngineTests.cs @@ -0,0 +1,361 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The seam between the trial judge and the engines (Phase 12, issue #118): the judge takes any +/// and any , the report gains an optional basket section, the plateau rule knows choice axes, +/// and nothing of what exists moves (the golden reports are in ). +/// +[TestClass] +public sealed class TrialEngineTests +{ + private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero); + private static readonly Guid Id = new("0b7e2c1d-5a3f-4e8b-9c6d-2f1a0e9d8c7b"); + private static readonly DateOnly First = new(2024, 1, 1); + + [TestMethod] + [TestCategory(Category.Unit)] + public void AnEngineThatIsNotDailyIsJudgedWithItsOwnSessionsYearFingerprintInstrumentsBenchmarkAndLimits() + { + var engine = new StubEngine(); + var (report, summary) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + + Assert.AreEqual(StubFamily.FamilyId, report.Strategy); + Assert.AreEqual("Famiglia finta", report.StrategyName); + Assert.AreEqual("USD", report.Currency); + Assert.AreEqual("USD", summary.Currency); + Assert.AreEqual(StubEngine.Year, report.PeriodsPerYear); + Assert.AreEqual(StubEngine.SessionCount, report.Sessions); + Assert.AreEqual("stub-data", report.DataFingerprint); + CollectionAssert.AreEqual(engine.Instruments().ToList(), report.Instruments.ToList()); + CollectionAssert.AreEqual(new[] { "Motore finto della prova." }, report.Limitations.ToList()); + + // The benchmark is the engine's own (here: stay flat), not buy and hold. + Assert.AreEqual(0d, report.Benchmark.TotalReturn); + Assert.IsTrue(report.Curve.All(p => p.Benchmark == StubEngine.Capital)); + + // Figures are annualised with the engine's periods per year. + var chosen = report.Variants.Single(v => v.Chosen).Parameters; + var expected = BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), StubEngine.Year); + Assert.AreEqual(expected.Sharpe, report.Metrics.Sharpe); + Assert.AreEqual(expected.AnnualReturn, report.Metrics.AnnualReturn); + Assert.AreNotEqual(BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), 365).Sharpe, report.Metrics.Sharpe); + + // What the engine expects and its look-ahead check reach the report as they are. + Assert.AreEqual(7.5m, report.ExpectedSlippageBp); + CollectionAssert.AreEqual(new[] { -0.01, -0.02 }, report.ExpectedPathP5!.ToList()); + Assert.AreEqual(42, report.LookAhead.Decisions); + Assert.IsTrue(report.LookAhead.Passed); + Assert.AreEqual(6, report.Variants.Count); + Assert.IsNull(report.Baskets); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheJudgeCallsTheEngineInTheOrderOfToday() + { + var engine = new StubEngine(); + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + var chosen = report.Variants.Single(v => v.Chosen).Parameters; + string[] expected = + [ + "run a=1;kind=0 x1", "run a=1;kind=1 x1", "run a=2;kind=0 x1", "run a=2;kind=1 x1", "run a=3;kind=0 x1", "run a=3;kind=1 x1", + $"run {chosen} x2", $"run {chosen} x3", "benchmark", $"look_ahead {chosen} 6", + ]; + CollectionAssert.AreEqual(expected, engine.Calls); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AJudgedVariantOutsideTheGridRunsOnceMoreOnTheEngine() + { + var engine = new StubEngine(); + var (report, _) = TrialRunner.Run(Id, StubPlan() with { Judged = "a=4;kind=1" }, "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now); + Assert.AreEqual("a=4;kind=1", report.Judged); + Assert.AreEqual("run a=4;kind=1 x1", engine.Calls[6]); + Assert.IsTrue(report.Variants[^1].OutsideGrid); + Assert.AreEqual(2, report.Limitations.Count); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportHasNoBasketsKeyWhenTheRunHasNone() + { + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine(), PriorTrials.None, Now); + Assert.IsNull(report.Baskets); + Assert.IsFalse(report.ToJson().Contains("\"baskets\"", StringComparison.Ordinal)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportCarriesTheBasketsOfTheRunWithUnitsLevelsLegsAndExitReasonAsItsLastSection() + { + var opened = new DateTimeOffset(2024, 3, 4, 14, 15, 0, TimeSpan.Zero); + BacktestBasket[] baskets = + [ + new("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, ["EURUSD", "USDCHF"], "target", 12.5m), + new("AUDUSD", opened.AddDays(1), null, 2_000m, 1, ["AUDUSD"], null, -3.25m), + ]; + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now); + + Assert.IsNotNull(report.Baskets); + Assert.AreEqual(2, report.Baskets.Count); + var first = report.Baskets[0]; + Assert.AreEqual(new ReportBasket("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, first.Legs, "target", 12.5m), first); + CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, first.Legs.ToList()); + Assert.IsNull(report.Baskets[1].Closed); + Assert.IsNull(report.Baskets[1].ExitReason); + + var json = report.ToJson(); + StringAssert.Contains(json, "\"units\":1000"); + StringAssert.Contains(json, "\"levels\":3"); + StringAssert.Contains(json, "\"legs\":[\"EURUSD\",\"USDCHF\"]"); + StringAssert.Contains(json, "\"exit_reason\":\"target\""); + Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"seconds\":", StringComparison.Ordinal), "The baskets come after every other field."); + Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"expected_slippage_bp\":", StringComparison.Ordinal)); + Assert.IsTrue(json.EndsWith("]}", StringComparison.Ordinal)); + + var back = BacktestReport.FromJson(json); + Assert.AreEqual(2, back.Baskets!.Count); + CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, back.Baskets[0].Legs.ToList()); + Assert.AreEqual(json, back.ToJson()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheReportKeepsOnlyTheLastBasketsUpToTheLimitOfTheTrades() + { + var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero); + var baskets = Enumerable.Range(0, TrialRunner.MaxTrades + 5) + .Select(i => new BacktestBasket("EURUSD", opened.AddHours(i), opened.AddHours(i + 1), 1_000m, 1, ["EURUSD"], "target", i)) + .ToArray(); + var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now); + Assert.AreEqual(TrialRunner.MaxTrades, report.Baskets!.Count); + Assert.AreEqual(5m, report.Baskets[0].Result); + Assert.AreEqual(TrialRunner.MaxTrades + 4m, report.Baskets[^1].Result); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheDailyEngineThroughTheNewOverloadGivesTheReportOfTheOldOne() + { + var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: First)); + var grid = new Dictionary> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] }; + var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"], + First.AddDays(60), First.AddDays(399), 10_000m, grid), Now).Plan; + var hash = TrialPlan.Hash(plan.ToJson()); + var family = MovingAverageCrossFamily.Instance; + + var engine = new DailyTrialEngine(plan, family, data); + Assert.AreEqual(data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To), engine.Sessions); + Assert.AreEqual(data.PeriodsPerYear, engine.PeriodsPerYear); + Assert.AreEqual(data.Currency, engine.Currency); + Assert.AreEqual(data.Fingerprint(), engine.Fingerprint()); + CollectionAssert.AreEqual(TrialRunner.Limitations(plan, family, data).ToList(), engine.Limitations().ToList()); + + var old = TrialRunner.Run(Id, plan, hash, family, data, PriorTrials.None, Now); + var seam = TrialRunner.Run(Id, plan, hash, family, engine, PriorTrials.None, Now); + Assert.AreEqual((old.Report with { Seconds = 0 }).ToJson(), (seam.Report with { Seconds = 0 }).ToJson()); + Assert.AreEqual(old.Summary.Chosen, seam.Summary.Chosen); + Assert.AreEqual(old.Summary.NetResult, seam.Summary.NetResult); + } + + /// + /// The hashes of plans built the way the laboratory and the protocols build them, recorded on commit 88b2883 before the + /// seam: a plan written today has the same hash, so the trial ids derived from it and the recorded outcomes do not move. + /// + [TestMethod] + [TestCategory(Category.Golden)] + public void APlanBuiltTodayHasTheHashItHadBeforeTheSeam() + { + var expected = new Dictionary + { + [StrategyNames.CryptoTrend] = "2a30b537ecf0d6a0d94794c5d9fe97695cc912d5a1ada6ca9c10382853d7b3cb", + ["equity_momentum"] = "9555ef93f3d90ae54ede9068f4db7dc38697f283ac586de6dff324c3475f4cd7", + ["equity_meanrev"] = "5b64b09419ba153703909c81b13b9934938d6f8ba1b984fc00330980ff0e082c", + [StrategyNames.StockAthBreakout] = "5bf77e99a0d2e4372002e9cc306cec84a98acee3804ace5dda8ab24ca90fb378", + [StrategyNames.CryptoRelativeMomentum] = "99a85eb937c80bbe14a5113973271fc73ca3f5f7ac966321bca3a9e44204985e", + [MovingAverageCrossFamily.FamilyId] = "952279ca4cd6193b08da61b96ecd12cac86c925a10c946099798dccb0c3326ca", + [BuyAndHoldFamily.FamilyId] = "8266b414ea78d9ad1317ce578f23e3def2bb37bcb28a6103fae1bab6bc082a06", + }; + var written = new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero); + Assert.AreEqual(expected.Count, StrategyCatalog.All.Count); + foreach (var family in StrategyCatalog.All) + { + var plan = Laboratory.BuildPlan(new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, ["BTCEUR", "ETHEUR"], + CryptoTrendProtocol.From, new DateOnly(2026, 10, 31), CryptoTrendProtocol.Capital), written).Plan; + Assert.AreEqual(expected[family.Id], TrialPlan.Hash(plan.ToJson()), family.Id); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePlateauRuleNeverTreatsTwoValuesOfAChoiceAxisAsNeighbours() + { + var variants = ParameterGrid.Of(StubFamily.Instance); + Assert.AreEqual(6, variants.Count); + Assert.IsTrue(variants.All(v => v.Choices is [false, true])); + + // Grid order: a = 1, 2, 3 outside, kind = 0, 1 inside. Kind 0 is a valley on the numeric axis, kind 1 a flat hill. + double[] values = [3, 5, 0, 5, 3, 5]; + var scores = Validation.PlateauScores(variants, values); + + // Kind 1 is averaged only with kind 1: no score is dragged down by the other choice. + Assert.AreEqual(5d, scores[1]); + Assert.AreEqual(5d, scores[3]); + Assert.AreEqual(5d, scores[5]); + + // The numeric axis still averages one step either side: (3 + 0) / 2 at the ends, min(0, 2) in the middle. + Assert.AreEqual(1.5, scores[0]); + Assert.AreEqual(0d, scores[2]); + Assert.AreEqual(1.5, scores[4]); + Assert.AreEqual(1, Validation.ChoosePlateau(variants, values)); + + // Without the choice mark the same grid mixes the two kinds, as the numeric rule always did. + var plain = variants.Select(v => v with { Choices = null }).ToList(); + Assert.AreEqual(3.25, Validation.PlateauScores(plain, values)[1]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AGridWithoutChoiceAxesMarksNoVariant() + { + Assert.IsTrue(ParameterGrid.Of(MovingAverageCrossFamily.Instance).All(v => v.Choices is null)); + Assert.IsTrue(StrategyCatalog.All.SelectMany(f => f.Parameters).All(p => !p.Choices)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EveryStrategyFamilyIsAResearchFamilyAndTheCatalogStillKnowsWhoNeedsTheWholeHistory() + { + Assert.IsTrue(typeof(IResearchFamily).IsAssignableFrom(typeof(IStrategyFamily))); + foreach (var family in StrategyCatalog.All) + { + Assert.IsInstanceOfType(family, family.Id); + } + + Assert.IsTrue(StrategyCatalog.Find(StrategyNames.StockAthBreakout) is { NeedsFullHistory: true }); + Assert.IsFalse(StrategyCatalog.Find(StrategyNames.CryptoTrend) is { NeedsFullHistory: true }); + IResearchFamily research = StockAthBreakoutFamily.Instance; + Assert.IsTrue(research.NeedsFullHistory); + IResearchFamily cross = MovingAverageCrossFamily.Instance; + Assert.IsFalse(cross.Accepts(new StrategyParameters([KeyValuePair.Create("fast", 50m), KeyValuePair.Create("slow", 20m)]))); + Assert.AreEqual("fast=20;slow=100", StrategyParameters.Of(cross, "fast=50;slow=20").ToString()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AResearchFamilyWithoutStrategiesHasItsGridAndItsParameters() + { + Assert.AreEqual("a=2;kind=1", StrategyParameters.Of(StubFamily.Instance, "a=2;kind=1").ToString()); + Assert.AreEqual("a=2;kind=0", StrategyParameters.Of(StubFamily.Instance, null).ToString()); + Assert.AreEqual(6, ParameterGrid.Of(StubFamily.Instance).Count); + Assert.IsFalse(typeof(IStrategyFamily).IsAssignableFrom(typeof(StubFamily))); + } + + private static TrialPlan StubPlan() => new( + StubFamily.FamilyId, + StubFamily.Instance.Version, + new SortedDictionary>(StringComparer.Ordinal) { ["a"] = [1m, 2m, 3m], ["kind"] = [0m, 1m] }, + new TrialData(TrialSources.Research, "dukascopy", ["EURUSD"], First, First.AddDays(StubEngine.Days - 1)), + StubEngine.Capital, + [1m, 2m, 3m], + TrialValidation.Default, + TrialThresholds.Default, + "stub", + Now); + + /// A research family that cannot build a strategy: a numeric axis and a choice axis. + private sealed class StubFamily : IResearchFamily + { + public const string FamilyId = "stub_baskets"; + + public static StubFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => "1"; + + public string Name => "Famiglia finta"; + + public string Description => "Famiglia finta per provare il giunto del giudice."; + + public IReadOnlyList Parameters => + [ + new("a", "Numero", 2m, [1m, 2m, 3m], 1m, 9m, Whole: true), + new("kind", "Tipo", 0m, [0m, 1m], 0m, 1m, Whole: true) { Choices = true }, + ]; + } + + /// An engine that is not daily: it builds its runs by hand, records every call and has its own figures. + private sealed class StubEngine : ITrialEngine + { + public const int Days = 320; + public const int SessionCount = 7_680; + public const int Year = 6_048; + public const decimal Capital = 10_000m; + + public List Calls { get; } = []; + + public IReadOnlyList Baskets { get; init; } = []; + + public string Currency => "USD"; + + public int PeriodsPerYear => Year; + + public int Sessions => SessionCount; + + public string Fingerprint() => "stub-data"; + + public IReadOnlyList Instruments() => [new("EURUSD", "dukascopy", First, First.AddDays(Days - 1), SessionCount, 0, "file")]; + + public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m) + { + Calls.Add(FormattableString.Invariant($"run {parameters} x{costMultiplier}")); + return Build(parameters, costMultiplier, Baskets); + } + + public BacktestRun Benchmark() + { + Calls.Add("benchmark"); + return new BacktestRun(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []); + } + + public LookAheadResult LookAhead(StrategyParameters parameters, int cuts) + { + Calls.Add(FormattableString.Invariant($"look_ahead {parameters} {cuts}")); + return new LookAheadResult([First.AddDays(100)], 42, []); + } + + public IReadOnlyList Limitations() => ["Motore finto della prova."]; + + public TrialExpectations Expected(BacktestRun run, double[] returns) => new(7.5m, [-0.01, -0.02]); + + /// A noisy equity whose drift depends on the parameters; costs lower it a little each day. + public static BacktestRun Build(StrategyParameters parameters, decimal costMultiplier, IReadOnlyList baskets) + { + var a = parameters.Whole("a"); + var kind = parameters.Whole("kind"); + var gen = new Gen((a * 10) + kind); + var drift = (0.0004 * a) - (0.0006 * kind); + var equity = new List(); + var value = Capital; + for (var i = 0; i < Days; i++) + { + if (i > 0) + { + value *= 1m + (decimal)(drift + (0.01 * gen.Normal())) - (0.0001m * (costMultiplier - 1m)); + value = Math.Round(value, 6); + } + + equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m)); + } + + return new BacktestRun("USD", Capital, equity, [], [], [], []) { Baskets = baskets }; + } + } +} -- 2.54.1 From aec848b4a2ba8285dd9d346c9cb408f5aec72ccf Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 09:57:50 +0100 Subject: [PATCH 4/6] Add the basket maths: server clock, relations, index, money rules, states Pure code in src/Anubis/Baskets for the basket reversion family of the new route, so the engine of phase 14 and the eToro Demo of phase 20 share one home for the arithmetic of the research document: - ServerClock: New York + 7 h, the server day changing at 17:00 New York, half-open weekend rule, hourly window and daily venue pause. - Relations: chain, ratio and disjoint couples (56 + 112 + 210 = 378), appendix B in the document's row order, the eight documented spreads, the index sign and the 14-pair list. - BasketIndex: pip and log basis-point index, sample z-score, Rvol with its filter, correlation of log returns and the OLS hedge ratio; every value at bar t reads bars up to t only. - BasketMath (decimal): pip sum, common exit, distance scale with no addition after the last level, stop excursion of table 4.12, pip value, equal units raised to the venue minimum, exposure, three-costs rule. - Styles: pair states, the four styles, the Fedele and Prudente profiles. Every acceptance criterion of the item has a named test with the document's numbers, plus a fixed-seed property test that nothing at a closed bar depends on later bars. refs #119 Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Baskets/BasketIndex.cs | 241 ++++++++++++++++ src/Anubis/Baskets/BasketMath.cs | 237 ++++++++++++++++ src/Anubis/Baskets/Relations.cs | 174 ++++++++++++ src/Anubis/Baskets/ServerClock.cs | 92 +++++++ src/Anubis/Baskets/Styles.cs | 153 ++++++++++ tests/Anubis.Tests/BasketMathTests.cs | 278 +++++++++++++++++++ tests/Anubis.Tests/BasketRelationTests.cs | 225 +++++++++++++++ tests/Anubis.Tests/BasketSignalTests.cs | 322 ++++++++++++++++++++++ tests/Anubis.Tests/ServerClockTests.cs | 162 +++++++++++ 9 files changed, 1884 insertions(+) create mode 100644 src/Anubis/Baskets/BasketIndex.cs create mode 100644 src/Anubis/Baskets/BasketMath.cs create mode 100644 src/Anubis/Baskets/Relations.cs create mode 100644 src/Anubis/Baskets/ServerClock.cs create mode 100644 src/Anubis/Baskets/Styles.cs create mode 100644 tests/Anubis.Tests/BasketMathTests.cs create mode 100644 tests/Anubis.Tests/BasketRelationTests.cs create mode 100644 tests/Anubis.Tests/BasketSignalTests.cs create mode 100644 tests/Anubis.Tests/ServerClockTests.cs diff --git a/src/Anubis/Baskets/BasketIndex.cs b/src/Anubis/Baskets/BasketIndex.cs new file mode 100644 index 0000000..4ab6d37 --- /dev/null +++ b/src/Anubis/Baskets/BasketIndex.cs @@ -0,0 +1,241 @@ +namespace Anubis.Baskets; + +/// +/// The index of a relation and the statistics on it (sections 4.2, 4.3, 4.7 and 11.3, appendix C): the index in pips and in +/// log basis points, the z-score, the relative volatility Rvol with its filter, the correlation of log returns and the hedge +/// ratio. Statistics are . Every value at bar t reads bars up to t only; which price feeds the index (mid +/// when bid and ask exist, bid otherwise) is the caller's choice. A missing value (not a number) inside a window gives null. +/// +public static class BasketIndex +{ + /// Bars of the z-score window: 100 bars of 15 minutes, 25 hours. + public const int DefaultWindow = 100; + + /// Differences in the short volatility window: 16 bars of 15 minutes, 4 hours. + public const int DefaultShortBars = 16; + + /// Market days of the volatility baseline. + public const int DefaultBaselineDays = 20; + + /// Bars of the baseline for 15-minute bars on a 24×5 market: 20 days × 96 bars. + public const int DefaultBaselineBars = DefaultBaselineDays * 96; + + /// Above this Rvol no new entry opens. + public const double DefaultMaxRvol = 2.0; + + private const double BasisPoints = 10_000; + + /// The pip index of two legs: X = A / pip(A) + s · B / pip(B). + public static double Pips(double priceA, FxPair a, double priceB, FxPair b, int sign) + { + ArgumentNullException.ThrowIfNull(b); + return Pips(priceA, a) + (sign * priceB / (double)b.Pip); + } + + /// The pip index of a single symbol: X = A / pip(A). + public static double Pips(double price, FxPair pair) + { + ArgumentNullException.ThrowIfNull(pair); + return price / (double)pair.Pip; + } + + /// + /// The log index in basis points (section 11.3): X = 10,000 · (ln A − β · ln B), β = 1 unless a hedge ratio is given. + /// For a relation of the 28 pairs in log form pass β = −s. + /// + public static double LogBp(double priceA, double priceB, double beta = 1) => BasisPoints * (Math.Log(priceA) - (beta * Math.Log(priceB))); + + /// The log index of a single symbol: X = 10,000 · ln P. + public static double LogBp(double price) => BasisPoints * Math.Log(price); + + /// + /// The z-score at closed bar : (X(t) − mean) / sample standard deviation (n − 1) of the last + /// values, bar t included. Null with fewer values than the window or a flat window. + /// + public static double? ZScore(IReadOnlyList index, int t, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + if (!Within(index, t) || t + 1 < window) + { + return null; + } + + var deviation = Deviation(index, t - window + 1, t, out var mean); + return deviation is > 0 ? (index[t] - mean) / deviation : null; + } + + /// + /// σ_short at bar : the sample standard deviation of the last first + /// differences of the index (shortBars + 1 values ending at t). Null when the history is shorter. + /// + public static double? ShortSigma(IReadOnlyList index, int t, int shortBars = DefaultShortBars) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(shortBars, 2); + if (!Within(index, t) || t < shortBars) + { + return null; + } + + var differences = new double[shortBars]; + for (var i = 0; i < shortBars; i++) + { + var at = t - shortBars + 1 + i; + differences[i] = index[at] - index[at - 1]; + } + + return Deviation(differences, 0, shortBars - 1, out _); + } + + /// Bars of the volatility baseline for a market with bars a day. + public static int BaselineBars(int barsPerDay, int days = DefaultBaselineDays) => barsPerDay * days; + + /// + /// Rvol at bar : σ_short(t) over σ_base(t), the median of σ_short over the last + /// bars ending at t. Null without enough history for every σ_short of the baseline, or + /// when σ_base is zero. + /// + public static double? Rvol(IReadOnlyList index, int t, int baselineBars = DefaultBaselineBars, int shortBars = DefaultShortBars) + { + ArgumentNullException.ThrowIfNull(index); + ArgumentOutOfRangeException.ThrowIfLessThan(baselineBars, 1); + if (!Within(index, t) || t - baselineBars + 1 < shortBars) + { + return null; + } + + var sigmas = new double[baselineBars]; + for (var i = 0; i < baselineBars; i++) + { + if (ShortSigma(index, t - baselineBars + 1 + i, shortBars) is not { } sigma) + { + return null; + } + + sigmas[i] = sigma; + } + + var current = sigmas[^1]; + Array.Sort(sigmas); + var middle = baselineBars / 2; + var baseline = baselineBars % 2 == 1 ? sigmas[middle] : (sigmas[middle - 1] + sigmas[middle]) / 2; + return baseline > 0 ? current / baseline : null; + } + + /// The volatility filter: a new entry only with a known Rvol no higher than . + public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max; + + /// + /// Pearson correlation of the log returns of two price series over the last returns ending at + /// bar (window + 1 prices). Null without enough prices, with a missing price or a flat leg. + /// + public static double? Correlation(IReadOnlyList pricesA, IReadOnlyList pricesB, int t, int window = DefaultWindow) + { + ArgumentNullException.ThrowIfNull(pricesA); + ArgumentNullException.ThrowIfNull(pricesB); + ArgumentOutOfRangeException.ThrowIfLessThan(window, 2); + if (!Within(pricesA, t) || !Within(pricesB, t) || t < window) + { + return null; + } + + var x = new double[window]; + var y = new double[window]; + for (var i = 0; i < window; i++) + { + var at = t - window + 1 + i; + x[i] = Math.Log(pricesA[at] / pricesA[at - 1]); + y[i] = Math.Log(pricesB[at] / pricesB[at - 1]); + } + + return Pearson(x, y); + } + + /// + /// The hedge ratio β of a statistical relation: the slope of the least-squares regression of ln A on ln B over the + /// formation window given. It stays fixed until the next reselection. Null with fewer than two points or a flat B. + /// + public static double? HedgeRatio(IReadOnlyList pricesA, IReadOnlyList pricesB) + { + ArgumentNullException.ThrowIfNull(pricesA); + ArgumentNullException.ThrowIfNull(pricesB); + if (pricesA.Count != pricesB.Count) + { + throw new ArgumentException("Le due serie del rapporto di copertura devono avere la stessa lunghezza.", nameof(pricesB)); + } + + if (pricesA.Count < 2) + { + return null; + } + + var y = pricesA.Select(p => Math.Log(p)).ToArray(); + var x = pricesB.Select(p => Math.Log(p)).ToArray(); + if (!y.All(double.IsFinite) || !x.All(double.IsFinite)) + { + return null; + } + + var meanX = x.Average(); + var meanY = y.Average(); + var covariance = 0d; + var variance = 0d; + for (var i = 0; i < x.Length; i++) + { + covariance += (x[i] - meanX) * (y[i] - meanY); + variance += (x[i] - meanX) * (x[i] - meanX); + } + + return variance > 0 ? covariance / variance : null; + } + + private static bool Within(IReadOnlyList values, int t) => t >= 0 && t < values.Count; + + /// Sample standard deviation of values[from..to]; null when a value is missing. + private static double? Deviation(IReadOnlyList values, int from, int to, out double mean) + { + var count = to - from + 1; + var sum = 0d; + for (var i = from; i <= to; i++) + { + sum += values[i]; + } + + mean = sum / count; + if (!double.IsFinite(mean)) + { + return null; + } + + var squares = 0d; + for (var i = from; i <= to; i++) + { + squares += (values[i] - mean) * (values[i] - mean); + } + + return Math.Sqrt(squares / (count - 1)); + } + + private static double? Pearson(double[] x, double[] y) + { + var meanX = x.Average(); + var meanY = y.Average(); + if (!double.IsFinite(meanX) || !double.IsFinite(meanY)) + { + return null; + } + + var sxy = 0d; + var sxx = 0d; + var syy = 0d; + for (var i = 0; i < x.Length; i++) + { + sxy += (x[i] - meanX) * (y[i] - meanY); + sxx += (x[i] - meanX) * (x[i] - meanX); + syy += (y[i] - meanY) * (y[i] - meanY); + } + + return sxx > 0 && syy > 0 ? Math.Clamp(sxy / Math.Sqrt(sxx * syy), -1, 1) : null; + } +} diff --git a/src/Anubis/Baskets/BasketMath.cs b/src/Anubis/Baskets/BasketMath.cs new file mode 100644 index 0000000..df3ec60 --- /dev/null +++ b/src/Anubis/Baskets/BasketMath.cs @@ -0,0 +1,237 @@ +namespace Anubis.Baskets; + +/// Buying or selling (section 4.4): a bought (long) order gains when the price rises, a sold (short) one when it falls. +public enum Direction +{ + Buy, + Sell, +} + +/// The two prices of a quote (section 4.5): a bought order closes at the bid, a sold one at the ask. +public readonly record struct BidAsk(decimal Bid, decimal Ask); + +/// One open order of a basket (section 4.5): pair, direction and entry price. +public sealed record BasketOrder(FxPair Pair, Direction Side, decimal Entry) +{ + /// Pips of the order at a quote: long (bid − entry) / pip, short (entry − ask) / pip. + public decimal Pips(BidAsk quote) => BasketMath.OrderPips(Side, Entry, quote, Pair.Pip); +} + +/// A leg for the exposure per currency (section 4.4, appendix C): units of the base at a price. +public sealed record ExposureLeg(FxPair Pair, Direction Side, decimal Units, decimal Price); + +/// Units on each leg of a unit (section 6.4); when the venue minimum lifted them. +public sealed record LegUnits(decimal Units, bool Raised) +{ + /// The effective lot the ledger records: units / 100,000. + public decimal Lot() => Units / BasketMath.LotUnits; +} + +/// +/// The money arithmetic of a basket, all in (sections 4.5, 4.6, 4.12, 6.4, 6.9 and 11.3, appendices A +/// and C): pip sum, common exit price, distance scale, stop excursion, pip value, equal units raised to the venue minimum, +/// exposure per currency and the three-costs rule. +/// +public static class BasketMath +{ + /// Units in one lot. + public const decimal LotUnits = 100_000m; + + /// The venue's minimum exposure per position, in USD (section 6.4). + public const decimal VenueMinimumUsd = 1_000m; + + /// A unit opens only when its target is at least this many times its cost (section 11.3). + public const decimal CostMultiple = 3m; + + /// Pips of one order: long (bid − entry) / pip, short (entry − ask) / pip. + public static decimal OrderPips(Direction side, decimal entry, BidAsk quote, decimal pip) => + side == Direction.Buy ? (quote.Bid - entry) / pip : (entry - quote.Ask) / pip; + + /// The pip sum of a basket: the pips of every open order, added. + public static decimal PipSum(IEnumerable orders, Func quotes) + { + ArgumentNullException.ThrowIfNull(orders); + ArgumentNullException.ThrowIfNull(quotes); + return orders.Sum(o => o.Pips(quotes(o.Pair))); + } + + /// + /// The common exit price of n equal orders on one symbol (section 4.5, appendix C): mean(entries) + target / n · pip for + /// longs (the bid reaches it), − target / n · pip for shorts (the ask reaches it). At that price the pip sum is the target. + /// + public static decimal CommonExit(IReadOnlyList entries, Direction side, decimal targetPips, decimal pip) + { + ArgumentNullException.ThrowIfNull(entries); + ArgumentOutOfRangeException.ThrowIfZero(entries.Count); + var move = MovePerOrder(targetPips, entries.Count) * pip; + var mean = entries.Sum() / entries.Count; + return side == Direction.Buy ? mean + move : mean - move; + } + + /// Table 4.5: the move beyond the mean entry each of n equal orders needs for the target, in pips (target / n). + public static decimal MovePerOrder(decimal targetPips, int orders) + { + ArgumentOutOfRangeException.ThrowIfLessThan(orders, 1); + return targetPips / orders; + } + + /// The distance factor of Rvol: max(1, min(Rvol, 3)). + public static decimal DistanceFactor(double rvol) => (decimal)Math.Max(1, Math.Min(Finite(rvol), 3)); + + /// The dynamic target factor of Rvol: max(0.7, min(Rvol, 3)). + public static decimal TargetFactor(double rvol) => (decimal)Math.Max(0.7, Math.Min(Finite(rvol), 3)); + + /// + /// The distance of the k-th re-entry (section 4.6, appendix C): Dmin × max(1, min(Rvol, 3)) × g^(k − 1), measured from + /// the last level, k = 1 … MaxReentries. + /// + public static decimal Distance(decimal minDistance, double rvol, decimal growth, int k) + { + ArgumentOutOfRangeException.ThrowIfLessThan(k, 1); + var distance = minDistance * DistanceFactor(rvol); + for (var i = 1; i < k; i++) + { + distance *= growth; + } + + return distance; + } + + /// The distances of every re-entry, k = 1 … . + public static IReadOnlyList Distances(decimal minDistance, double rvol, decimal growth, int maxReentries) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxReentries); + return [.. Enumerable.Range(1, maxReentries).Select(k => Distance(minDistance, rvol, growth, k))]; + } + + /// Whether a basket with levels open may add one: only while levels < 1 + MaxReentries. + public static bool CanAdd(int levels, int maxReentries) => levels >= 1 && levels < 1 + maxReentries; + + /// The distance the next level needs from the last one; null once the last level is open. + public static decimal? NextDistance(int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) => + CanAdd(levels, maxReentries) ? Distance(minDistance, rvol, growth, levels) : null; + + /// + /// Whether to add a level: a level may still be added and the last level has lost at least the distance. The lot of the + /// new level is the lot of the first; it never grows. + /// + public static bool ShouldAdd(decimal lastLevelPips, int levels, int maxReentries, decimal minDistance, double rvol, decimal growth) => + NextDistance(levels, maxReentries, minDistance, rvol, growth) is { } distance && lastLevelPips <= -distance; + + /// The pip sum of n levels, D apart, when the first level stands at E pips (appendix C): n·E + D·n(n − 1)/2. + public static decimal PipSumAtExcursion(int levels, decimal firstLevelPips, decimal distance) + { + ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1); + return (levels * firstLevelPips) + (distance * levels * (levels - 1) / 2); + } + + /// + /// The first-level excursion E ≤ 0 at which n full levels lose of the capital (table 4.12, + /// section 6.9): |n·E + D·n(n − 1)/2| × lot × pip value per lot = threshold × capital. Exact; the document's tables + /// show it rounded half to even. + /// + public static decimal StopExcursion(int levels, decimal distance, decimal lot, decimal pipValuePerLot, decimal threshold, decimal capital) + { + ArgumentOutOfRangeException.ThrowIfLessThan(levels, 1); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(lot); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot); + var pipSum = -(threshold * capital) / (lot * pipValuePerLot); + return (pipSum - (distance * levels * (levels - 1) / 2)) / levels; + } + + /// The lot that loses of the capital at the excursion E (appendix C). + public static decimal LotForRisk(int levels, decimal excursion, decimal distance, decimal pipValuePerLot, decimal threshold, decimal capital) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pipValuePerLot); + var pipSum = Math.Abs(PipSumAtExcursion(levels, excursion, distance)); + if (pipSum == 0) + { + throw new ArgumentException("A questa escursione la somma dei pip è zero: nessun lotto la porta alla soglia.", nameof(excursion)); + } + + return threshold * capital / (pipValuePerLot * pipSum); + } + + /// + /// The USD value of one unit of a currency (appendix C): 1 for the dollar, the price of XUSD when it is a pair, 1 / USDX + /// otherwise (usd(JPY) = 1 / USDJPY). + /// + public static decimal UsdPerUnit(string currency, Func price) + { + ArgumentNullException.ThrowIfNull(price); + if (currency == Currencies.Usd) + { + return 1m; + } + + var pair = FxPairs.Of(currency, Currencies.Usd) + ?? throw new ArgumentException($"{currency} non è una delle otto valute.", nameof(currency)); + return pair.Base == Currencies.Usd ? 1m / price(pair) : price(pair); + } + + /// The value of one pip in USD (appendix C): units × pip × usd(quote). + public static decimal PipValue(FxPair pair, decimal units, decimal usdPerQuote) + { + ArgumentNullException.ThrowIfNull(pair); + return units * pair.Pip * usdPerQuote; + } + + /// The value of one pip in USD, the quote currency valued at the prices given. + public static decimal PipValue(FxPair pair, decimal units, Func price) + { + ArgumentNullException.ThrowIfNull(pair); + return PipValue(pair, units, UsdPerUnit(pair.Quote, price)); + } + + /// + /// Equal units on every leg (section 6.4 and the forward-test phase): LotPer10k × capital / 10,000 × 100,000, in whole + /// units. When a leg would be worth less than the venue minimum, every leg rises to the units that bring the weakest leg + /// (the lowest USD value of its base) to the minimum, rounded up to whole units. + /// + public static LegUnits EqualUnits(decimal lotPer10k, decimal capital, IReadOnlyList usdPerBase, decimal minimumUsd = VenueMinimumUsd) + { + ArgumentNullException.ThrowIfNull(usdPerBase); + ArgumentOutOfRangeException.ThrowIfZero(usdPerBase.Count); + var weakest = usdPerBase.Min(); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weakest); + + var units = Math.Floor(lotPer10k * capital / 10_000m * LotUnits); + if (units * weakest >= minimumUsd) + { + return new LegUnits(units, false); + } + + return new LegUnits(Math.Ceiling(minimumUsd / weakest), true); + } + + /// + /// The net position per currency in native units (section 4.4, appendix C): a long of U units of BASEQUOTE at price P is + /// +U of the base and −U·P of the quote; a short reverses both signs. + /// + public static IReadOnlyDictionary Exposure(IEnumerable legs) + { + ArgumentNullException.ThrowIfNull(legs); + var net = new Dictionary(StringComparer.Ordinal); + foreach (var leg in legs) + { + var sign = leg.Side == Direction.Buy ? 1m : -1m; + net[leg.Pair.Base] = net.GetValueOrDefault(leg.Pair.Base) + (sign * leg.Units); + net[leg.Pair.Quote] = net.GetValueOrDefault(leg.Pair.Quote) - (sign * leg.Units * leg.Price); + } + + return net; + } + + /// The net position per currency valued in USD. + public static IReadOnlyDictionary UsdExposure(IReadOnlyDictionary native, Func price) + { + ArgumentNullException.ThrowIfNull(native); + return native.ToDictionary(e => e.Key, e => e.Value * UsdPerUnit(e.Key, price), StringComparer.Ordinal); + } + + /// The three-costs rule (section 11.3): a unit opens only if its target is at least three times its cost. + public static bool PassesCostRule(decimal targetPips, decimal costPips, decimal multiple = CostMultiple) => targetPips >= multiple * costPips; + + private static double Finite(double rvol) => + double.IsFinite(rvol) ? rvol : throw new ArgumentOutOfRangeException(nameof(rvol), rvol, "Rvol deve essere un numero finito."); +} diff --git a/src/Anubis/Baskets/Relations.cs b/src/Anubis/Baskets/Relations.cs new file mode 100644 index 0000000..42f15f9 --- /dev/null +++ b/src/Anubis/Baskets/Relations.cs @@ -0,0 +1,174 @@ +namespace Anubis.Baskets; + +/// The kinds of relation of section 4.1 (chain, ratio, disjoint) and the two of section 11 (statistical, single symbol). +public enum RelationKind +{ + /// The common currency is the quote of one pair and the base of the other: the synthetic is the product. + Chain, + + /// The common currency has the same role in both pairs: the synthetic is the ratio A / B. + Ratio, + + /// No common currency: no synthetic, the sign comes from the correlation. + Disjoint, + + /// Two instruments tied by a hedge ratio β from the regression of log prices. + Statistical, + + /// One symbol on its own. + SingleSymbol, +} + +/// +/// How two of the 28 pairs relate (section 4.1). is the listed pair equivalent to the synthetic: for a +/// chain the product A × B, always a listed pair; for a ratio the quotient A / B, which may be the inverse of the listed pair +/// (). Kind, common currency and cross never depend on the order of the legs; only the +/// orientation of a ratio's quotient does. +/// +public sealed record PairRelation(FxPair A, FxPair B, RelationKind Kind, string? Common, FxPair? Cross, bool CrossInverted) +{ + /// The sign s of the pip index (section 4.2); null when the couple has no sign and cannot be traded. + public int? Sign(double? correlation = null) => Relations.Sign(Kind, correlation); +} + +/// A row of appendix B: leg A ends in the common currency, leg B starts with it, buying both buys the cross. +public sealed record ChainRow(int Row, FxPair A, FxPair B, FxPair Cross, bool Listed); + +/// A two-leg spread as the document writes it (section 3.3), leg A first. +public sealed record DocumentedSpread(FxPair A, FxPair B); + +/// +/// The relations among the 28 pairs (section 4.1, appendix B, appendix C): classification, the 378 couples, the 56 chains in +/// the document's order, the eight documented spreads (section 3.3) and the 14-pair list (section 4.9). +/// +public static class Relations +{ + private static readonly int[] ListedRows = [3, 9, 17, 29, 30, 35]; + + /// The 378 unordered couples of the 28 pairs, each once, in appendix A order: 56 chains, 112 ratios, 210 disjoint. + public static IReadOnlyList Couples { get; } = Array.AsReadOnly(BuildCouples()); + + /// + /// Appendix B: for each common currency c from GBP to CHF, every a before c and every b after c in the currency order, + /// A = a c, B = c b, cross = a b. Rows 3, 9, 17, 29, 30 and 35 are the ones the documented editions list. + /// + public static IReadOnlyList AppendixB { get; } = Array.AsReadOnly(BuildAppendixB()); + + /// The eight spreads of section 3.3, in the document's leg order: six chains and two disjoint couples. + public static IReadOnlyList DocumentedSpreads { get; } = Array.AsReadOnly( + [ + new(FxPairs.Get("EURUSD"), FxPairs.Get("USDCHF")), + new(FxPairs.Get("AUDUSD"), FxPairs.Get("USDCAD")), + new(FxPairs.Get("NZDUSD"), FxPairs.Get("EURNZD")), + new(FxPairs.Get("USDCAD"), FxPairs.Get("EURUSD")), + new(FxPairs.Get("EURAUD"), FxPairs.Get("AUDCAD")), + new(FxPairs.Get("GBPUSD"), FxPairs.Get("EURGBP")), + new(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF")), + new(FxPairs.Get("EURCHF"), FxPairs.Get("AUDCAD")), + ]); + + /// The 14-pair list (section 4.9): the twelve documented symbols plus EURCAD and AUDNZD, in appendix A order. + public static IReadOnlyList FourteenPairs { get; } = Array.AsReadOnly( + new[] + { + "EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD", + "AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF", + }.Select(FxPairs.Get).ToArray()); + + /// Classifies two different pairs; the result never depends on which one is given first, except for a ratio's orientation. + public static PairRelation Classify(FxPair a, FxPair b) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + if (a == b) + { + throw new ArgumentException($"Una relazione vuole due coppie diverse, non {a.Name} due volte.", nameof(b)); + } + + var common = Shared(a, b); + if (common is null) + { + return new PairRelation(a, b, RelationKind.Disjoint, null, null, false); + } + + // Chain: x/c × c/y = x/y. The listed pairs give x before c before y, so the cross is always listed. + if (a.Quote == common && b.Base == common) + { + return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(a.Base, b.Quote), false); + } + + if (a.Base == common && b.Quote == common) + { + return new PairRelation(a, b, RelationKind.Chain, common, FxPairs.Of(b.Base, a.Quote), false); + } + + // Ratio. Both quote c: (c per x) / (c per y) = y per x, the pair x/y. Both base c: (x per c) / (y per c) = x per y, + // the pair y/x. The listed pair may be the other way round. + var otherA = a.Base == common ? a.Quote : a.Base; + var otherB = b.Base == common ? b.Quote : b.Base; + var syntheticBase = a.Quote == common ? otherA : otherB; + var cross = FxPairs.Of(otherA, otherB)!; + return new PairRelation(a, b, RelationKind.Ratio, common, cross, cross.Base != syntheticBase); + } + + /// + /// The sign s of the pip index X = A / pip(A) + s · B / pip(B) (section 4.2, appendix C): +1 for a chain, −1 for a ratio, + /// −sign(ρ) for a disjoint couple. A disjoint couple with ρ zero, unknown or not a number has no sign: null. + /// + public static int? Sign(RelationKind kind, double? correlation) => kind switch + { + RelationKind.Chain => 1, + RelationKind.Ratio => -1, + RelationKind.Disjoint => correlation is { } rho && rho != 0 && !double.IsNaN(rho) ? -Math.Sign(rho) : null, + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Il segno dell'indice in pip vale solo per catena, rapporto e disgiunta."), + }; + + private static string? Shared(FxPair a, FxPair b) + { + if (a.Base == b.Base || a.Base == b.Quote) + { + return a.Base; + } + + return a.Quote == b.Base || a.Quote == b.Quote ? a.Quote : null; + } + + private static PairRelation[] BuildCouples() + { + var pairs = FxPairs.All; + var couples = new List(pairs.Count * (pairs.Count - 1) / 2); + for (var i = 0; i < pairs.Count; i++) + { + for (var j = i + 1; j < pairs.Count; j++) + { + couples.Add(Classify(pairs[i], pairs[j])); + } + } + + return [.. couples]; + } + + private static ChainRow[] BuildAppendixB() + { + var order = Currencies.Order; + var rows = new List(56); + for (var c = 1; c < order.Count - 1; c++) + { + for (var a = 0; a < c; a++) + { + for (var b = c + 1; b < order.Count; b++) + { + var row = rows.Count + 1; + rows.Add(new ChainRow( + row, + FxPairs.Get(order[a] + order[c]), + FxPairs.Get(order[c] + order[b]), + FxPairs.Get(order[a] + order[b]), + ListedRows.Contains(row))); + } + } + } + + return [.. rows]; + } +} diff --git a/src/Anubis/Baskets/ServerClock.cs b/src/Anubis/Baskets/ServerClock.cs new file mode 100644 index 0000000..53cb62a --- /dev/null +++ b/src/Anubis/Baskets/ServerClock.cs @@ -0,0 +1,92 @@ +using Anubis.Data; + +namespace Anubis.Baskets; + +/// +/// A window of the day on a wall clock (section 4.7), half-open: is inside, is not. When +/// comes before the window crosses midnight. +/// +public sealed record DailyWindow(TimeOnly From, TimeOnly To) +{ + public bool Contains(TimeOnly time) => From <= To ? time >= From && time < To : time >= From || time < To; +} + +/// +/// The server clock of the research document (section 4.7 and appendix C): New York time plus seven hours, so it follows +/// the United States' daylight saving only (UTC+2 in winter, UTC+3 in summer). The server day changes at 17:00 New York. +/// Every window is half-open: the weekend rule (no new entries from Friday 16:00 to Monday 02:00 server time), the hourly +/// window (10:00 to 20:00 server time, when it is on) and the daily venue pause (16:55 to 18:10 New York time). +/// +public static class ServerClock +{ + /// How far the server clock is ahead of New York. + public static readonly TimeSpan AheadOfNewYork = TimeSpan.FromHours(7); + + /// First server time of the weekend rule, on Friday. + public static readonly TimeOnly WeekendFrom = new(16, 0); + + /// First server time after the weekend rule, on Monday. + public static readonly TimeOnly WeekendTo = new(2, 0); + + /// The hourly window, in server time. + public static DailyWindow Session { get; } = new(new TimeOnly(10, 0), new TimeOnly(20, 0)); + + /// The daily venue pause, in New York time: no entries and no averaging inside it. + public static DailyWindow DailyPauseNewYork { get; } = new(new TimeOnly(16, 55), new TimeOnly(18, 10)); + + /// The server wall clock at a moment. + public static DateTime ToServer(DateTimeOffset moment) => NewYork(moment) + AheadOfNewYork; + + /// The moment a server wall-clock time names. In the hour New York's clock goes back, standard time wins. + public static DateTimeOffset FromServer(DateTime server) + { + var newYork = DateTime.SpecifyKind(server - AheadOfNewYork, DateTimeKind.Unspecified); + return new DateTimeOffset(newYork, Zones.NewYork.GetUtcOffset(newYork)).ToUniversalTime(); + } + + /// How far the server clock is ahead of UTC at a moment: two hours in winter, three in summer. + public static TimeSpan OffsetFromUtc(DateTimeOffset moment) => ToServer(moment) - moment.UtcDateTime; + + /// The server day of a moment: the date of the server clock. + public static DateOnly Day(DateTimeOffset moment) => DateOnly.FromDateTime(ToServer(moment)); + + /// The moment of a server time on a server day. + public static DateTimeOffset At(DateOnly day, TimeOnly time) => FromServer(day.ToDateTime(time)); + + /// Server midnight: 17:00 New York of the day before. + public static DateTimeOffset DayStart(DateOnly day) => At(day, TimeOnly.MinValue); + + /// The start of the server day after the one of : when entries resume after the equity stop. + public static DateTimeOffset NextDayStart(DateTimeOffset moment) => DayStart(Day(moment).AddDays(1)); + + /// True from Friday 16:00 to Monday 02:00 server time (Monday 02:00 excluded). + public static bool InWeekend(DateTimeOffset moment) + { + var server = ToServer(moment); + var time = TimeOnly.FromDateTime(server); + return server.DayOfWeek switch + { + DayOfWeek.Friday => time >= WeekendFrom, + DayOfWeek.Saturday or DayOfWeek.Sunday => true, + DayOfWeek.Monday => time < WeekendTo, + _ => false, + }; + } + + /// True inside the hourly window, in server time; replaces 10:00–20:00. + public static bool InSession(DateTimeOffset moment, DailyWindow? window = null) => + (window ?? Session).Contains(TimeOnly.FromDateTime(ToServer(moment))); + + /// True inside the daily venue pause, in New York time; replaces 16:55–18:10. + public static bool InDailyPause(DateTimeOffset moment, DailyWindow? pause = null) => + (pause ?? DailyPauseNewYork).Contains(TimeOnly.FromDateTime(NewYork(moment))); + + /// + /// Whether the clock allows a new entry: outside the weekend rule and the daily pause, and inside the hourly window when + /// it is on. + /// + public static bool EntriesAllowed(DateTimeOffset moment, bool sessionOn) => + !InWeekend(moment) && !InDailyPause(moment) && (!sessionOn || InSession(moment)); + + private static DateTime NewYork(DateTimeOffset moment) => TimeZoneInfo.ConvertTime(moment, Zones.NewYork).DateTime; +} diff --git a/src/Anubis/Baskets/Styles.cs b/src/Anubis/Baskets/Styles.cs new file mode 100644 index 0000000..d7a58f3 --- /dev/null +++ b/src/Anubis/Baskets/Styles.cs @@ -0,0 +1,153 @@ +namespace Anubis.Baskets; + +/// The state of a pair on the panel (section 4.9): ferma, in osservazione, pronta, aperta. +public enum PairState +{ + /// Ferma: |z| below the watch threshold. + Idle, + + /// In osservazione: |z| at or above the watch threshold. + Watch, + + /// Pronta: |z| at or above the entry threshold, but a gate blocks the entry. + Armed, + + /// Aperta: every gate passes, or a unit is already open. + Open, +} + +/// The states of a pair, the entry signal and the closing of the spread (sections 4.3 and 4.9). +public static class PairStates +{ + /// |z| from which a pair is watched. + public const double DefaultWatchZ = 1.5; + + /// |z| at or below which the spread counts as closed. + public const double DefaultSpreadClosedZ = 0.5; + + /// + /// The state at a closed bar: with a unit open or with |z| ≥ entry and every gate passing; + /// with |z| ≥ entry and a gate blocking; with |z| ≥ watch; + /// otherwise, and without a z-score. + /// + public static PairState Of(double? z, double entryZ, bool gatesPass, bool hasOpenUnit = false, double watchZ = DefaultWatchZ) + { + if (hasOpenUnit) + { + return PairState.Open; + } + + if (z is not { } value || double.IsNaN(value)) + { + return PairState.Idle; + } + + var size = Math.Abs(value); + if (size >= entryZ) + { + return gatesPass ? PairState.Open : PairState.Armed; + } + + return size >= watchZ ? PairState.Watch : PairState.Idle; + } + + /// The entry signal: buy the spread at z ≤ −entry, sell it at z ≥ +entry, nothing otherwise. + public static Direction? Signal(double? z, double entryZ) => z switch + { + { } value when value <= -entryZ => Direction.Buy, + { } value when value >= entryZ => Direction.Sell, + _ => null, + }; + + /// Whether the spread has closed: |z| ≤ . + public static bool SpreadClosed(double? z, double closedZ = DefaultSpreadClosedZ) => z is { } value && Math.Abs(value) <= closedZ; +} + +/// +/// One of the four styles of section 4.7: entry threshold, spreads open at once, averagings; the growth variant (1.3) allows +/// . +/// +public sealed record TradingStyle(string Name, double EntryZ, int MaxOpenSpreads, int MaxAveragings, int MaxAveragingsWithGrowth); + +/// The four styles of section 4.7; Moderato is the default. +public static class TradingStyles +{ + public static TradingStyle HedgeFund { get; } = new("HedgeFund", 3.0, 1, 2, 2); + + public static TradingStyle Conservativo { get; } = new("Conservativo", 2.5, 2, 3, 3); + + public static TradingStyle Moderato { get; } = new("Moderato", 2.0, 2, 3, 3); + + public static TradingStyle Aggressivo { get; } = new("Aggressivo", 1.5, 3, 3, 4); + + public static TradingStyle Default => Moderato; + + public static IReadOnlyList All { get; } = Array.AsReadOnly(new[] { HedgeFund, Conservativo, Moderato, Aggressivo }); + + /// The style with this name, or null. + public static TradingStyle? Find(string name) => All.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.Ordinal)); +} + +/// +/// A risk profile of the basket logic (sections 5 and 7.1, appendix D). Fractions are of the balance or of equity: +/// 0.09 is 9%. A null stop is a stop that does not exist; a null exposure cap means the cap is only logged. +/// +/// Fedele or Prudente. +/// Basket stop when |z| reaches this value. +/// Basket stop when its loss reaches this fraction of equity. +/// Basket stop when the relation breaks (the correlation loses its expected sign). +/// Basket stop after this many bars open. +/// Everything closes when open loss ÷ balance reaches this fraction. +/// After the equity stop entries resume at the next server day. +/// The three-costs rule blocks entries (otherwise it is only logged). +/// Net exposure per currency, in multiples of one entry's exposure. +/// Allowed only in backtest, simulator and Demo. +public sealed record BasketProfile( + string Name, + double? StopZ, + decimal? StopLoss, + bool StopOnBrokenRelation, + int? StopAfterBars, + decimal EquityStop, + bool ResumeAtNextServerDay, + bool CostGate, + decimal? MaxCurrencyExposure, + bool OffRealAccountsOnly) +{ + /// Whether any basket stop is on. + public bool HasBasketStops() => StopZ is not null || StopLoss is not null || StopOnBrokenRelation || StopAfterBars is not null; +} + +/// +/// The two profiles: Fedele, the document as written (no basket stop, equity stop at 9% with resume at the next server day, +/// only off real accounts); Prudente, the same logic with the basket stops (z 3.5, loss 1% — the document's 1.5% reduced by +/// SPEC 9.2 — broken relation, 96 bars), the cost gate and the currency exposure cap 2.0. +/// +public static class BasketProfiles +{ + public static BasketProfile Fedele { get; } = new( + "Fedele", + StopZ: null, + StopLoss: null, + StopOnBrokenRelation: false, + StopAfterBars: null, + EquityStop: 0.09m, + ResumeAtNextServerDay: true, + CostGate: false, + MaxCurrencyExposure: null, + OffRealAccountsOnly: true); + + public static BasketProfile Prudente { get; } = new( + "Prudente", + StopZ: 3.5, + StopLoss: 0.01m, + StopOnBrokenRelation: true, + StopAfterBars: 96, + EquityStop: 0.09m, + ResumeAtNextServerDay: true, + CostGate: true, + MaxCurrencyExposure: 2.0m, + OffRealAccountsOnly: false); + + public static IReadOnlyList All { get; } = Array.AsReadOnly(new[] { Fedele, Prudente }); +} diff --git a/tests/Anubis.Tests/BasketMathTests.cs b/tests/Anubis.Tests/BasketMathTests.cs new file mode 100644 index 0000000..1822c50 --- /dev/null +++ b/tests/Anubis.Tests/BasketMathTests.cs @@ -0,0 +1,278 @@ +using System.Globalization; +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// The money side of the basket maths (Phase 12, issue #119): pip sum and common exit, table 4.5, the distance scale, the +/// stop excursions of table 4.12 and section 6.9, pip value, units raised to the venue minimum, exposure and the three-costs +/// rule. Every expected number is the document's, or worked out by hand in the comment next to it. +/// +[TestClass] +public sealed class BasketMathTests +{ + private static readonly decimal[] AudusdEntries = [0.69456m, 0.69003m, 0.68739m]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThreeAudusdBuysWithTarget69ExitAtTheCommonPrice() + { + var pair = FxPairs.Get("AUDUSD"); + + // mean = 2.07198 / 3 = 0.69066; target / n = 6.9 / 3 = 2.3 pips = 0.00023; P* = 0.69089. + var exit = BasketMath.CommonExit(AudusdEntries, Direction.Buy, 6.9m, pair.Pip); + Assert.IsTrue(Math.Abs(exit - 0.69089m) <= 0.1m * pair.Pip, exit.ToString(CultureInfo.InvariantCulture)); + + // At that bid each order has −36.7, +8.6 and +35.0 pips, +6.9 in all. + var quote = new BidAsk(0.69089m, 0.69095m); + var orders = AudusdEntries.Select(e => new BasketOrder(pair, Direction.Buy, e)).ToArray(); + CollectionAssert.AreEqual(new[] { -36.7m, 8.6m, 35.0m }, orders.Select(o => o.Pips(quote)).ToArray()); + Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => quote)); + Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => new BidAsk(exit, exit + 0.00006m))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ShortOrdersExitBelowTheMeanAndCountPipsOnTheAsk() + { + var pair = FxPairs.Get("USDJPY"); + decimal[] entries = [157.20m, 157.60m, 158.00m]; + + // mean 157.60, target 9 over 3 orders = 3 pips = 0.03 below: 157.57. + var exit = BasketMath.CommonExit(entries, Direction.Sell, 9m, pair.Pip); + Assert.AreEqual(157.57m, exit); + + var orders = entries.Select(e => new BasketOrder(pair, Direction.Sell, e)).ToArray(); + Assert.AreEqual(9m, BasketMath.PipSum(orders, _ => new BidAsk(157.55m, exit))); + CollectionAssert.AreEqual(new[] { -37m, 3m, 43m }, orders.Select(o => o.Pips(new BidAsk(157.55m, exit))).ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(1, "10.00")] + [DataRow(2, "5.00")] + [DataRow(3, "3.33")] + [DataRow(4, "2.50")] + [DataRow(5, "2.00")] + [DataRow(8, "1.25")] + public void TheMovePerOrderFollowsTable45(int orders, string expected) + { + var move = BasketMath.MovePerOrder(10m, orders); + Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), Math.Round(move, 2)); + + // The same identity as the common exit: P* − mean = target / n pips. + var entries = Enumerable.Range(0, orders).Select(i => 1.1000m - (i * 0.0040m)).ToArray(); + var exit = BasketMath.CommonExit(entries, Direction.Buy, 10m, 0.0001m); + AssertClose(move * 0.0001m, exit - entries.Average(), 0.0000000000000000001m); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(0.8, "1.0", "40", "40", "40", "40")] + [DataRow(0.8, "1.3", "40", "52", "67.6", "87.88")] + [DataRow(1.5, "1.0", "60", "60", "60", "60")] + [DataRow(1.5, "1.3", "60", "78", "101.4", "131.82")] + [DataRow(4.0, "1.0", "120", "120", "120", "120")] + [DataRow(4.0, "1.3", "120", "156", "202.8", "263.64")] + public void TheDistanceScaleFollowsRvolAndTheGrowth(double rvol, string growth, string d1, string d2, string d3, string d4) + { + var g = decimal.Parse(growth, CultureInfo.InvariantCulture); + decimal[] expected = [.. new[] { d1, d2, d3, d4 }.Select(d => decimal.Parse(d, CultureInfo.InvariantCulture))]; + + for (var k = 1; k <= 4; k++) + { + Assert.AreEqual(expected[k - 1], BasketMath.Distance(40m, rvol, g, k), $"k = {k}"); + } + + CollectionAssert.AreEqual(expected, BasketMath.Distances(40m, rvol, g, maxReentries: 4).ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoLevelIsAddedAfterTheLast() + { + // Three re-entries: four levels at most; the k-th addition is the one made with k levels open. + for (var levels = 1; levels <= 3; levels++) + { + Assert.IsTrue(BasketMath.CanAdd(levels, maxReentries: 3)); + Assert.AreEqual(BasketMath.Distance(40m, 1.0, 1.3m, levels), BasketMath.NextDistance(levels, 3, 40m, 1.0, 1.3m)); + } + + Assert.IsFalse(BasketMath.CanAdd(4, maxReentries: 3)); + Assert.IsNull(BasketMath.NextDistance(4, 3, 40m, 1.0, 1.3m)); + Assert.IsFalse(BasketMath.ShouldAdd(-10_000m, levels: 4, maxReentries: 3, 40m, 1.0, 1.3m)); + + // With four re-entries (growth variant) the fifth level is the last. + Assert.IsTrue(BasketMath.CanAdd(4, maxReentries: 4)); + Assert.IsFalse(BasketMath.CanAdd(5, maxReentries: 4)); + Assert.IsFalse(BasketMath.CanAdd(0, maxReentries: 3)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ALevelIsAddedOnlyWhenTheLastLevelHasLostTheDistance() + { + // Second level (k = 1): 40 pips; third (k = 2) with growth 1.3: 52 pips, measured from the last level. + Assert.IsFalse(BasketMath.ShouldAdd(-39.9m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsTrue(BasketMath.ShouldAdd(-40m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsFalse(BasketMath.ShouldAdd(-51.9m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m)); + Assert.IsTrue(BasketMath.ShouldAdd(-52m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("0.01", "40", -2310)] + [DataRow("0.02", "40", -1185)] + [DataRow("0.05", "40", -510)] + [DataRow("0.10", "40", -285)] + [DataRow("0.01", "65", -2348)] + [DataRow("0.02", "65", -1222)] + [DataRow("0.05", "65", -548)] + [DataRow("0.10", "65", -322)] + public void TheEightExcursionsOfTable412(string lot, string distance, int expected) + { + var l = decimal.Parse(lot, CultureInfo.InvariantCulture); + var d = decimal.Parse(distance, CultureInfo.InvariantCulture); + + // Account 10,000 USD, stop at 9%, 10 USD per lot per pip, 1 + 3 levels; shown values rounded half to even. + var excursion = BasketMath.StopExcursion(4, d, l, 10m, 0.09m, 10_000m); + Assert.AreEqual((decimal)expected, Math.Round(excursion)); + + // At that excursion the pip sum loses exactly the 9%: 900 USD. + Assert.AreEqual(-900m, BasketMath.PipSumAtExcursion(4, excursion, d) * l * 10m); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(500, -172)] + [DataRow(1000, -285)] + [DataRow(2500, -622)] + [DataRow(5000, -1185)] + [DataRow(10000, -2310)] + [DataRow(25000, -5685)] + public void TheCapitalTableOfSection69(int capital, int expected) + { + // Lot 0.01 (the pip sum is worth 0.1 USD), D = 40, four levels, 9% of capital. + Assert.AreEqual((decimal)expected, Math.Round(BasketMath.StopExcursion(4, 40m, 0.01m, 10m, 0.09m, capital))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheLotForAGivenRiskInvertsTheExcursion() + { + // 0.09 × 10,000 / (10 × |4 × −285 + 6 × 40|) = 900 / 9,000 = 0.10. + Assert.AreEqual(0.10m, BasketMath.LotForRisk(4, -285m, 40m, 10m, 0.09m, 10_000m)); + Assert.AreEqual(4 * -100m + (6 * 40m), BasketMath.PipSumAtExcursion(4, -100m, 40m)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipValueOfAYenPairIsUnitsTimesPipOverUsdjpy() + { + // The ECB test day of the plan: USDJPY = 176.79 / 1.1193. + var usdjpy = 176.79m / 1.1193m; + var prices = Prices(("USDJPY", usdjpy)); + + Assert.AreEqual(1m / usdjpy, BasketMath.UsdPerUnit(Currencies.Jpy, prices)); + AssertClose(10m / usdjpy, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices)); + AssertClose(9.21m / usdjpy, BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, prices)); + AssertClose(8.47m / usdjpy, BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, prices)); + AssertClose(0.0633124m, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices), 0.0000001m); + + // Appendix A, units per 1,000 USD with USDJPY about 160.3: 0.062, 0.057 and 0.053 USD per pip. + var appendix = Prices(("USDJPY", 160.3m)); + Assert.AreEqual(0.062m, Math.Round(BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, appendix), 3)); + Assert.AreEqual(0.057m, Math.Round(BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, appendix), 3)); + Assert.AreEqual(0.053m, Math.Round(BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, appendix), 3)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipValueOfOtherQuotesUsesTheirDollarValue() + { + var prices = Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m), ("AUDUSD", 0.6623m)); + + Assert.AreEqual(1m, BasketMath.UsdPerUnit(Currencies.Usd, prices)); + Assert.AreEqual(1.0856m, BasketMath.UsdPerUnit(Currencies.Eur, prices)); + Assert.AreEqual(0.1m, BasketMath.PipValue(FxPairs.Get("EURUSD"), 1000m, prices)); + Assert.AreEqual(0.1m / 0.847m, BasketMath.PipValue(FxPairs.Get("USDCHF"), 1000m, prices)); + + // Appendix A: 1,510 AUDUSD units per 1,000 USD are worth 0.151 USD per pip. + Assert.AreEqual(0.151m, BasketMath.PipValue(FxPairs.Get("AUDUSD"), 1510m, prices)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void BothLegsRiseToTheUnitsThatBringTheWeakestToTheVenueMinimum() + { + // 0.01 lot per 10,000 USD on 10,000 USD: 1,000 units, worth 662.3 USD on an AUD base, under the 1,000 USD minimum. + // 1,000 / 0.6623 = 1,509.89, rounded up: 1,510 on both legs (appendix A). + var aud = BasketMath.EqualUnits(0.01m, 10_000m, [1.0856m, 0.6623m]); + Assert.AreEqual(1510m, aud.Units); + Assert.IsTrue(aud.Raised); + Assert.AreEqual(0.0151m, aud.Lot()); + + // NZD base: 1,000 / 0.54172 = 1,845.97, rounded up: 1,846. (Appendix A rounds to the nearest unit: at exactly 0.5417 + // the minimum needs 1,846.04, so 1,847 rounded up.) + var nzd = BasketMath.EqualUnits(0.01m, 10_000m, [0.6623m, 0.54172m]); + Assert.AreEqual(1846m, nzd.Units); + Assert.IsTrue(nzd.Units * 0.54172m >= 1000m); + Assert.AreEqual(1847m, BasketMath.EqualUnits(0.01m, 10_000m, [0.5417m]).Units); + + // Above the minimum nothing moves: 2,000 units are 1,083 USD on the NZD leg. + var enough = BasketMath.EqualUnits(0.01m, 20_000m, [0.6623m, 0.54172m]); + Assert.AreEqual(2000m, enough.Units); + Assert.IsFalse(enough.Raised); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheNetExposureOfEqualUnitsOnEurusdAndUsdchf() + { + // Long 1,000 EURUSD at 1.0856: +1,000 EUR, −1,085.6 USD. Long 1,000 USDCHF at 0.847: +1,000 USD, −847 CHF. + var exposure = BasketMath.Exposure( + [ + new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Buy, 1000m, 1.0856m), + new ExposureLeg(FxPairs.Get("USDCHF"), Direction.Buy, 1000m, 0.847m), + ]); + + Assert.AreEqual(3, exposure.Count); + Assert.AreEqual(1000m, exposure[Currencies.Eur]); + Assert.AreEqual(-85.6m, exposure[Currencies.Usd]); + Assert.AreEqual(-86m, Math.Round(exposure[Currencies.Usd])); + Assert.AreEqual(-847m, exposure[Currencies.Chf]); + + // Selling reverses every sign; in dollars the base is valued at its own price. + var sold = BasketMath.Exposure([new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Sell, 1000m, 1.0856m)]); + Assert.AreEqual(-1000m, sold[Currencies.Eur]); + Assert.AreEqual(1085.6m, sold[Currencies.Usd]); + var dollars = BasketMath.UsdExposure(exposure, Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m))); + Assert.AreEqual(1085.6m, dollars[Currencies.Eur]); + AssertClose(-1000m, dollars[Currencies.Chf]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheThreeCostsRulePassesThreeOfTheFiveDocumentedSpreads() + { + decimal[] costs = [2.1m, 2.5m, 6.9m, 2.9m, 4.7m]; + var passing = costs.Where(c => BasketMath.PassesCostRule(10m, c)).ToArray(); + + CollectionAssert.AreEqual(new[] { 2.1m, 2.5m, 2.9m }, passing); + Assert.IsFalse(BasketMath.PassesCostRule(10m, 6.9m)); + Assert.IsFalse(BasketMath.PassesCostRule(10m, 4.7m)); + + // Exactly three times the cost still passes. + Assert.IsTrue(BasketMath.PassesCostRule(9m, 3m)); + Assert.IsFalse(BasketMath.PassesCostRule(8.99m, 3m)); + } + + private static Func Prices(params (string Pair, decimal Price)[] prices) + { + var map = prices.ToDictionary(p => p.Pair, p => p.Price, StringComparer.Ordinal); + return pair => map[pair.Name]; + } + + private static void AssertClose(decimal expected, decimal actual, decimal tolerance = 0.000000000001m) => + Assert.IsTrue(Math.Abs(expected - actual) <= tolerance, $"{expected} ≠ {actual}"); +} diff --git a/tests/Anubis.Tests/BasketRelationTests.cs b/tests/Anubis.Tests/BasketRelationTests.cs new file mode 100644 index 0000000..efb6fda --- /dev/null +++ b/tests/Anubis.Tests/BasketRelationTests.cs @@ -0,0 +1,225 @@ +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// The relations among the 28 pairs (Phase 12, issue #119): the counts of section 4.1, appendix B row by row, the eight +/// documented spreads of section 3.3, the sign of the index and the 14-pair list. +/// +[TestClass] +public sealed class BasketRelationTests +{ + /// Appendix B, written out by hand from the document: row, leg A, leg B, synthetic cross. + private static readonly string[][] AppendixB = + [ + ["EURGBP", "GBPAUD", "EURAUD"], ["EURGBP", "GBPNZD", "EURNZD"], ["EURGBP", "GBPUSD", "EURUSD"], + ["EURGBP", "GBPCAD", "EURCAD"], ["EURGBP", "GBPCHF", "EURCHF"], ["EURGBP", "GBPJPY", "EURJPY"], + ["EURAUD", "AUDNZD", "EURNZD"], ["EURAUD", "AUDUSD", "EURUSD"], ["EURAUD", "AUDCAD", "EURCAD"], + ["EURAUD", "AUDCHF", "EURCHF"], ["EURAUD", "AUDJPY", "EURJPY"], ["GBPAUD", "AUDNZD", "GBPNZD"], + ["GBPAUD", "AUDUSD", "GBPUSD"], ["GBPAUD", "AUDCAD", "GBPCAD"], ["GBPAUD", "AUDCHF", "GBPCHF"], + ["GBPAUD", "AUDJPY", "GBPJPY"], ["EURNZD", "NZDUSD", "EURUSD"], ["EURNZD", "NZDCAD", "EURCAD"], + ["EURNZD", "NZDCHF", "EURCHF"], ["EURNZD", "NZDJPY", "EURJPY"], ["GBPNZD", "NZDUSD", "GBPUSD"], + ["GBPNZD", "NZDCAD", "GBPCAD"], ["GBPNZD", "NZDCHF", "GBPCHF"], ["GBPNZD", "NZDJPY", "GBPJPY"], + ["AUDNZD", "NZDUSD", "AUDUSD"], ["AUDNZD", "NZDCAD", "AUDCAD"], ["AUDNZD", "NZDCHF", "AUDCHF"], + ["AUDNZD", "NZDJPY", "AUDJPY"], ["EURUSD", "USDCAD", "EURCAD"], ["EURUSD", "USDCHF", "EURCHF"], + ["EURUSD", "USDJPY", "EURJPY"], ["GBPUSD", "USDCAD", "GBPCAD"], ["GBPUSD", "USDCHF", "GBPCHF"], + ["GBPUSD", "USDJPY", "GBPJPY"], ["AUDUSD", "USDCAD", "AUDCAD"], ["AUDUSD", "USDCHF", "AUDCHF"], + ["AUDUSD", "USDJPY", "AUDJPY"], ["NZDUSD", "USDCAD", "NZDCAD"], ["NZDUSD", "USDCHF", "NZDCHF"], + ["NZDUSD", "USDJPY", "NZDJPY"], ["EURCAD", "CADCHF", "EURCHF"], ["EURCAD", "CADJPY", "EURJPY"], + ["GBPCAD", "CADCHF", "GBPCHF"], ["GBPCAD", "CADJPY", "GBPJPY"], ["AUDCAD", "CADCHF", "AUDCHF"], + ["AUDCAD", "CADJPY", "AUDJPY"], ["NZDCAD", "CADCHF", "NZDCHF"], ["NZDCAD", "CADJPY", "NZDJPY"], + ["USDCAD", "CADCHF", "USDCHF"], ["USDCAD", "CADJPY", "USDJPY"], ["EURCHF", "CHFJPY", "EURJPY"], + ["GBPCHF", "CHFJPY", "GBPJPY"], ["AUDCHF", "CHFJPY", "AUDJPY"], ["NZDCHF", "CHFJPY", "NZDJPY"], + ["USDCHF", "CHFJPY", "USDJPY"], ["CADCHF", "CHFJPY", "CADJPY"], + ]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCouplesOfTheTwentyEightPairsAre56Chains112RatiosAnd210Disjoint() + { + var couples = Relations.Couples; + + Assert.AreEqual(378, couples.Count); + Assert.AreEqual(378, couples.Select(c => (c.A.Name, c.B.Name)).Distinct().Count()); + Assert.AreEqual(56, couples.Count(c => c.Kind == RelationKind.Chain)); + Assert.AreEqual(112, couples.Count(c => c.Kind == RelationKind.Ratio)); + Assert.AreEqual(210, couples.Count(c => c.Kind == RelationKind.Disjoint)); + + // Every pair is the synthetic cross of exactly six couples that share a currency, one per other currency (section 4.1). + foreach (var pair in FxPairs.All) + { + Assert.AreEqual(6, couples.Count(c => c.Cross == pair), pair.Name); + } + + Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Disjoint).All(c => c.Common is null && c.Cross is null)); + Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Chain).All(c => !c.CrossInverted)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AppendixBIsReproducedRowByRow() + { + var rows = Relations.AppendixB; + int[] listed = [3, 9, 17, 29, 30, 35]; + + Assert.AreEqual(56, rows.Count); + for (var i = 0; i < AppendixB.Length; i++) + { + var row = rows[i]; + var expected = AppendixB[i]; + Assert.AreEqual(i + 1, row.Row); + Assert.AreEqual(expected[0], row.A.Name, $"riga {i + 1}"); + Assert.AreEqual(expected[1], row.B.Name, $"riga {i + 1}"); + Assert.AreEqual(expected[2], row.Cross.Name, $"riga {i + 1}"); + Assert.AreEqual(listed.Contains(i + 1), row.Listed, $"riga {i + 1}"); + + // The common currency is the quote of A and the base of B; the classification agrees with the row. + Assert.AreEqual(row.A.Quote, row.B.Base); + var relation = Relations.Classify(row.A, row.B); + Assert.AreEqual(RelationKind.Chain, relation.Kind); + Assert.AreEqual(row.Cross, relation.Cross); + Assert.AreEqual(row.A.Quote, relation.Common); + } + + // The 56 rows are the 56 chains of the 378 couples, each once. + var chains = Relations.Couples.Where(c => c.Kind == RelationKind.Chain).Select(c => Key(c.A, c.B)).ToHashSet(); + CollectionAssert.AreEquivalent(chains.ToList(), rows.Select(r => Key(r.A, r.B)).ToList()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEightDocumentedSpreadsAreSixChainsAndTwoDisjointWhateverTheLegOrder() + { + (string A, string B, RelationKind Kind, string? Cross)[] expected = + [ + ("EURUSD", "USDCHF", RelationKind.Chain, "EURCHF"), + ("AUDUSD", "USDCAD", RelationKind.Chain, "AUDCAD"), + ("NZDUSD", "EURNZD", RelationKind.Chain, "EURUSD"), + ("USDCAD", "EURUSD", RelationKind.Chain, "EURCAD"), + ("EURAUD", "AUDCAD", RelationKind.Chain, "EURCAD"), + ("GBPUSD", "EURGBP", RelationKind.Chain, "EURUSD"), + ("NZDUSD", "AUDCHF", RelationKind.Disjoint, null), + ("EURCHF", "AUDCAD", RelationKind.Disjoint, null), + ]; + + var spreads = Relations.DocumentedSpreads; + Assert.AreEqual(8, spreads.Count); + for (var i = 0; i < expected.Length; i++) + { + var (a, b, kind, cross) = expected[i]; + Assert.AreEqual(a, spreads[i].A.Name); + Assert.AreEqual(b, spreads[i].B.Name); + + var forward = Relations.Classify(FxPairs.Get(a), FxPairs.Get(b)); + var backward = Relations.Classify(FxPairs.Get(b), FxPairs.Get(a)); + Assert.AreEqual(kind, forward.Kind, $"{a}–{b}"); + Assert.AreEqual(kind, backward.Kind, $"{b}–{a}"); + Assert.AreEqual(cross, forward.Cross?.Name, $"{a}–{b}"); + Assert.AreEqual(cross, backward.Cross?.Name, $"{b}–{a}"); + Assert.AreEqual(forward.Common, backward.Common); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoClassificationDependsOnTheOrderOfTheLegs() + { + foreach (var couple in Relations.Couples) + { + var swapped = Relations.Classify(couple.B, couple.A); + Assert.AreEqual(couple.Kind, swapped.Kind); + Assert.AreEqual(couple.Cross, swapped.Cross); + Assert.AreEqual(couple.Common, swapped.Common); + + // Only the orientation of a ratio's synthetic A/B turns over with the legs. + if (couple.Kind == RelationKind.Ratio) + { + Assert.AreNotEqual(couple.CrossInverted, swapped.CrossInverted); + } + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ARatioNamesItsSyntheticCrossAndWhetherItIsTheInverse() + { + // Both quote USD: EURUSD / GBPUSD = EURGBP (section 4.1); swapped it is 1/EURGBP. + var both = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("GBPUSD")); + Assert.AreEqual(RelationKind.Ratio, both.Kind); + Assert.AreEqual("USD", both.Common); + Assert.AreEqual("EURGBP", both.Cross?.Name); + Assert.IsFalse(both.CrossInverted); + Assert.IsTrue(Relations.Classify(FxPairs.Get("GBPUSD"), FxPairs.Get("EURUSD")).CrossInverted); + + // Both base EUR: EURUSD / EURGBP = USD per GBP = GBPUSD. + var bases = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("EURGBP")); + Assert.AreEqual(RelationKind.Ratio, bases.Kind); + Assert.AreEqual("GBPUSD", bases.Cross?.Name); + Assert.IsFalse(bases.CrossInverted); + Assert.IsTrue(Relations.Classify(FxPairs.Get("EURGBP"), FxPairs.Get("EURUSD")).CrossInverted); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheSignIsPlusForChainsMinusForRatiosAndAgainstTheCorrelationForDisjoint() + { + Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, null)); + Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, 0.9)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, null)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, -0.9)); + Assert.AreEqual(-1, Relations.Sign(RelationKind.Disjoint, 0.3)); + Assert.AreEqual(1, Relations.Sign(RelationKind.Disjoint, -0.3)); + + // With no correlation, or a zero one, a disjoint couple has no sign and cannot be traded. + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, 0)); + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, null)); + Assert.IsNull(Relations.Sign(RelationKind.Disjoint, double.NaN)); + + var disjoint = Relations.Classify(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF")); + Assert.AreEqual(-1, disjoint.Sign(0.5)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ACoupleOfAPairWithItselfIsRefused() + { + var pair = FxPairs.Get("EURUSD"); + Assert.ThrowsExactly(() => Relations.Classify(pair, pair)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFourteenPairListIsTheTwelveDocumentedSymbolsPlusEurcadAndAudnzd() + { + string[] expected = + [ + "EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD", + "AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF", + ]; + + var list = Relations.FourteenPairs; + CollectionAssert.AreEqual(expected, list.Select(p => p.Name).ToArray()); + + // Appendix A order, no yen: the order of the 28 with the others left out. + CollectionAssert.AreEqual(FxPairs.All.Where(list.Contains).ToArray(), list.ToArray()); + Assert.IsFalse(list.Any(p => p.Quote == Currencies.Jpy)); + + // Every leg of the eight documented spreads is in the list. + Assert.IsTrue(Relations.DocumentedSpreads.All(s => list.Contains(s.A) && list.Contains(s.B))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipIsOneHundredthForYenPairsAndOneTenThousandthForTheOthers() + { + string[] yen = ["EURJPY", "GBPJPY", "AUDJPY", "NZDJPY", "USDJPY", "CADJPY", "CHFJPY"]; + foreach (var pair in FxPairs.All) + { + Assert.AreEqual(yen.Contains(pair.Name) ? 0.01m : 0.0001m, pair.Pip, pair.Name); + } + + Assert.AreEqual(7, FxPairs.All.Count(p => p.Pip == 0.01m)); + } + + private static string Key(FxPair a, FxPair b) => string.CompareOrdinal(a.Name, b.Name) < 0 ? a.Name + b.Name : b.Name + a.Name; +} diff --git a/tests/Anubis.Tests/BasketSignalTests.cs b/tests/Anubis.Tests/BasketSignalTests.cs new file mode 100644 index 0000000..083914b --- /dev/null +++ b/tests/Anubis.Tests/BasketSignalTests.cs @@ -0,0 +1,322 @@ +using System.Globalization; +using Anubis.Baskets; + +namespace Anubis.Tests; + +/// +/// The statistics of the basket maths (Phase 12, issue #119): the index in pips and in log basis points, z-score, Rvol with +/// its filter and factors, correlation, the hedge ratio, the states of a pair, the four styles, the two profiles, and the +/// rule that nothing computed at a closed bar looks at a later one. +/// +[TestClass] +public sealed class BasketSignalTests +{ + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePipIndexAddsTheLegsWithTheSignOfTheRelation() + { + var eurusd = FxPairs.Get("EURUSD"); + var usdchf = FxPairs.Get("USDCHF"); + + // Chain, s = +1: 1.0856 / 0.0001 + 0.847 / 0.0001 = 10,856 + 8,470. + Assert.AreEqual(19_326, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, +1), 1e-9); + Assert.AreEqual(2_386, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, -1), 1e-9); + + // Single symbol, and a yen pair with its 0.01 pip. + Assert.AreEqual(10_856, BasketIndex.Pips(1.0856, eurusd), 1e-9); + Assert.AreEqual(15_795, BasketIndex.Pips(157.95, FxPairs.Get("USDJPY")), 1e-9); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheLogIndexIsInBasisPoints() + { + // One basis point is 0.01%: a 1% rise of leg A is about 99.5 points. + Assert.AreEqual(10_000 * Math.Log(1.01), BasketIndex.LogBp(1.01, 1.0), 1e-9); + Assert.AreEqual(99.50330853168, BasketIndex.LogBp(1.01, 1.0), 1e-9); + Assert.AreEqual(10_000 * (Math.Log(50.0) - (1.5 * Math.Log(20.0))), BasketIndex.LogBp(50.0, 20.0, beta: 1.5), 1e-9); + Assert.AreEqual(10_000 * Math.Log(2.0), BasketIndex.LogBp(2.0), 1e-9); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheZScoreUsesTheSampleDeviationOfTheLastWValuesIncludingTheBar() + { + double[] index = [7, 1, 2, 3, 4, 10]; + + // Last 5 values ending at t = 5: 1, 2, 3, 4, 10. Mean 4; squares 9 + 4 + 1 + 0 + 36 = 50; sample variance 50 / 4 + // = 12.5; deviation 5 / √2; z = (10 − 4) / (5 / √2) = 6√2 / 5 = 1.6970562748. + Assert.AreEqual(1.6970562748477141, BasketIndex.ZScore(index, 5, window: 5)!.Value, 1e-12); + + // At t = 4 the window is 7, 1, 2, 3, 4: mean 3.4, squares 12.96 + 5.76 + 1.96 + 0.16 + 0.36 = 21.2, variance 5.3. + Assert.AreEqual((4 - 3.4) / Math.Sqrt(5.3), BasketIndex.ZScore(index, 4, window: 5)!.Value, 1e-12); + + // Fewer than W values, a flat window or a missing value: no z. + Assert.IsNull(BasketIndex.ZScore(index, 3, window: 5)); + Assert.IsNull(BasketIndex.ZScore([5, 5, 5, 5, 5], 4, window: 5)); + Assert.IsNull(BasketIndex.ZScore([1, 2, double.NaN, 4, 5], 4, window: 5)); + Assert.AreEqual(100, BasketIndex.DefaultWindow); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void RvolIsTheShortDeviationOverTheMedianOfItsBaseline() + { + // Index 0, 1, 3, 4, 6, 12: differences d1..d5 = 1, 2, 1, 2, 6. With 2 differences per short window the sample + // deviation of two values a, b is |a − b| / √2: σ(2) = σ(3) = σ(4) = 1 / √2, σ(5) = 4 / √2. + double[] index = [0, 1, 3, 4, 6, 12]; + Assert.AreEqual(1 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 2, shortBars: 2)!.Value, 1e-12); + Assert.AreEqual(4 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 5, shortBars: 2)!.Value, 1e-12); + Assert.IsNull(BasketIndex.ShortSigma(index, 1, shortBars: 2)); + + // Baseline of 3: at t = 4 the median of σ(2), σ(3), σ(4) is 1 / √2, so Rvol = 1; at t = 5 the median of σ(3), σ(4), + // σ(5) is still 1 / √2, so Rvol = 4. At t = 3, σ(1) does not exist yet: no Rvol. + Assert.AreEqual(1.0, BasketIndex.Rvol(index, 4, baselineBars: 3, shortBars: 2)!.Value, 1e-12); + Assert.AreEqual(4.0, BasketIndex.Rvol(index, 5, baselineBars: 3, shortBars: 2)!.Value, 1e-12); + Assert.IsNull(BasketIndex.Rvol(index, 3, baselineBars: 3, shortBars: 2)); + + // A flat baseline has no Rvol. + Assert.IsNull(BasketIndex.Rvol([0, 1, 2, 3, 4, 5], 5, baselineBars: 3, shortBars: 2)); + + // An even baseline takes the mean of the two middle values: σ(4) and σ(5) → (1 + 4) / √2 / 2 against σ(5) = 4 / √2. + Assert.AreEqual(4.0 / 2.5, BasketIndex.Rvol(index, 5, baselineBars: 2, shortBars: 2)!.Value, 1e-12); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheDefaultRvolWindowsAreSixteenBarsAndTwentyDays() + { + Assert.AreEqual(16, BasketIndex.DefaultShortBars); + Assert.AreEqual(1920, BasketIndex.BaselineBars(barsPerDay: 96)); + Assert.AreEqual(1920, BasketIndex.DefaultBaselineBars); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheVolatilityFilterBlocksNewEntriesAboveTwo() + { + Assert.IsTrue(BasketIndex.AllowsEntry(1.0)); + Assert.IsTrue(BasketIndex.AllowsEntry(2.0)); + Assert.IsFalse(BasketIndex.AllowsEntry(2.0001)); + Assert.IsFalse(BasketIndex.AllowsEntry(4.0)); + + // Without enough history to know the volatility, no new entry. + Assert.IsFalse(BasketIndex.AllowsEntry(null)); + Assert.IsFalse(BasketIndex.AllowsEntry(double.NaN)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(0.5, "1", "0.7")] + [DataRow(0.8, "1", "0.8")] + [DataRow(1.0, "1", "1")] + [DataRow(1.5, "1.5", "1.5")] + [DataRow(3.0, "3", "3")] + [DataRow(4.0, "3", "3")] + public void TheRvolFactorsAreClampedAsTheDocumentSays(double rvol, string distance, string target) + { + Assert.AreEqual(decimal.Parse(distance, CultureInfo.InvariantCulture), BasketMath.DistanceFactor(rvol)); + Assert.AreEqual(decimal.Parse(target, CultureInfo.InvariantCulture), BasketMath.TargetFactor(rvol)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCorrelationIsPearsonOfLogReturnsOverTheWindow() + { + double[] a = [1.0, 1.1, 1.05, 1.2, 1.3]; + var squared = a.Select(x => x * x).ToArray(); + var inverse = a.Select(x => 1 / x).ToArray(); + + Assert.AreEqual(1.0, BasketIndex.Correlation(a, squared, 4, window: 4)!.Value, 1e-12); + Assert.AreEqual(-1.0, BasketIndex.Correlation(a, inverse, 4, window: 4)!.Value, 1e-12); + + // Four returns need five prices; a flat leg has no correlation. + Assert.IsNull(BasketIndex.Correlation(a, squared, 3, window: 4)); + Assert.IsNull(BasketIndex.Correlation(a, [2.0, 2.0, 2.0, 2.0, 2.0], 4, window: 4)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheHedgeRatioIsTheOlsSlopeOfLogPrices() + { + // ln A = ln 3 + 2 ln B exactly: β = 2. + double[] b = [1.0, 1.2, 0.9, 1.5, 1.1]; + var a = b.Select(x => 3 * x * x).ToArray(); + + Assert.AreEqual(2.0, BasketIndex.HedgeRatio(a, b)!.Value, 1e-12); + Assert.IsNull(BasketIndex.HedgeRatio([1.0, 2.0], [3.0, 3.0])); + Assert.IsNull(BasketIndex.HedgeRatio([1.0], [3.0])); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow(0.0, true, false, PairState.Idle)] + [DataRow(1.49, true, false, PairState.Idle)] + [DataRow(1.5, true, false, PairState.Watch)] + [DataRow(-1.5, true, false, PairState.Watch)] + [DataRow(1.99, true, false, PairState.Watch)] + [DataRow(2.0, true, false, PairState.Open)] + [DataRow(-2.0, true, false, PairState.Open)] + [DataRow(2.0, false, false, PairState.Armed)] + [DataRow(-2.5, false, false, PairState.Armed)] + [DataRow(0.1, false, true, PairState.Open)] + public void ThePairStatesFollowTheThresholds(double z, bool gatesPass, bool open, PairState expected) + { + Assert.AreEqual(expected, PairStates.Of(z, entryZ: 2.0, gatesPass, hasOpenUnit: open)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void APairWithoutAZScoreIsIdle() + { + Assert.AreEqual(PairState.Idle, PairStates.Of(null, entryZ: 2.0, gatesPass: true)); + Assert.AreEqual(1.5, PairStates.DefaultWatchZ); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheSignalBuysTheSpreadLowAndSellsItHighAndTheSpreadClosesNearZero() + { + Assert.AreEqual(Direction.Buy, PairStates.Signal(-2.0, entryZ: 2.0)); + Assert.AreEqual(Direction.Sell, PairStates.Signal(2.0, entryZ: 2.0)); + Assert.IsNull(PairStates.Signal(1.99, entryZ: 2.0)); + Assert.IsNull(PairStates.Signal(null, entryZ: 2.0)); + + Assert.IsTrue(PairStates.SpreadClosed(0.5)); + Assert.IsTrue(PairStates.SpreadClosed(-0.5)); + Assert.IsFalse(PairStates.SpreadClosed(0.51)); + Assert.IsFalse(PairStates.SpreadClosed(null)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFourStylesCarryTheDocumentedValues() + { + (string Name, double EntryZ, int Spreads, int Averagings, int WithGrowth)[] expected = + [ + ("HedgeFund", 3.0, 1, 2, 2), + ("Conservativo", 2.5, 2, 3, 3), + ("Moderato", 2.0, 2, 3, 3), + ("Aggressivo", 1.5, 3, 3, 4), + ]; + + Assert.AreEqual(4, TradingStyles.All.Count); + for (var i = 0; i < expected.Length; i++) + { + var style = TradingStyles.All[i]; + Assert.AreEqual(expected[i].Name, style.Name); + Assert.AreEqual(expected[i].EntryZ, style.EntryZ); + Assert.AreEqual(expected[i].Spreads, style.MaxOpenSpreads); + Assert.AreEqual(expected[i].Averagings, style.MaxAveragings); + Assert.AreEqual(expected[i].WithGrowth, style.MaxAveragingsWithGrowth); + } + + Assert.AreSame(TradingStyles.Moderato, TradingStyles.Default); + Assert.AreSame(TradingStyles.Aggressivo, TradingStyles.Find("Aggressivo")); + Assert.IsNull(TradingStyles.Find("Spericolato")); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheTwoProfilesCarryTheDocumentedValues() + { + var fedele = BasketProfiles.Fedele; + Assert.AreEqual("Fedele", fedele.Name); + Assert.IsFalse(fedele.HasBasketStops()); + Assert.AreEqual(0.09m, fedele.EquityStop); + Assert.IsTrue(fedele.ResumeAtNextServerDay); + Assert.IsFalse(fedele.CostGate); + Assert.IsNull(fedele.MaxCurrencyExposure); + Assert.IsTrue(fedele.OffRealAccountsOnly); + + // The document's 1.5% basket loss is reduced to 1% by SPEC 9.2. + var prudente = BasketProfiles.Prudente; + Assert.AreEqual("Prudente", prudente.Name); + Assert.IsTrue(prudente.HasBasketStops()); + Assert.AreEqual(3.5, prudente.StopZ); + Assert.AreEqual(0.01m, prudente.StopLoss); + Assert.IsTrue(prudente.StopOnBrokenRelation); + Assert.AreEqual(96, prudente.StopAfterBars); + Assert.IsTrue(prudente.CostGate); + Assert.AreEqual(2.0m, prudente.MaxCurrencyExposure); + Assert.AreEqual(0.09m, prudente.EquityStop); + Assert.IsTrue(prudente.ResumeAtNextServerDay); + Assert.IsFalse(prudente.OffRealAccountsOnly); + + CollectionAssert.AreEqual(new[] { fedele, prudente }, BasketProfiles.All.ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NothingComputedAtABarDependsOnLaterBars() + { + var checkedValues = 0; + Property.ForAll(Walks, c => + { + var past = c.Cut + 1; + var pastA = c.A[..past]; + var pastB = c.B[..past]; + var pastIndex = Index(pastA, pastB, c.Sign); + var fullIndex = Index(c.A, c.B, c.Sign); + var pastLog = pastA.Select((a, i) => BasketIndex.LogBp(a, pastB[i])).ToArray(); + var fullLog = c.A.Select((a, i) => BasketIndex.LogBp(a, c.B[i])).ToArray(); + + Assert.AreEqual(pastIndex[c.Cut], fullIndex[c.Cut]); + Assert.AreEqual(pastLog[c.Cut], fullLog[c.Cut]); + + var z = BasketIndex.ZScore(pastIndex, c.Cut, window: 20); + Assert.AreEqual(z, BasketIndex.ZScore(fullIndex, c.Cut, window: 20)); + Assert.AreEqual(BasketIndex.ZScore(pastLog, c.Cut, window: 20), BasketIndex.ZScore(fullLog, c.Cut, window: 20)); + + var rvol = BasketIndex.Rvol(pastIndex, c.Cut, baselineBars: 12, shortBars: 4); + Assert.AreEqual(rvol, BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4)); + + var rho = BasketIndex.Correlation(pastA, pastB, c.Cut, window: 20); + Assert.AreEqual(rho, BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20)); + + var gates = BasketIndex.AllowsEntry(rvol) && rho is not null; + var pastState = PairStates.Of(z, entryZ: 2.0, gates, watchZ: 1.0); + var fullState = PairStates.Of( + BasketIndex.ZScore(fullIndex, c.Cut, window: 20), + entryZ: 2.0, + BasketIndex.AllowsEntry(BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4)) + && BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20) is not null, + watchZ: 1.0); + Assert.AreEqual(pastState, fullState); + + if (z is not null && rvol is not null && rho is not null) + { + checkedValues++; + } + }); + + // The property is not empty: most cases have every statistic defined. + Assert.IsTrue(checkedValues > Property.DefaultCases / 2, checkedValues.ToString(CultureInfo.InvariantCulture)); + } + + private static double[] Index(double[] a, double[] b, int sign) => + [.. a.Select((price, i) => BasketIndex.Pips(price, FxPairs.Get("EURUSD"), b[i], FxPairs.Get("USDCHF"), sign))]; + + private static Walk Walks(Gen gen) + { + var length = gen.Int(40, 120); + var future = gen.Int(1, 40); + var a = new double[length + future]; + var b = new double[length + future]; + a[0] = 1.1; + b[0] = 0.9; + for (var i = 1; i < a.Length; i++) + { + a[i] = a[i - 1] * Math.Exp(0.002 * gen.Normal()); + b[i] = b[i - 1] * Math.Exp(0.002 * gen.Normal()); + } + + return new Walk(a, b, gen.Bool() ? 1 : -1, gen.Int(length / 2, length)); + } + + /// Two price walks; bars after are the future that must not matter. + private sealed record Walk(double[] A, double[] B, int Sign, int Cut) + { + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{A.Length} barre, taglio {Cut}, segno {Sign}"); + } +} diff --git a/tests/Anubis.Tests/ServerClockTests.cs b/tests/Anubis.Tests/ServerClockTests.cs new file mode 100644 index 0000000..161fac0 --- /dev/null +++ b/tests/Anubis.Tests/ServerClockTests.cs @@ -0,0 +1,162 @@ +using System.Globalization; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The server clock of the research document (Phase 12, issue #119): New York time plus seven hours, the server day, the daily +/// pause, the hourly window and the weekend rule. Four dates cover winter, summer and the weeks in which the United States +/// and Europe change the clock on different days (2026: US 8 March and 1 November, Europe 29 March and 25 October). +/// +[TestClass] +public sealed class ServerClockTests +{ + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15", 2, "2026-01-15T08:00:00Z", "2026-01-14T22:00:00Z")] + [DataRow("2026-03-16", 3, "2026-03-16T07:00:00Z", "2026-03-15T21:00:00Z")] + [DataRow("2026-07-15", 3, "2026-07-15T07:00:00Z", "2026-07-14T21:00:00Z")] + [DataRow("2026-10-27", 3, "2026-10-27T07:00:00Z", "2026-10-26T21:00:00Z")] + public void TheServerClockIsNewYorkPlusSevenHoursOnFourDates(string day, int offsetHours, string tenServerUtc, string midnightUtc) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var ten = Utc(tenServerUtc); + var midnight = Utc(midnightUtc); + + Assert.AreEqual(ten, ServerClock.At(date, new TimeOnly(10, 0))); + Assert.AreEqual(midnight, ServerClock.DayStart(date)); + Assert.AreEqual(TimeSpan.FromHours(offsetHours), ServerClock.OffsetFromUtc(ten)); + Assert.AreEqual(date.ToDateTime(new TimeOnly(10, 0)), ServerClock.ToServer(ten)); + + // The server day starts at server midnight, not a tick earlier. + Assert.AreEqual(date, ServerClock.Day(midnight)); + Assert.AreEqual(date.AddDays(-1), ServerClock.Day(midnight.AddTicks(-1))); + Assert.AreEqual(date, ServerClock.Day(ten)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15")] + [DataRow("2026-03-16")] + [DataRow("2026-07-15")] + [DataRow("2026-10-27")] + public void TheServerDayChangesAtFivePmNewYork(string day) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var five = Zones.At(date, new TimeOnly(17, 0), Zones.NewYork); + + Assert.AreEqual(date, ServerClock.Day(five.AddSeconds(-1))); + Assert.AreEqual(date.AddDays(1), ServerClock.Day(five)); + Assert.AreEqual(ServerClock.DayStart(date.AddDays(1)), five); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15", "2026-01-15T21:55:00Z", "2026-01-15T23:10:00Z")] + [DataRow("2026-03-16", "2026-03-16T20:55:00Z", "2026-03-16T22:10:00Z")] + [DataRow("2026-07-15", "2026-07-15T20:55:00Z", "2026-07-15T22:10:00Z")] + [DataRow("2026-10-27", "2026-10-27T20:55:00Z", "2026-10-27T22:10:00Z")] + public void TheDailyPauseRunsFrom1655To1810NewYorkHalfOpen(string day, string fromUtc, string toUtc) + { + var from = Utc(fromUtc); + var to = Utc(toUtc); + Assert.AreEqual(Zones.At(DateOnly.Parse(day, CultureInfo.InvariantCulture), new TimeOnly(16, 55), Zones.NewYork), from); + + Assert.IsFalse(ServerClock.InDailyPause(from.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InDailyPause(from)); + Assert.IsTrue(ServerClock.InDailyPause(from.AddMinutes(30))); + Assert.IsTrue(ServerClock.InDailyPause(to.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InDailyPause(to)); + + // The pause crosses server midnight; no entries inside it, whatever else allows them. + Assert.IsTrue(ServerClock.InDailyPause(ServerClock.DayStart(DateOnly.Parse(day, CultureInfo.InvariantCulture).AddDays(1)))); + Assert.IsFalse(ServerClock.EntriesAllowed(from, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(to, sessionOn: false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-16T14:00:00Z", "2026-01-19T00:00:00Z")] + [DataRow("2026-07-17T13:00:00Z", "2026-07-19T23:00:00Z")] + public void TheWeekendRuleBlocksFromFriday1600ToMonday0200ServerTimeHalfOpen(string fridayUtc, string mondayUtc) + { + var friday = Utc(fridayUtc); + var monday = Utc(mondayUtc); + Assert.AreEqual(DayOfWeek.Friday, ServerClock.ToServer(friday).DayOfWeek); + Assert.AreEqual(new TimeOnly(16, 0), TimeOnly.FromDateTime(ServerClock.ToServer(friday))); + Assert.AreEqual(DayOfWeek.Monday, ServerClock.ToServer(monday).DayOfWeek); + Assert.AreEqual(new TimeOnly(2, 0), TimeOnly.FromDateTime(ServerClock.ToServer(monday))); + + Assert.IsFalse(ServerClock.InWeekend(friday.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InWeekend(friday)); + Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(1))); + Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(2))); + Assert.IsTrue(ServerClock.InWeekend(monday.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InWeekend(monday)); + Assert.IsFalse(ServerClock.InWeekend(monday.AddDays(3))); + + Assert.IsFalse(ServerClock.EntriesAllowed(friday, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(monday, sessionOn: false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("2026-01-15")] + [DataRow("2026-03-16")] + [DataRow("2026-07-15")] + [DataRow("2026-10-27")] + public void TheHourlyWindowRunsFrom1000To2000ServerTimeHalfOpen(string day) + { + var date = DateOnly.Parse(day, CultureInfo.InvariantCulture); + var ten = ServerClock.At(date, new TimeOnly(10, 0)); + var eight = ServerClock.At(date, new TimeOnly(20, 0)); + + Assert.IsFalse(ServerClock.InSession(ten.AddSeconds(-1))); + Assert.IsTrue(ServerClock.InSession(ten)); + Assert.IsTrue(ServerClock.InSession(eight.AddSeconds(-1))); + Assert.IsFalse(ServerClock.InSession(eight)); + + // The window only matters when it is switched on. + Assert.IsFalse(ServerClock.EntriesAllowed(eight, sessionOn: true)); + Assert.IsTrue(ServerClock.EntriesAllowed(eight, sessionOn: false)); + Assert.IsTrue(ServerClock.EntriesAllowed(ten, sessionOn: true)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AfterTheEquityStopEntriesResumeAtTheNextServerDay() + { + // Thursday 15 January 2026, 15:00 New York = 22:00 server: the next server day starts at 17:00 New York. + var stop = new DateTimeOffset(2026, 1, 15, 20, 0, 0, TimeSpan.Zero); + Assert.AreEqual(new DateTimeOffset(2026, 1, 15, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(stop)); + + // One minute after the change the next day is a whole day later. + var after = new DateTimeOffset(2026, 1, 15, 22, 1, 0, TimeSpan.Zero); + Assert.AreEqual(new DateTimeOffset(2026, 1, 16, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(after)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AServerTimeTurnsBackIntoTheSameMoment() + { + var gen = new Gen(Property.DefaultSeed); + var start = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero); + for (var i = 0; i < 500; i++) + { + var moment = start.AddMinutes(gen.Int(0, 3 * 365 * 24 * 60)); + var server = ServerClock.ToServer(moment); + + // Away from the hour in which New York's clock goes back, a server time names one moment only. + if (server.DayOfWeek == DayOfWeek.Sunday && server.Hour is >= 7 and < 10) + { + continue; + } + + Assert.AreEqual(moment, ServerClock.FromServer(server), moment.ToString("O", CultureInfo.InvariantCulture)); + } + } + + private static DateTimeOffset Utc(string text) => + DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); +} -- 2.54.1 From 2a96e08d5a86c73e01df3619a559b4a3f7ddd20d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 10:01:00 +0100 Subject: [PATCH 5/6] Add sub-day research bars, ECB crosses and FX minute import Phase 12 needs intraday bars and the 28 currency pairs for the basket research, without touching the daily backtest engine. - Timeframes gain 15m, 30m, 1h, 4h, 8h with Length and IsIntraday; the CSV import checks any intraday timeframe minute-style at its length instead of sending it to the daily check. - BarAggregator builds longer bars in decimal on UTC epoch buckets, never fills a gap and leaves out a bucket that has not closed. - Bar calendars (24x7, 24x5 FX from Sunday to Friday 17:00 New York, exchange sessions) and BarDataset: a common clock in double columns, NaN where a series has no bar, optional ask columns, Through that only shows closed bars, and a fingerprint of the data. - EcbCrosses derives the 28 pairs (from the shared Baskets list) from the seven ECB rates; "anubis data ecb" writes them under research/ecb from the same cached zip as "backtest base", whose loader moves into the library with its output unchanged. - CsvImporter.Parse is split out of ImportAsync and mappings accept a fixed offset such as UTC-05:00. - "anubis data fx" reads Dukascopy and HistData one-minute files, refuses anything else in Italian, drops bars outside the FX week and writes the 1m and 15m series. The formats come from general knowledge: the fixtures are constructed samples, as API-NOTES says. refs #120 Co-Authored-By: Claude Opus 5.5 --- docs/API-NOTES.md | 3 + docs/MANUALE.md | 12 +- src/Anubis.Server/BacktestCommand.cs | 12 +- src/Anubis.Server/DataCommand.cs | 56 +- src/Anubis.Server/Program.cs | 2 +- src/Anubis/Data/BarAggregator.cs | 89 +++ src/Anubis/Data/BarCalendars.cs | 154 +++++ src/Anubis/Data/BarDataset.cs | 282 ++++++++ src/Anubis/Data/EcbCrosses.cs | 60 ++ src/Anubis/Data/FreeSources.cs | 27 + src/Anubis/Data/FxMinuteFiles.cs | 176 +++++ src/Anubis/Data/Importers.cs | 105 ++- src/Anubis/Data/Quality.cs | 64 +- .../Fixtures/fx/DAT_ASCII_EURUSD_M1_2024.csv | 5 + ...dlestick_1_M_ASK_02.01.2024-06.01.2024.csv | 6 + ...dlestick_1_M_BID_02.01.2024-06.01.2024.csv | 7 + tests/Anubis.Tests/ResearchBarsTests.cs | 622 ++++++++++++++++++ 17 files changed, 1636 insertions(+), 46 deletions(-) create mode 100644 src/Anubis/Data/BarAggregator.cs create mode 100644 src/Anubis/Data/BarCalendars.cs create mode 100644 src/Anubis/Data/BarDataset.cs create mode 100644 src/Anubis/Data/EcbCrosses.cs create mode 100644 src/Anubis/Data/FxMinuteFiles.cs create mode 100644 tests/Anubis.Tests/Fixtures/fx/DAT_ASCII_EURUSD_M1_2024.csv create mode 100644 tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv create mode 100644 tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv create mode 100644 tests/Anubis.Tests/ResearchBarsTests.cs diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index 368eccb..d661a3c 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -166,6 +166,9 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio | Codici di una chiave rifiutata | Alpaca e OKX rispondono 401 o 403; su OKX i codici 50102 e 50112 parlano dell'orologio e non della chiave. Scritto dalla documentazione, non provato dal vivo: se un codice mancasse, l'avviso direbbe "non risponde" invece di "non accetta la chiave" (ADR 0020). | 9 | | Archivi della SEC (settori) | `company_tickers.json` e `submissions` letti come da documentazione, non provati dal vivo perché serve un contatto dell'utente. Senza, nessuna richiesta parte; un settore sconosciuto non limita niente. | 9 | | Minuti senza scambi su OKX | Il buco si riscarica una volta, poi resta segnato come non recuperabile e non blocca nulla. | 2 | +| Formato dei file a un minuto di Dukascopy | Scritto da conoscenze generali, non da un file visto: intestazione `Gmt time,Open,High,Low,Close,Volume`, ora `dd.MM.yyyy HH:mm:ss.fff` in UTC, un file per lato con `_BID_` o `_ASK_` nel nome, unità del volume non documentata (si tiene com'è). I campioni nei test (`Fixtures/fx`) sono costruiti a mano. Un file in ora locale o di formato diverso viene rifiutato con la spiegazione; le barre fuori dalla settimana 24×5 vengono lasciate fuori e contate. Da confrontare con il primo file vero dell'utente. | 12 | +| Formato dei file a un minuto di HistData | Scritto da conoscenze generali: ASCII generico senza intestazione, `;`, ora `yyyyMMdd HHmmss` di New York senza ora legale (UTC−5 tutto l'anno), solo denaro, coppia nel nome `DAT_ASCII_EURUSD_M1_2024.csv`. Il formato MetaTrader (`DAT_MT_…`) viene rifiutato. Campioni costruiti a mano; da confrontare con il primo file vero. | 12 | +| Le sette valute nello storico della BCE dal 1999 | Lo zip `eurofxref-hist.zip` ha le colonne USD, JPY, GBP, CHF, AUD, CAD e NZD (controllato sul file registrato di due giorni); non è stato controllato su tutto lo storico che ogni giorno le abbia tutte. Un giorno senza un cambio toglie solo le coppie che lo usano, e `anubis data ecb` dice quante barre mancano. | 12 | ## Verifiche della Fase 2 (dati di mercato) diff --git a/docs/MANUALE.md b/docs/MANUALE.md index 8aa6ffb..278539b 100644 --- a/docs/MANUALE.md +++ b/docs/MANUALE.md @@ -290,7 +290,7 @@ Chi aggiorna da una versione precedente trova nel Diario una riga sola: da quest } ``` -Le colonne si indicano con il nome dell'intestazione o con il numero, contando da 0. `timeframe` è `1m` (al minuto) o `1d` (giornaliero). `time_format` è `auto`, `unix_s`, `unix_ms`, `unix_us` o un formato di data. `continuous` è `true` per i mercati che non chiudono mai (crypto), `false` per le azioni. Poi: +Le colonne si indicano con il nome dell'intestazione o con il numero, contando da 0. `timeframe` è `1m` (al minuto), `15m`, `30m`, `1h`, `4h`, `8h` o `1d` (giornaliero). `time_format` è `auto`, `unix_s`, `unix_ms`, `unix_us` o un formato di data. `time_zone` è un fuso come `Europe/Rome` oppure uno spostamento fisso tutto l'anno come `UTC-05:00`. `continuous` è `true` per i mercati che non chiudono mai (crypto), `false` per le azioni. Poi: ```sh docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data csv /data/import/file.csv @@ -298,6 +298,16 @@ docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data csv Se hai impostato `PUID` e `PGID`, metti quei numeri al posto di `99:100`. Il comando scrive quante barre ha letto e i problemi trovati. +**Valute per la ricerca.** Due comandi preparano le 28 coppie delle otto valute (EUR, GBP, AUD, NZD, USD, CAD, CHF, JPY) nello storico di ricerca; il bot non le usa per decidere. + +- `data ecb` ricava ogni giorno dal 1999 le 28 coppie dai cambi di riferimento della BCE (per esempio USDJPY è il cambio dello yen diviso quello del dollaro). Scarica lo stesso file di `backtest base`; con `--offline` usa quello già scaricato. +- `data fx ` legge un file a un minuto che scarichi tu da Dukascopy (un file per il prezzo denaro, `_BID_` nel nome, e uno per la lettera, `_ASK_`, in ora GMT) o da HistData (formato ASCII generico, `DAT_ASCII_EURUSD_M1_2024.csv`, solo denaro). Scrive le barre da un minuto e quelle da 15 minuti costruite da quelle. Se il nome del file non dice la coppia, aggiungi `--symbol EURUSD`. Le barre del fine settimana vengono lasciate fuori e il comando dice quante. Un formato diverso viene rifiutato con la spiegazione. + +```sh +docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data ecb +docker exec -u 99:100 -e HOME=/tmp anubis dotnet /app/Anubis.Server.dll data fx /data/import/DAT_ASCII_EURUSD_M1_2024.csv +``` + Attenzione: il Laboratorio legge dallo storico di ricerca solo le serie giornaliere di Binance. I dati importati con `"venue": "import"` restano in archivio e il Laboratorio **non li usa**. Per usarli servono `"venue": "binance"`, `"timeframe": "1d"` e un simbolo di Binance come `BTCUSDT`: in quel caso le tue barre **sostituiscono** quelle già scaricate per gli stessi giorni, anche per la revisione trimestrale. Fallo solo se sei sicuro dei dati. --- diff --git a/src/Anubis.Server/BacktestCommand.cs b/src/Anubis.Server/BacktestCommand.cs index 4be5761..7c8dea1 100644 --- a/src/Anubis.Server/BacktestCommand.cs +++ b/src/Anubis.Server/BacktestCommand.cs @@ -106,17 +106,9 @@ internal static class BacktestCommand } /// The ECB history of EUR/USD, kept next to the research data so an offline run uses the same rates. - private static async Task> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output) + internal static async Task> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output) { - var path = Path.Combine(researchRoot, "ecb-eurofxref-hist.zip"); - if (!offline || !File.Exists(path)) - { - var zip = await http.GetBytesAsync(Ecb.History, null, null, CancellationToken.None).ConfigureAwait(false) - ?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true); - await File.WriteAllBytesAsync(path, zip).ConfigureAwait(false); - } - - var rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(await File.ReadAllBytesAsync(path).ConfigureAwait(false)), ["USD"]); + var rates = await Ecb.LoadHistoryAsync(http, researchRoot, offline, ["USD"], CancellationToken.None).ConfigureAwait(false); await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Cambi BCE EUR/USD: {rates.Count} giorni, dal {rates[0].Date:yyyy-MM-dd} al {rates[^1].Date:yyyy-MM-dd}.")) .ConfigureAwait(false); return rates; diff --git a/src/Anubis.Server/DataCommand.cs b/src/Anubis.Server/DataCommand.cs index 2d6a0bc..e9e52f6 100644 --- a/src/Anubis.Server/DataCommand.cs +++ b/src/Anubis.Server/DataCommand.cs @@ -15,15 +15,18 @@ internal static class DataCommand { private const string Usage = "Uso: anubis data report [--days N] [--out file.md]\n" + - " anubis data binance <1d|1m> (per esempio BTCUSDT 1d 2017-08)\n" + - " anubis data csv (colonne descritte in file.mapping.json o mapping.json)\n" + + " anubis data binance <1d|1m|15m|30m|1h|4h|8h> (per esempio BTCUSDT 1d 2017-08)\n" + + " anubis data csv (colonne descritte in file.mapping.json o mapping.json)\n" + + " anubis data ecb [--offline] (le 28 coppie delle otto valute dai cambi giornalieri della BCE, dal 1999;\n" + + " con --offline usa lo storico già scaricato, anche da backtest base)\n" + + " anubis data fx [--symbol EURUSD] (file a un minuto di Dukascopy o HistData: scrive le barre da 1 e da 15 minuti)\n" + "Opzioni comuni: [--data-dir , obbligatoria fuori dal container]"; public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, HttpMessageHandler? handler = null) { output ??= Console.Out; - if (args.Length < 1 || args[0] is not ("report" or "binance" or "csv")) + if (args.Length < 1 || args[0] is not ("report" or "binance" or "csv" or "ecb" or "fx")) { await output.WriteLineAsync(Usage).ConfigureAwait(false); return 2; @@ -58,6 +61,26 @@ internal static class DataCommand var result = await new CsvImporter(new ResearchStore(config.Data.Research)).ImportAsync(file, CsvImporter.MappingFor(file), CancellationToken.None) .ConfigureAwait(false); await WriteAsync(output, result).ConfigureAwait(false); + return 0; + case "ecb" when positional.Count == 0: + config.Data.Ensure(); + using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false)) + { + http.Timeout = TimeSpan.FromMinutes(5); + http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + await EcbAsync(new ApiHttp(http, clock, Ecb.Source), new ResearchStore(config.Data.Research), rest.Contains("--offline"), output) + .ConfigureAwait(false); + } + + return 0; + case "fx" when positional.Count == 1: + config.Data.Ensure(); + foreach (var imported in await new FxMinuteImporter(new ResearchStore(config.Data.Research)) + .ImportAsync(Path.GetFullPath(positional[0]), Option(rest, "--symbol"), CancellationToken.None).ConfigureAwait(false)) + { + await WriteAsync(output, imported).ConfigureAwait(false); + } + return 0; default: await output.WriteLineAsync(Usage).ConfigureAwait(false); @@ -72,6 +95,33 @@ internal static class DataCommand } } + /// The 28 pairs from the ECB history (the zip shared with backtest base), one series each under research/ecb. + private static async Task EcbAsync(ApiHttp http, ResearchStore store, bool offline, TextWriter output) + { + var rates = await Ecb.LoadHistoryAsync(http, store.Root, offline, EcbCrosses.Rates, CancellationToken.None).ConfigureAwait(false); + var crosses = EcbCrosses.Build(rates); + var written = crosses.Where(c => c.Value.Count > 0).ToList(); + if (written.Count == 0) + { + throw new MarketDataException("BCE: lo storico non contiene i cambi delle sette valute.", retryable: false); + } + + foreach (var (pair, bars) in written) + { + await store.WriteAsync(EcbCrosses.Venue, pair, Timeframes.Day, bars, CancellationToken.None).ConfigureAwait(false); + } + + var days = written.SelectMany(c => c.Value.Select(b => b.OpensAt)).Distinct().Order().ToList(); + var missing = days.Count * crosses.Count - crosses.Values.Sum(b => b.Count); + await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, + $"Coppie di valute dai cambi BCE: {written.Count} coppie, {days.Count} giorni, dal {days[0]:yyyy-MM-dd} al {days[^1]:yyyy-MM-dd}.")).ConfigureAwait(false); + if (missing > 0) + { + await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, + $"- {missing} barre giornaliere mancano perché quel giorno la BCE non ha pubblicato uno dei due cambi.")).ConfigureAwait(false); + } + } + private static async Task ReportAsync(Platform.StartupConfig config, IClock clock, IReadOnlyList rest, TextWriter output) { if (!config.IsComplete) diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index 83dcb2c..dd062f2 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -26,7 +26,7 @@ static async Task RunAsync(string[] args) return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false); } - // "anubis data report|binance|csv": the data quality report and the research imports (Phase 2). + // "anubis data report|binance|csv|ecb|fx": the data quality report and the research imports (Phases 2 and 12). if (args.Length >= 1 && args[0] == "data") { return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false); diff --git a/src/Anubis/Data/BarAggregator.cs b/src/Anubis/Data/BarAggregator.cs new file mode 100644 index 0000000..a16703c --- /dev/null +++ b/src/Anubis/Data/BarAggregator.cs @@ -0,0 +1,89 @@ +namespace Anubis.Data; + +/// +/// Builds longer bars from shorter ones (Phase 12, ADR 0028), as a pure function in : no digit is lost. +/// A bucket is aligned on a multiple of its length counted from the Unix epoch in UTC: 15 minutes, 30 minutes and one hour +/// then also fall on the New York hours and on the server clock (New York + 7 hours); 4 and 8 hours fall on 00, 04, 08 … +/// UTC like the Binance archives. Open is the first bar's, high the highest, low the lowest, close the last bar's, volume +/// the sum; quote volume and trades are summed only when every bar of the bucket has them. A bucket without bars gives no +/// bar: nothing is ever carried forward. +/// +public static class BarAggregator +{ + /// The start of the bucket of that holds , in UTC. + public static DateTimeOffset BucketOf(DateTimeOffset moment, TimeSpan length) + { + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(length, TimeSpan.Zero); + var ticks = (moment.UtcTicks - DateTimeOffset.UnixEpoch.UtcTicks) / length.Ticks * length.Ticks; + if (moment.UtcTicks < DateTimeOffset.UnixEpoch.UtcTicks && (moment.UtcTicks - DateTimeOffset.UnixEpoch.UtcTicks) % length.Ticks != 0) + { + ticks -= length.Ticks; // Before 1970 the division rounds towards zero, not down. + } + + return new DateTimeOffset(DateTimeOffset.UnixEpoch.UtcTicks + ticks, TimeSpan.Zero); + } + + /// + /// The bars of built from (usually one-minute bars), oldest first. + /// Every input bar must open on a whole UTC minute and appear once. With , a bucket that + /// ends after it is left out: it has not closed yet, and an unfinished bar must never reach the data. + /// + public static IReadOnlyList Aggregate(IEnumerable bars, string timeframe, DateTimeOffset? completeBefore = null) + { + ArgumentNullException.ThrowIfNull(bars); + var length = Timeframes.Length(timeframe); + var ordered = bars.OrderBy(b => b.OpensAt).ToList(); + for (var i = 0; i < ordered.Count; i++) + { + if (ordered[i].OpensAt.UtcTicks % TimeSpan.TicksPerMinute != 0) + { + throw new ArgumentException($"La barra delle {ordered[i].OpensAt:O} non comincia a un minuto intero.", nameof(bars)); + } + + if (i > 0 && ordered[i].OpensAt == ordered[i - 1].OpensAt) + { + throw new ArgumentException($"Due barre per lo stesso momento: {ordered[i].OpensAt:O}.", nameof(bars)); + } + } + + var result = new List(); + var start = 0; + while (start < ordered.Count) + { + var bucket = BucketOf(ordered[start].OpensAt, length); + var end = start; + while (end < ordered.Count && BucketOf(ordered[end].OpensAt, length) == bucket) + { + end++; + } + + if (completeBefore is not { } cut || bucket + length <= cut) + { + result.Add(Merge(bucket, ordered, start, end)); + } + + start = end; + } + + return result; + } + + private static ResearchBar Merge(DateTimeOffset bucket, List bars, int start, int end) + { + var first = bars[start]; + decimal high = first.High, low = first.Low, volume = 0m; + decimal? quoteVolume = 0m; + long? trades = 0; + for (var i = start; i < end; i++) + { + var bar = bars[i]; + high = Math.Max(high, bar.High); + low = Math.Min(low, bar.Low); + volume += bar.Volume; + quoteVolume = quoteVolume is { } q && bar.QuoteVolume is { } bq ? q + bq : null; + trades = trades is { } t && bar.Trades is { } bt ? t + bt : null; + } + + return new ResearchBar(bucket, first.Open, high, low, bars[end - 1].Close, volume) { QuoteVolume = quoteVolume, Trades = trades }; + } +} diff --git a/src/Anubis/Data/BarCalendars.cs b/src/Anubis/Data/BarCalendars.cs new file mode 100644 index 0000000..47a0e96 --- /dev/null +++ b/src/Anubis/Data/BarCalendars.cs @@ -0,0 +1,154 @@ +using Anubis.Core; + +namespace Anubis.Data; + +/// +/// When a market has bars (Phase 12, ADR 0028): a bar of a given length that opens at a given moment is "open" when the +/// market trades during at least part of it, so a bar that straddles the opening or the close holds traded minutes and +/// belongs to the calendar. +/// +public interface IBarCalendar +{ + /// Short name, part of the data fingerprint: 24x7, 24x5, exchange. + string Name { get; } + + bool IsOpen(DateTimeOffset opensAt, TimeSpan length); + + /// Bars of in a year, to annualise. + int PeriodsPerYear(TimeSpan length); +} + +/// The three calendars of the research bars: crypto every day, currencies five days a week, exchanges by session. +public static class BarCalendars +{ + /// Crypto: every moment of every day. + public static IBarCalendar Always { get; } = new AlwaysOpen(); + + /// + /// Currencies, 24×5: open from Sunday 17:00 to Friday 17:00 New York time, following US daylight saving only (Monday + /// 00:00 to Saturday 00:00 of the server clock). Daily bars, which open at 00:00 UTC, count Monday to Friday: the days + /// the ECB publishes; Sunday evening belongs to Monday's trading. + /// + public static IBarCalendar Fx { get; } = new FxWeek(); + + /// An exchange: the bars that overlap one of its sessions (early closes included). + public static IBarCalendar Exchange(IEnumerable sessions) => new ExchangeSessions(sessions); + + /// The opening moments of the bars of in [from, to) when the calendar is open, aligned as . + public static IEnumerable Moments(this IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to, TimeSpan length) + { + ArgumentNullException.ThrowIfNull(calendar); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(length, TimeSpan.Zero); + return Walk(calendar, from, to, length); + + static IEnumerable Walk(IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to, TimeSpan length) + { + var t = BarAggregator.BucketOf(from, length); + if (t < from) + { + t += length; + } + + for (; t < to; t += length) + { + if (calendar.IsOpen(t, length)) + { + yield return t; + } + } + } + } + + private sealed class AlwaysOpen : IBarCalendar + { + public string Name => "24x7"; + + public bool IsOpen(DateTimeOffset opensAt, TimeSpan length) => true; + + public int PeriodsPerYear(TimeSpan length) => (int)(TimeSpan.FromDays(365).Ticks / length.Ticks); + } + + private sealed class FxWeek : IBarCalendar + { + private static readonly TimeSpan Five = TimeSpan.FromHours(17); + + // A plain week of January 2024, far from any change of the clocks. + private static readonly DateTimeOffset ReferenceWeek = new(2024, 1, 7, 0, 0, 0, TimeSpan.Zero); + + public string Name => "24x5"; + + public bool IsOpen(DateTimeOffset opensAt, TimeSpan length) + { + if (length >= TimeSpan.FromDays(1)) + { + return opensAt.UtcDateTime.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday); + } + + var local = TimeZoneInfo.ConvertTime(opensAt, Zones.NewYork); + var closedUntil = local.DayOfWeek switch + { + DayOfWeek.Friday when local.TimeOfDay >= Five => 2, + DayOfWeek.Saturday => 1, + DayOfWeek.Sunday when local.TimeOfDay < Five => 0, + _ => -1, + }; + if (closedUntil < 0) + { + return true; + } + + var reopens = Zones.At(DateOnly.FromDateTime(local.Date).AddDays(closedUntil), new TimeOnly(17, 0), Zones.NewYork); + return opensAt + length > reopens; + } + + public int PeriodsPerYear(TimeSpan length) => 52 * this.Moments(ReferenceWeek, ReferenceWeek.AddDays(7), length).Count(); + } + + private sealed class ExchangeSessions : IBarCalendar + { + private readonly MarketSession[] _sessions; + + public ExchangeSessions(IEnumerable sessions) + { + ArgumentNullException.ThrowIfNull(sessions); + _sessions = [.. sessions.OrderBy(s => s.CloseUtc)]; + } + + public string Name => "exchange"; + + public bool IsOpen(DateTimeOffset opensAt, TimeSpan length) + { + // The first session that closes after the bar opens: the bar is open when that session opens before it ends. + int lo = 0, hi = _sessions.Length; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (_sessions[mid].CloseUtc <= opensAt) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo < _sessions.Length && _sessions[lo].OpenUtc < opensAt + length; + } + + /// About 252 sessions a year, each with the average number of bars of the sessions given (a regular one when none is). + public int PeriodsPerYear(TimeSpan length) + { + static int Bars(DateTimeOffset open, DateTimeOffset close, TimeSpan length) => + (int)((BarAggregator.BucketOf(close.AddTicks(-1), length) - BarAggregator.BucketOf(open, length)).Ticks / length.Ticks) + 1; + + if (_sessions.Length == 0) + { + var regular = new DateTimeOffset(2024, 1, 2, 14, 30, 0, TimeSpan.Zero); + return 252 * Bars(regular, regular.AddMinutes(390), length); + } + + return 252 * (int)Math.Round(_sessions.Average(s => Bars(s.OpenUtc, s.CloseUtc, length)), MidpointRounding.AwayFromZero); + } + } +} diff --git a/src/Anubis/Data/BarDataset.cs b/src/Anubis/Data/BarDataset.cs new file mode 100644 index 0000000..d53bae3 --- /dev/null +++ b/src/Anubis/Data/BarDataset.cs @@ -0,0 +1,282 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; + +namespace Anubis.Data; + +/// The prices of one series on the common clock of a : NaN where it has no bar. +public sealed class BarColumns +{ + private readonly double[] _open, _high, _low, _close, _volume; + + private BarColumns(double[] open, double[] high, double[] low, double[] close, double[] volume) + { + (_open, _high, _low, _close, _volume) = (open, high, low, close, volume); + } + + public IReadOnlyList Open => _open; + + public IReadOnlyList High => _high; + + public IReadOnlyList Low => _low; + + public IReadOnlyList Close => _close; + + public IReadOnlyList Volume => _volume; + + /// Whether the series has a bar at the position of the clock. + public bool Has(int t) => !double.IsNaN(_close[t]); + + internal static BarColumns Empty(int length) + { + static double[] Nan(int n) + { + var values = new double[n]; + Array.Fill(values, double.NaN); + return values; + } + + return new BarColumns(Nan(length), Nan(length), Nan(length), Nan(length), Nan(length)); + } + + internal void Set(int t, ResearchBar bar) => + (_open[t], _high[t], _low[t], _close[t], _volume[t]) = ((double)bar.Open, (double)bar.High, (double)bar.Low, (double)bar.Close, (double)bar.Volume); + + internal BarColumns Slice(int start, int count) => new( + _open[start..(start + count)], _high[start..(start + count)], _low[start..(start + count)], _close[start..(start + count)], _volume[start..(start + count)]); + + internal void Write(StringBuilder text, IReadOnlyList clock) + { + for (var t = 0; t < clock.Count; t++) + { + if (Has(t)) + { + text.Append(CultureInfo.InvariantCulture, + $"{clock[t].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'},{_open[t]:R},{_high[t]:R},{_low[t]:R},{_close[t]:R},{_volume[t]:R}\n"); + } + } + } +} + +/// +/// Research bars shorter than a day (or daily) of several series on one common clock (Phase 12, ADR 0028): every moment +/// of the calendar in the window, in columns of (analysis data, SPEC 5.4). A series without a bar at +/// a moment has NaN there: nothing is ever filled. Bars outside the calendar are left out and counted in +/// . Built once and never changed, like BacktestDataset. +/// +public sealed class BarDataset +{ + private readonly Dictionary _bars; + private readonly Dictionary _asks; + private readonly DateTimeOffset[] _clock; + + private BarDataset(string timeframe, IBarCalendar calendar, DateTimeOffset[] clock, Dictionary bars, Dictionary asks, int dropped) + { + Timeframe = timeframe; + Length = Timeframes.Length(timeframe); + Calendar = calendar; + _clock = clock; + _bars = bars; + _asks = asks; + Symbols = [.. bars.Keys.Order(StringComparer.Ordinal)]; + Dropped = dropped; + } + + public string Timeframe { get; } + + public TimeSpan Length { get; } + + public IBarCalendar Calendar { get; } + + /// The series, in ordinal order. + public IReadOnlyList Symbols { get; } + + /// The opening moments of the bars, oldest first, in UTC. + public IReadOnlyList Clock => _clock; + + /// Bars inside the window but outside the calendar, or not on its grid: left out. + public int Dropped { get; } + + public int PeriodsPerYear => Calendar.PeriodsPerYear(Length); + + /// The prices of a series (the bid when the source gives both sides). + public BarColumns Bars(string symbol) => + _bars.TryGetValue(symbol, out var columns) ? columns : throw new KeyNotFoundException($"{symbol} non è nei dati."); + + /// The ask prices of a series, or null when the source gives only one side. + public BarColumns? Ask(string symbol) => _asks.GetValueOrDefault(symbol); + + public bool Has(string symbol, int t) => Bars(symbol).Has(t); + + /// The position of a moment on the clock, or -1. + public int IndexOf(DateTimeOffset opensAt) + { + var index = Array.BinarySearch(_clock, opensAt); + return index >= 0 ? index : -1; + } + + /// When the bar at position closes: only from then on is it known. + public DateTimeOffset ClosesAt(int t) => _clock[t] + Length; + + /// + /// The data known at : only the bars that have closed by then. A bar still open is never + /// shown, not even in part. + /// + public BarDataset Through(DateTimeOffset moment) + { + var count = 0; + while (count < _clock.Length && _clock[count] + Length <= moment) + { + count++; + } + + return Slice(0, count); + } + + /// The bars that open in [from, to). + public BarDataset Between(DateTimeOffset from, DateTimeOffset to) + { + var start = 0; + while (start < _clock.Length && _clock[start] < from) + { + start++; + } + + var end = start; + while (end < _clock.Length && _clock[end] < to) + { + end++; + } + + return Slice(start, end - start); + } + + /// + /// A SHA-256 of the timeframe, the calendar, the clock and every bar: two reports with the same fingerprint and the + /// same plan were computed on exactly the same data. + /// + public string Fingerprint() + { + var text = new StringBuilder(); + text.Append(CultureInfo.InvariantCulture, $"{Timeframe}|{Calendar.Name}|{_clock.Length}"); + if (_clock.Length > 0) + { + text.Append(CultureInfo.InvariantCulture, $"|{_clock[0].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}|{_clock[^1].UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}"); + } + + text.Append('\n'); + foreach (var symbol in Symbols) + { + text.Append(symbol).Append('\n'); + _bars[symbol].Write(text, _clock); + if (_asks.TryGetValue(symbol, out var ask)) + { + text.Append("ask\n"); + ask.Write(text, _clock); + } + } + + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } + + /// + /// The dataset of the bars given, on the moments of in [from, to). + /// holds the ask side of the series that have one. + /// + public static BarDataset Build(string timeframe, IBarCalendar calendar, DateTimeOffset from, DateTimeOffset to, + IReadOnlyDictionary> bars, IReadOnlyDictionary>? asks = null) + { + ArgumentNullException.ThrowIfNull(calendar); + ArgumentNullException.ThrowIfNull(bars); + var length = Timeframes.Length(timeframe); + var clock = calendar.Moments(from, to, length).ToArray(); + var index = new Dictionary(clock.Length); + for (var t = 0; t < clock.Length; t++) + { + index[clock[t]] = t; + } + + var dropped = 0; + Dictionary Columns(IReadOnlyDictionary> series) + { + var columns = new Dictionary(StringComparer.Ordinal); + foreach (var (symbol, list) in series) + { + var column = BarColumns.Empty(clock.Length); + foreach (var bar in list.Where(b => b.OpensAt >= from && b.OpensAt < to)) + { + if (index.TryGetValue(bar.OpensAt, out var t)) + { + column.Set(t, bar); + } + else + { + dropped++; + } + } + + columns[symbol] = column; + } + + return columns; + } + + var bidColumns = Columns(bars); + var askColumns = asks is null ? new Dictionary(StringComparer.Ordinal) : Columns(asks); + var stray = askColumns.Keys.FirstOrDefault(s => !bidColumns.ContainsKey(s)); + if (stray is not null) + { + throw new ArgumentException($"{stray} ha i prezzi lettera ma non quelli denaro.", nameof(asks)); + } + + return new BarDataset(timeframe, calendar, clock, bidColumns, askColumns, dropped); + } + + /// The series of a venue from the research history, as they are stored. + public static async Task LoadAsync(ResearchStore store, string venue, IReadOnlyList symbols, string timeframe, IBarCalendar calendar, + DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(symbols); + var bars = new Dictionary>(StringComparer.Ordinal); + foreach (var symbol in symbols) + { + bars[symbol] = await store.ReadAsync(venue, symbol, timeframe, from, to, cancellationToken).ToListAsync(cancellationToken).ConfigureAwait(false); + } + + return Build(timeframe, calendar, from, to, bars); + } + + /// + /// Currency pairs of a venue on the 24×5 calendar, from the series written by anubis data fx: the bid of + /// EURUSD-BID and, when the venue has it, the ask of EURUSD-ASK, both under the name EURUSD. + /// + public static async Task LoadQuotesAsync(ResearchStore store, string venue, IReadOnlyList pairs, string timeframe, + DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(pairs); + var bids = new Dictionary>(StringComparer.Ordinal); + var asks = new Dictionary>(StringComparer.Ordinal); + foreach (var pair in pairs) + { + bids[pair] = await store.ReadAsync(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Bid), timeframe, from, to, cancellationToken) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (store.Years(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Ask), timeframe).Count > 0) + { + asks[pair] = await store.ReadAsync(venue, FxMinuteFiles.Series(pair, FxMinuteFiles.Ask), timeframe, from, to, cancellationToken) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + } + + return Build(timeframe, BarCalendars.Fx, from, to, bids, asks); + } + + private BarDataset Slice(int start, int count) => new( + Timeframe, + Calendar, + _clock[start..(start + count)], + _bars.ToDictionary(p => p.Key, p => p.Value.Slice(start, count), StringComparer.Ordinal), + _asks.ToDictionary(p => p.Key, p => p.Value.Slice(start, count), StringComparer.Ordinal), + Dropped); +} diff --git a/src/Anubis/Data/EcbCrosses.cs b/src/Anubis/Data/EcbCrosses.cs new file mode 100644 index 0000000..fbd003f --- /dev/null +++ b/src/Anubis/Data/EcbCrosses.cs @@ -0,0 +1,60 @@ +using Anubis.Baskets; + +namespace Anubis.Data; + +/// +/// The 28 pairs of the eight currencies, day by day since 1999, from the ECB reference rates (Phase 12, ADR 0028). The ECB +/// gives how many units of each currency buy one euro: with r(EUR) = 1, the pair BQ is r(Q) / r(B), rounded to 10 +/// decimals (to even). A pair whose rate is missing on a day has no bar that day; the others are still built. Each bar +/// opens at 00:00 UTC of the day with open = high = low = close and volume 0, venue "ecb", timeframe "1d". +/// The rates of day d are fixed at about 16:00 CET of d (the same rule as EuroHistory): a decision at the close +/// of d may use them, and shows the bar of d only once the day is over. +/// +public static class EcbCrosses +{ + public const string Venue = Ecb.Source; + + public const int Decimals = 10; + + /// The seven rates the ECB publishes against the euro for the other currencies: from the shared list. + public static IReadOnlyList Rates { get; } = [.. Currencies.Order.Where(c => c != Currencies.Eur)]; + + /// The bars of the 28 pairs in the order of , each oldest first (empty when no day has both rates). + public static IReadOnlyDictionary> Build(IEnumerable rates) + { + ArgumentNullException.ThrowIfNull(rates); + var byDay = new SortedDictionary>(); + foreach (var rate in rates.Where(r => r.Base == Currencies.Eur && Rates.Contains(r.Quote))) + { + if (!byDay.TryGetValue(rate.Date, out var day)) + { + byDay[rate.Date] = day = new Dictionary(StringComparer.Ordinal) { [Currencies.Eur] = 1m }; + } + + if (day.TryGetValue(rate.Quote, out var known) && known != rate.Rate) + { + throw new ArgumentException($"BCE: due cambi diversi per {rate.Quote} il {rate.Date:yyyy-MM-dd}.", nameof(rates)); + } + + day[rate.Quote] = rate.Rate; + } + + var result = new Dictionary>(StringComparer.Ordinal); + foreach (var pair in FxPairs.All) + { + var bars = new List(); + foreach (var (date, day) in byDay) + { + if (day.TryGetValue(pair.Base, out var b) && day.TryGetValue(pair.Quote, out var q) && b > 0) + { + var value = Math.Round(q / b, Decimals, MidpointRounding.ToEven); + bars.Add(new ResearchBar(QualityChecks.Midnight(date), value, value, value, value, 0m)); + } + } + + result[pair.Name] = bars; + } + + return result; + } +} diff --git a/src/Anubis/Data/FreeSources.cs b/src/Anubis/Data/FreeSources.cs index e595bba..38101bd 100644 --- a/src/Anubis/Data/FreeSources.cs +++ b/src/Anubis/Data/FreeSources.cs @@ -4,6 +4,7 @@ using System.Security.Cryptography; using System.Text.Json; using System.Text.RegularExpressions; using System.Xml.Linq; +using Anubis.Brokers; namespace Anubis.Data; @@ -68,6 +69,32 @@ public static class Ecb using var reader = new StreamReader(entry.Open()); return reader.ReadToEnd(); } + + /// The name of the cached history zip, next to the research data. + public const string HistoryFile = "ecb-eurofxref-hist.zip"; + + public static string HistoryPath(string researchRoot) => Path.Combine(researchRoot, HistoryFile); + + /// + /// The full ECB history of the , kept in the research folder so an offline run uses the + /// same rates: downloaded again on every run, and with only when the zip is missing. Shared by + /// anubis backtest base and anubis data ecb. + /// + public static async Task> LoadHistoryAsync(ApiHttp http, string researchRoot, bool offline, IReadOnlyCollection currencies, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(http); + var path = HistoryPath(researchRoot); + if (!offline || !File.Exists(path)) + { + var zip = await http.GetBytesAsync(History, null, null, cancellationToken).ConfigureAwait(false) + ?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true); + Directory.CreateDirectory(researchRoot); + await File.WriteAllBytesAsync(path, zip, cancellationToken).ConfigureAwait(false); + } + + return ParseHistoryCsv(ExtractHistoryCsv(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)), currencies); + } } /// The weekly economic calendar of Forex Factory (faireconomy.media). It has no actual values. diff --git a/src/Anubis/Data/FxMinuteFiles.cs b/src/Anubis/Data/FxMinuteFiles.cs new file mode 100644 index 0000000..0007503 --- /dev/null +++ b/src/Anubis/Data/FxMinuteFiles.cs @@ -0,0 +1,176 @@ +using System.Text.RegularExpressions; +using Anubis.Baskets; + +namespace Anubis.Data; + +/// A one-minute FX file recognised by : its format, pair, side and the mapping that reads it. +public sealed record FxMinuteFile(string Format, string Pair, string Side, CsvMapping Mapping) +{ + /// The venue of the research history: the format's name. + public string Venue => Format; + + /// The series name: the pair and its side, such as EURUSD-BID. + public string Series => FxMinuteFiles.Series(Pair, Side); +} + +/// +/// The two one-minute FX formats the research document names (Phase 12, ADR 0028). The layouts come from general +/// knowledge, not from a file seen: the test fixtures are constructed samples, to check on the first real file. +/// +/// Dukascopy: header Gmt time,Open,High,Low,Close,Volume, times dd.MM.yyyy HH:mm:ss.fff in UTC, one file +/// per side with _BID_ or _ASK_ in its name. +/// HistData generic ASCII M1: no header, ;, times yyyyMMdd HHmmss in New York winter time all year +/// (UTC−5), bid only; the pair is in the name DAT_ASCII_EURUSD_M1_2024.csv. +/// +/// Anything else is refused with a message in Italian. +/// +public static partial class FxMinuteFiles +{ + public const string Dukascopy = "dukascopy"; + public const string HistData = "histdata"; + public const string Bid = "BID"; + public const string Ask = "ASK"; + + public const string Unknown = + "Formato non riconosciuto. anubis data fx legge solo i file a un minuto di Dukascopy (intestazione «Gmt time,Open,High,Low,Close,Volume», " + + "un file per il denaro e uno per la lettera) e di HistData in formato ASCII generico (righe «AAAAMMGG HHMMSS;apertura;massimo;minimo;chiusura;volume»)."; + + public static string Series(string pair, string side) => pair + "-" + side; + + /// + /// Recognises a file from its first non-empty line and its name; (from --symbol) wins + /// over the pair in the name. Throws with the reason in Italian. + /// + public static FxMinuteFile Detect(string path, string? firstLine, string? symbol) + { + ArgumentNullException.ThrowIfNull(path); + var name = Path.GetFileName(path); + var line = (firstLine ?? "").Trim().TrimStart(''); + if (line.StartsWith("Local time", StringComparison.OrdinalIgnoreCase)) + { + throw new FormatException("Il file di Dukascopy è in ora locale: scaricalo di nuovo in ora GMT (colonna «Gmt time»)."); + } + + if (line.StartsWith("Gmt time,", StringComparison.OrdinalIgnoreCase)) + { + var side = name.Contains("_BID_", StringComparison.OrdinalIgnoreCase) ? Bid + : name.Contains("_ASK_", StringComparison.OrdinalIgnoreCase) ? Ask + : throw new FormatException("Dal nome del file di Dukascopy non si capisce se i prezzi sono denaro o lettera: deve contenere _BID_ o _ASK_."); + var pair = Pair(symbol ?? name.Split('_')[0]); + return new FxMinuteFile(Dukascopy, pair, side, new CsvMapping + { + Symbol = Series(pair, side), + Venue = Dukascopy, + Timeframe = Timeframes.Minute, + Delimiter = ",", + HasHeader = true, + Time = "Gmt time", + TimeFormat = "dd.MM.yyyy HH:mm:ss.fff", + TimeZone = "UTC", + Open = "Open", + High = "High", + Low = "Low", + Close = "Close", + Volume = "Volume", + Continuous = false, + }); + } + + if (HistDataLine().IsMatch(line)) + { + var named = HistDataName().Match(name); + var pair = Pair(symbol ?? (named.Success ? named.Groups[1].Value + : throw new FormatException("Dal nome del file di HistData non si capisce la coppia: indicala con --symbol, per esempio --symbol EURUSD."))); + return new FxMinuteFile(HistData, pair, Bid, new CsvMapping + { + Symbol = Series(pair, Bid), + Venue = HistData, + Timeframe = Timeframes.Minute, + Delimiter = ";", + HasHeader = false, + Time = "0", + TimeFormat = "yyyyMMdd HHmmss", + TimeZone = "UTC-05:00", + Open = "1", + High = "2", + Low = "3", + Close = "4", + Volume = "5", + Continuous = false, + }); + } + + throw new FormatException(Unknown); + } + + private static string Pair(string text) + { + var pair = text.Trim().ToUpperInvariant(); + return FxPairs.Find(pair)?.Name + ?? throw new FormatException($"«{text}» non è una delle 28 coppie delle otto valute: indica la coppia con --symbol, per esempio --symbol EURUSD."); + } + + [GeneratedRegex(@"^\d{8} \d{6};", RegexOptions.CultureInvariant)] + private static partial Regex HistDataLine(); + + [GeneratedRegex(@"DAT_ASCII_([A-Za-z]{6})_M1", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)] + private static partial Regex HistDataName(); +} + +/// +/// anubis data fx (Phase 12): reads a one-minute file of , leaves out the bars outside the +/// 24×5 week (saying how many), checks the rest against that calendar, writes the minutes and then the 15-minute bars +/// rebuilt from every stored minute of the buckets the file touched. +/// +public sealed class FxMinuteImporter(ResearchStore store) +{ + private static readonly TimeSpan OneMinute = TimeSpan.FromMinutes(1); + + /// The import of the minutes, then that of the 15-minute bars. + public async Task> ImportAsync(string path, string? symbol, CancellationToken cancellationToken) + { + var lines = await File.ReadAllLinesAsync(path, cancellationToken).ConfigureAwait(false); + var file = FxMinuteFiles.Detect(path, lines.FirstOrDefault(l => l.Trim().Length > 0), symbol); + var parsed = CsvImporter.Parse(lines, file.Mapping); + var notes = parsed.Notes.ToList(); + var ordered = parsed.Bars.OrderBy(b => b.OpensAt).ToList(); + if (ordered.FirstOrDefault(b => b.OpensAt.UtcTicks % TimeSpan.TicksPerMinute != 0) is { } odd) + { + throw new FormatException($"Il file non contiene barre da un minuto: una comincia alle {odd.OpensAt.UtcDateTime:yyyy-MM-dd HH:mm:ss.fff} (UTC)."); + } + + var open = ordered.Where(b => BarCalendars.Fx.IsOpen(b.OpensAt, OneMinute)).ToList(); + if (open.Count == 0) + { + throw new FormatException($"Nessuna barra valida nel file: {parsed.Errors} righe non lette su {parsed.Lines}."); + } + + if (open.Count > 1 && !open.Zip(open.Skip(1)).Any(p => p.Second.OpensAt - p.First.OpensAt == OneMinute)) + { + throw new FormatException("Il file non contiene barre da un minuto: nessuna barra segue la precedente di un minuto."); + } + + if (open.Count < ordered.Count) + { + notes.Add($"{ordered.Count - open.Count} barre fuori dall'orario del mercato (24×5) lasciate fuori"); + } + + var issues = QualityChecks.CheckIntraday(open.Select(b => b.ToBar()).ToList(), Timeframes.Minute, + BarCalendars.Fx.Moments(open[0].OpensAt, open[^1].OpensAt + OneMinute, OneMinute)); + notes.AddRange(issues.Take(CsvImporter.MaxReportedErrors).Select(CsvImporter.Note)); + await store.WriteAsync(file.Venue, file.Series, Timeframes.Minute, open, cancellationToken).ConfigureAwait(false); + + var quarter = Timeframes.Length(Timeframes.Minutes15); + var from = BarAggregator.BucketOf(open[0].OpensAt, quarter); + var to = BarAggregator.BucketOf(open[^1].OpensAt, quarter) + quarter; + var minutes = await store.ReadAsync(file.Venue, file.Series, Timeframes.Minute, from, to, cancellationToken).ToListAsync(cancellationToken).ConfigureAwait(false); + var quarters = BarAggregator.Aggregate(minutes, Timeframes.Minutes15); + await store.WriteAsync(file.Venue, file.Series, Timeframes.Minutes15, quarters, cancellationToken).ConfigureAwait(false); + + return + [ + new ImportResult(file.Venue, file.Series, Timeframes.Minute, open.Count, open[0].OpensAt, open[^1].OpensAt, notes), + new ImportResult(file.Venue, file.Series, Timeframes.Minutes15, quarters.Count, quarters[0].OpensAt, quarters[^1].OpensAt, []), + ]; + } +} diff --git a/src/Anubis/Data/Importers.cs b/src/Anubis/Data/Importers.cs index 3f5ea09..6cff92b 100644 --- a/src/Anubis/Data/Importers.cs +++ b/src/Anubis/Data/Importers.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; +using System.Text.RegularExpressions; using Anubis.Brokers; using Anubis.Core; @@ -93,7 +94,9 @@ public sealed record CsvMapping /// unix_ms, unix_s, unix_us, auto (milliseconds or microseconds by size), or a .NET date format such as yyyy-MM-dd HH:mm:ss. public string TimeFormat { get; init; } = "auto"; - /// Time zone of text times (IANA id); unix times are always UTC. + /// + /// Time zone of text times: an IANA id, or a fixed offset all year such as UTC-05:00; unix times are always UTC. + /// public string TimeZone { get; init; } = "UTC"; public string Open { get; init; } = "1"; @@ -123,11 +126,15 @@ public sealed record CsvMapping }; } +/// What read: the bars in file order, the notes, the unreadable lines and all the lines. +public sealed record CsvParse(IReadOnlyList Bars, IReadOnlyList Notes, int Errors, int Lines); + /// -/// The generic importer of user CSV files with one-minute or daily bars into the research history (issue #21). +/// The generic importer of user CSV files with bars of one of the into the research history +/// (issue #21; any length shorter than a day since Phase 12). /// Lines that cannot be read are counted and reported, never silently fixed. /// -public sealed class CsvImporter(ResearchStore store) +public sealed partial class CsvImporter(ResearchStore store) { public const int MaxReportedErrors = 5; @@ -146,7 +153,46 @@ public sealed class CsvImporter(ResearchStore store) var symbol = string.IsNullOrWhiteSpace(mapping.Symbol) ? Path.GetFileNameWithoutExtension(csvPath).Split('-', '_')[0].ToUpperInvariant() : mapping.Symbol; - var zone = TimeZoneInfo.FindSystemTimeZoneById(mapping.TimeZone); + var parsed = Parse(await File.ReadAllLinesAsync(csvPath, cancellationToken).ConfigureAwait(false), mapping); + var bars = parsed.Bars; + var notes = parsed.Notes.ToList(); + var ordered = bars.OrderBy(b => b.OpensAt).ToList(); + IReadOnlyList issues = []; + if (ordered.Count > 0 && Timeframes.IsIntraday(mapping.Timeframe)) + { + var length = Timeframes.Length(mapping.Timeframe); + issues = QualityChecks.CheckIntraday(ordered.Select(b => b.ToBar()).ToList(), mapping.Timeframe, + mapping.Continuous ? QualityChecks.Every(ordered[0].OpensAt, ordered[^1].OpensAt + length, length) : null); + } + else if (ordered.Count > 0) + { + var days = ordered.Select(b => new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, + (double)b.Close, (double)b.Volume)).ToList(); + issues = QualityChecks.CheckDaily(days, mapping.Continuous ? QualityChecks.EveryDay(days[0].Day, days[^1].Day) : null); + } + + notes.AddRange(issues.Take(MaxReportedErrors).Select(Note)); + + await store.WriteAsync(mapping.Venue, symbol, mapping.Timeframe, bars, cancellationToken).ConfigureAwait(false); + return new ImportResult(mapping.Venue, symbol, mapping.Timeframe, bars.Count, ordered.FirstOrDefault()?.OpensAt, ordered.LastOrDefault()?.OpensAt, notes); + } + + /// A finding of the checks as a line of the import notes. + public static string Note(QualityFinding finding) + { + ArgumentNullException.ThrowIfNull(finding); + return $"{finding.Kind} {finding.StartsAt:yyyy-MM-dd HH:mm}: {finding.Detail}"; + } + + /// + /// Reads the lines of a CSV with a mapping, without touching any file: the bars in file order, the notes on the + /// lines that could not be read (at most , then the count), and the counts. + /// + public static CsvParse Parse(IEnumerable lines, CsvMapping mapping) + { + ArgumentNullException.ThrowIfNull(lines); + ArgumentNullException.ThrowIfNull(mapping); + var zone = ZoneOf(mapping.TimeZone); var numbers = new NumberFormatInfo { NumberDecimalSeparator = mapping.DecimalSeparator, NumberGroupSeparator = mapping.DecimalSeparator == "," ? "." : "," }; var style = mapping.DecimalSeparator == "," ? NumberStyles.Float | NumberStyles.AllowThousands : NumberStyles.Float; var bars = new List(); @@ -154,7 +200,7 @@ public sealed class CsvImporter(ResearchStore store) var errors = 0; string[]? header = null; var lineNumber = 0; - foreach (var line in await File.ReadAllLinesAsync(csvPath, cancellationToken).ConfigureAwait(false)) + foreach (var line in lines) { lineNumber++; if (line.Length == 0) @@ -193,26 +239,39 @@ public sealed class CsvImporter(ResearchStore store) notes.Add($"{errors} righe non lette su {lineNumber}"); } - var ordered = bars.OrderBy(b => b.OpensAt).ToList(); - IReadOnlyList issues = []; - if (ordered.Count > 0 && mapping.Timeframe == Timeframes.Minute) - { - issues = QualityChecks.CheckMinutes(ordered.Select(b => b.ToBar()).ToList(), - mapping.Continuous ? QualityChecks.EveryMinute(ordered[0].OpensAt, ordered[^1].OpensAt.AddMinutes(1)) : null); - } - else if (ordered.Count > 0) - { - var days = ordered.Select(b => new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, - (double)b.Close, (double)b.Volume)).ToList(); - issues = QualityChecks.CheckDaily(days, mapping.Continuous ? QualityChecks.EveryDay(days[0].Day, days[^1].Day) : null); - } - - notes.AddRange(issues.Take(MaxReportedErrors).Select(i => $"{i.Kind} {i.StartsAt:yyyy-MM-dd HH:mm}: {i.Detail}")); - - await store.WriteAsync(mapping.Venue, symbol, mapping.Timeframe, bars, cancellationToken).ConfigureAwait(false); - return new ImportResult(mapping.Venue, symbol, mapping.Timeframe, bars.Count, ordered.FirstOrDefault()?.OpensAt, ordered.LastOrDefault()?.OpensAt, notes); + return new CsvParse(bars, notes, errors, lineNumber); } + /// + /// The time zone of a mapping: UTC, a fixed offset all year written UTC+hh:mm or UTC-hh:mm (HistData + /// keeps New York winter time all year), or an IANA id from the system's database. + /// + public static TimeZoneInfo ZoneOf(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + if (id == "UTC") + { + return TimeZoneInfo.Utc; + } + + var match = FixedOffset().Match(id); + if (match.Success) + { + var offset = new TimeSpan(int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture), 0); + if (offset > TimeSpan.FromHours(14)) + { + throw new TimeZoneNotFoundException($"Fuso orario «{id}» fuori dai limiti (al massimo 14 ore da UTC)."); + } + + return TimeZoneInfo.CreateCustomTimeZone(id, match.Groups[1].Value == "-" ? -offset : offset, id, id); + } + + return TimeZoneInfo.FindSystemTimeZoneById(id); + } + + [GeneratedRegex(@"^UTC([+-])(\d{2}):(\d{2})$", RegexOptions.CultureInvariant)] + private static partial Regex FixedOffset(); + private static int Index(string column, string[]? header) { if (int.TryParse(column, NumberStyles.None, CultureInfo.InvariantCulture, out var index)) diff --git a/src/Anubis/Data/Quality.cs b/src/Anubis/Data/Quality.cs index 7b34a3c..747f5e5 100644 --- a/src/Anubis/Data/Quality.cs +++ b/src/Anubis/Data/Quality.cs @@ -35,10 +35,39 @@ public static class IssueStatus public const string Corrected = "corrected"; } +/// +/// The bar lengths Anubis knows. The names are those of the Binance archives, so an archive and a series built by +/// end up in the same folder of the research history. +/// public static class Timeframes { - public const string Day = "1d"; public const string Minute = "1m"; + public const string Minutes15 = "15m"; + public const string Minutes30 = "30m"; + public const string Hour = "1h"; + public const string Hours4 = "4h"; + public const string Hours8 = "8h"; + public const string Day = "1d"; + + /// From the shortest to the longest. + public static IReadOnlyList All { get; } = [Minute, Minutes15, Minutes30, Hour, Hours4, Hours8, Day]; + + public static bool IsKnown(string timeframe) => All.Contains(timeframe); + + /// A known timeframe shorter than a day; an unknown one is not intraday. + public static bool IsIntraday(string timeframe) => timeframe != Day && IsKnown(timeframe); + + public static TimeSpan Length(string timeframe) => timeframe switch + { + Minute => TimeSpan.FromMinutes(1), + Minutes15 => TimeSpan.FromMinutes(15), + Minutes30 => TimeSpan.FromMinutes(30), + Hour => TimeSpan.FromHours(1), + Hours4 => TimeSpan.FromHours(4), + Hours8 => TimeSpan.FromHours(8), + Day => TimeSpan.FromDays(1), + _ => throw new ArgumentException($"Durata delle barre sconosciuta: «{timeframe}». Valori ammessi: {string.Join(", ", All)}.", nameof(timeframe)), + }; } /// A problem found in a series. Moments are UTC; for daily bars they are the day at 00:00 UTC. @@ -101,13 +130,22 @@ public static class QualityChecks /// Checks one-minute bars. lists the minutes that should exist (every minute for /// crypto, the session minutes for stocks); without it gaps are not looked for. /// - public static IReadOnlyList CheckMinutes(IReadOnlyList bars, IEnumerable? expected = null) + public static IReadOnlyList CheckMinutes(IReadOnlyList bars, IEnumerable? expected = null) => + CheckIntraday(bars, Timeframes.Minute, expected); + + /// + /// Checks bars shorter than a day of any the way checks minutes; + /// lists the opening moments that should exist at that length. + /// + public static IReadOnlyList CheckIntraday(IReadOnlyList bars, string timeframe, IEnumerable? expected = null) { ArgumentNullException.ThrowIfNull(bars); + var minutes = timeframe == Timeframes.Minute; var findings = new List(); foreach (var group in bars.GroupBy(b => b.OpensAt).Where(g => g.Count() > 1)) { - findings.Add(new QualityFinding(IssueKinds.Duplicate, group.Key, group.Key, $"{group.Count()} barre per lo stesso minuto")); + findings.Add(new QualityFinding(IssueKinds.Duplicate, group.Key, group.Key, + $"{group.Count()} barre per lo stesso " + (minutes ? "minuto" : "momento"))); } var unique = bars.DistinctBy(b => b.OpensAt).OrderBy(b => b.OpensAt).ToList(); @@ -126,8 +164,9 @@ public static class QualityChecks var have = unique.Select(b => b.OpensAt).ToHashSet(); foreach (var run in MissingRuns(expected, have, unique[0].OpensAt, unique[^1].OpensAt)) { - findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last, - run.Count == 1 ? "Manca la barra di un minuto" : $"Mancano {run.Count} minuti")); + findings.Add(new QualityFinding(IssueKinds.Gap, run.First, run.Last, minutes + ? run.Count == 1 ? "Manca la barra di un minuto" : $"Mancano {run.Count} minuti" + : run.Count == 1 ? $"Manca una barra da {timeframe}" : $"Mancano {run.Count} barre da {timeframe}")); } } @@ -135,11 +174,20 @@ public static class QualityChecks } /// Every minute in [from, to): the expected moments of a market that never closes. - public static IEnumerable EveryMinute(DateTimeOffset from, DateTimeOffset to) + public static IEnumerable EveryMinute(DateTimeOffset from, DateTimeOffset to) => Every(from, to, TimeSpan.FromMinutes(1)); + + /// Every from (included) to (excluded). + public static IEnumerable Every(DateTimeOffset from, DateTimeOffset to, TimeSpan step) { - for (var t = from; t < to; t = t.AddMinutes(1)) + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(step, TimeSpan.Zero); + return Steps(from, to, step); + + static IEnumerable Steps(DateTimeOffset from, DateTimeOffset to, TimeSpan step) { - yield return t; + for (var t = from; t < to; t += step) + { + yield return t; + } } } diff --git a/tests/Anubis.Tests/Fixtures/fx/DAT_ASCII_EURUSD_M1_2024.csv b/tests/Anubis.Tests/Fixtures/fx/DAT_ASCII_EURUSD_M1_2024.csv new file mode 100644 index 0000000..2503d8f --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/fx/DAT_ASCII_EURUSD_M1_2024.csv @@ -0,0 +1,5 @@ +20240102 030000;1.094500;1.094800;1.094400;1.094700;0 +20240102 030100;1.094700;1.095200;1.094600;1.095100;0 +20240102 030700;1.095100;1.095300;1.094900;1.095000;0 +20240102 031400;1.095000;1.095000;1.094100;1.094300;0 +20240102 031500;1.094300;1.094600;1.094200;1.094500;0 diff --git a/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv b/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv new file mode 100644 index 0000000..5baaf94 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv @@ -0,0 +1,6 @@ +Gmt time,Open,High,Low,Close,Volume +02.01.2024 08:00:00.000,1.09462,1.09492,1.09452,1.09482,10.5 +02.01.2024 08:01:00.000,1.09482,1.09532,1.09472,1.09522,20.25 +02.01.2024 08:07:00.000,1.09522,1.09542,1.09502,1.09512,3 +02.01.2024 08:14:00.000,1.09512,1.09512,1.09422,1.09442,1.5 +02.01.2024 08:15:00.000,1.09442,1.09472,1.09432,1.09462,7 diff --git a/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv b/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv new file mode 100644 index 0000000..008a672 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv @@ -0,0 +1,7 @@ +Gmt time,Open,High,Low,Close,Volume +02.01.2024 08:00:00.000,1.09450,1.09480,1.09440,1.09470,10.5 +02.01.2024 08:01:00.000,1.09470,1.09520,1.09460,1.09510,20.25 +02.01.2024 08:07:00.000,1.09510,1.09530,1.09490,1.09500,3 +02.01.2024 08:14:00.000,1.09500,1.09500,1.09410,1.09430,1.5 +02.01.2024 08:15:00.000,1.09430,1.09460,1.09420,1.09450,7 +06.01.2024 12:00:00.000,1.09450,1.09450,1.09450,1.09450,0 diff --git a/tests/Anubis.Tests/ResearchBarsTests.cs b/tests/Anubis.Tests/ResearchBarsTests.cs new file mode 100644 index 0000000..8b2f01f --- /dev/null +++ b/tests/Anubis.Tests/ResearchBarsTests.cs @@ -0,0 +1,622 @@ +using System.IO.Compression; +using Anubis.Baskets; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Server; + +namespace Anubis.Tests; + +/// +/// Bars shorter than a day for research, the 28 currency pairs from the ECB rates and the import of one-minute FX files +/// (Phase 12, issue #120). +/// +[TestClass] +public sealed class ResearchBarsTests +{ + private static readonly DateTimeOffset _jan2 = new(2024, 1, 2, 0, 0, 0, TimeSpan.Zero); + + private static ResearchBar Minute(DateTimeOffset at, decimal open, decimal high, decimal low, decimal close, decimal volume = 1m) => + new(at, open, high, low, close, volume); + + // ---- Timeframes ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void TimeframesKnowTheirLengthAndWhichAreIntraday() + { + CollectionAssert.AreEqual(new[] { "1m", "15m", "30m", "1h", "4h", "8h", "1d" }, Timeframes.All.ToArray()); + Assert.AreEqual(TimeSpan.FromMinutes(1), Timeframes.Length(Timeframes.Minute)); + Assert.AreEqual(TimeSpan.FromMinutes(15), Timeframes.Length(Timeframes.Minutes15)); + Assert.AreEqual(TimeSpan.FromMinutes(30), Timeframes.Length(Timeframes.Minutes30)); + Assert.AreEqual(TimeSpan.FromHours(1), Timeframes.Length(Timeframes.Hour)); + Assert.AreEqual(TimeSpan.FromHours(4), Timeframes.Length(Timeframes.Hours4)); + Assert.AreEqual(TimeSpan.FromHours(8), Timeframes.Length(Timeframes.Hours8)); + Assert.AreEqual(TimeSpan.FromDays(1), Timeframes.Length(Timeframes.Day)); + Assert.IsTrue(Timeframes.IsIntraday("15m")); + Assert.IsTrue(Timeframes.IsIntraday("1m")); + Assert.IsFalse(Timeframes.IsIntraday("1d")); + Assert.IsFalse(Timeframes.IsIntraday("1w"), "an unknown timeframe is not intraday"); + Assert.ThrowsExactly(() => Timeframes.Length("1w")); + } + + // ---- Aggregator ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void AggregatorNeverFillsAGapAndEmitsPartialBuckets() + { + var minutes = new[] + { + Minute(_jan2.AddMinutes(31), 10m, 12m, 9m, 11m, 2m), + Minute(_jan2, 5m, 6m, 4m, 5.5m, 1m), + }; + + var bars = BarAggregator.Aggregate(minutes, Timeframes.Minutes15); + + Assert.AreEqual(2, bars.Count, "the empty bucket of 00:15 gives no bar"); + Assert.AreEqual(new ResearchBar(_jan2, 5m, 6m, 4m, 5.5m, 1m), bars[0], "a bucket with one minute out of fifteen is still a bar"); + Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(30), 10m, 12m, 9m, 11m, 2m), bars[1]); + Assert.AreEqual(0, BarAggregator.Aggregate([], Timeframes.Hour).Count); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AggregatorLeavesOutTheBucketThatHasNotClosed() + { + var minutes = Enumerable.Range(0, 21).Select(i => Minute(_jan2.AddMinutes(i), 1m + i, 2m + i, 0.5m + i, 1.5m + i)).ToList(); + + var early = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(25)); + Assert.AreEqual(1, early.Count, "00:15–00:30 ends after 00:25: not emitted"); + Assert.AreEqual(_jan2, early[0].OpensAt); + + var closed = BarAggregator.Aggregate(minutes, Timeframes.Minutes15, completeBefore: _jan2.AddMinutes(30)); + Assert.AreEqual(2, closed.Count, "a bucket that ends exactly at the cut is complete"); + Assert.AreEqual(new ResearchBar(_jan2.AddMinutes(15), 16m, 22m, 15.5m, 21.5m, 6m), closed[1]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void FourHourBucketsOfBinanceMinutesStartOnUtcMultiples() + { + // Binance archives: 4h klines open at 00, 04, 08 … UTC; minutes carry quote volume and trades. + var start = new DateTimeOffset(2024, 3, 10, 3, 58, 0, TimeSpan.Zero); + var minutes = Enumerable.Range(0, 4) + .Select(i => Minute(start.AddMinutes(i), 100m + i, 101m + i, 99m + i, 100.5m + i, 0.25m) with { QuoteVolume = 10.1m, Trades = 3 + i }) + .ToList(); + + var bars = BarAggregator.Aggregate(minutes, Timeframes.Hours4); + + Assert.AreEqual(2, bars.Count); + Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 0, 0, 0, TimeSpan.Zero), bars[0].OpensAt); + Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 4, 0, 0, TimeSpan.Zero), bars[1].OpensAt); + Assert.AreEqual(new ResearchBar(bars[0].OpensAt, 100m, 102m, 99m, 101.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 7 }, bars[0]); + Assert.AreEqual(new ResearchBar(bars[1].OpensAt, 102m, 104m, 101m, 103.5m, 0.5m) { QuoteVolume = 20.2m, Trades = 11 }, bars[1]); + + // One minute without quote volume or trades: the sums would be wrong, so they stay empty. + minutes[3] = minutes[3] with { QuoteVolume = null, Trades = null }; + var partial = BarAggregator.Aggregate(minutes, Timeframes.Hours4); + Assert.AreEqual(20.2m, partial[0].QuoteVolume); + Assert.IsNull(partial[1].QuoteVolume); + Assert.IsNull(partial[1].Trades); + + Assert.AreEqual(new DateTimeOffset(2024, 3, 10, 8, 0, 0, TimeSpan.Zero), + BarAggregator.BucketOf(new DateTimeOffset(2024, 3, 10, 12, 59, 0, TimeSpan.FromHours(1)), TimeSpan.FromHours(4)), "UTC, whatever the offset given"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AggregatorKeepsDecimalsExactAndRefusesUnalignedOrDuplicateMinutes() + { + var minutes = new[] + { + Minute(_jan2, 1.123456789012345678m, 1.2m, 1.1m, 1.15m, 0.1m), + Minute(_jan2.AddMinutes(1), 1.15m, 1.3m, 1.000000000000000001m, 1.25m, 0.2m), + }; + var bar = BarAggregator.Aggregate(minutes, Timeframes.Minutes30).Single(); + Assert.AreEqual(0.3m, bar.Volume, "0.1 + 0.2 is 0.3 in decimal"); + Assert.AreEqual(1.123456789012345678m, bar.Open); + Assert.AreEqual(1.000000000000000001m, bar.Low); + + Assert.ThrowsExactly(() => BarAggregator.Aggregate([Minute(_jan2.AddSeconds(30), 1m, 1m, 1m, 1m)], Timeframes.Minutes15)); + Assert.ThrowsExactly(() => BarAggregator.Aggregate([minutes[0], minutes[0]], Timeframes.Minutes15)); + Assert.ThrowsExactly(() => BarAggregator.Aggregate(minutes, Timeframes.Day + "x")); + } + + // ---- Calendars ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFxWeekOpensSundayAndClosesFridayAtFivePmNewYorkAcrossDaylightSaving() + { + var fx = BarCalendars.Fx; + var quarter = TimeSpan.FromMinutes(15); + static DateTimeOffset Utc(int month, int day, int hour, int minute) => new(2024, month, day, hour, minute, 0, TimeSpan.Zero); + + // Friday 8 March 2024 closes at 17:00 EST (22:00 UTC); the US clocks move on Sunday 10 March, so it reopens + // at 17:00 EDT (21:00 UTC). Europe moves on 31 March: the two are different weeks. + Assert.IsTrue(fx.IsOpen(Utc(3, 8, 21, 45), quarter)); + Assert.IsFalse(fx.IsOpen(Utc(3, 8, 22, 0), quarter)); + Assert.IsFalse(fx.IsOpen(Utc(3, 9, 12, 0), quarter), "Saturday"); + Assert.IsFalse(fx.IsOpen(Utc(3, 10, 20, 45), quarter)); + Assert.IsTrue(fx.IsOpen(Utc(3, 10, 21, 0), quarter)); + + // November: Friday 1 closes at 17:00 EDT (21:00 UTC), Sunday 3 reopens at 17:00 EST (22:00 UTC). + Assert.IsTrue(fx.IsOpen(Utc(11, 1, 20, 45), quarter)); + Assert.IsFalse(fx.IsOpen(Utc(11, 1, 21, 0), quarter)); + Assert.IsFalse(fx.IsOpen(Utc(11, 3, 21, 45), quarter)); + Assert.IsTrue(fx.IsOpen(Utc(11, 3, 22, 0), quarter)); + + var march = fx.Moments(Utc(3, 8, 0, 0), Utc(3, 11, 0, 0), quarter).ToList(); + Assert.AreEqual(Utc(3, 8, 21, 45), march.Last(t => t < Utc(3, 9, 0, 0))); + Assert.AreEqual(Utc(3, 10, 21, 0), march.First(t => t > Utc(3, 9, 0, 0))); + Assert.AreEqual(88 + 12, march.Count, "Friday until 22:00 UTC, then Sunday from 21:00 UTC"); + + // A bar that straddles the opening is open: it holds traded minutes. + Assert.IsTrue(fx.IsOpen(Utc(3, 10, 20, 0), TimeSpan.FromHours(4))); + Assert.IsFalse(fx.IsOpen(Utc(3, 10, 16, 0), TimeSpan.FromHours(4))); + + // Daily bars: Monday to Friday, the days the ECB publishes. + Assert.IsFalse(fx.IsOpen(Utc(3, 10, 0, 0), TimeSpan.FromDays(1))); + Assert.IsTrue(fx.IsOpen(Utc(3, 11, 0, 0), TimeSpan.FromDays(1))); + Assert.IsTrue(BarCalendars.Always.IsOpen(Utc(3, 9, 12, 0), quarter)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CalendarsCountTheirPeriodsPerYearAndExchangesKeepOnlyTheirSessions() + { + Assert.AreEqual(35040, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromMinutes(15))); + Assert.AreEqual(365, BarCalendars.Always.PeriodsPerYear(TimeSpan.FromDays(1))); + Assert.AreEqual(24960, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromMinutes(15)), "52 weeks × 5 days × 96"); + Assert.AreEqual(260, BarCalendars.Fx.PeriodsPerYear(TimeSpan.FromDays(1))); + + var day = new DateOnly(2024, 7, 2); + var session = new MarketSession(day, Zones.At(day, new TimeOnly(9, 30), Zones.NewYork), Zones.At(day, new TimeOnly(16, 0), Zones.NewYork)); + var exchange = BarCalendars.Exchange([session]); + Assert.AreEqual("exchange", exchange.Name); + Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 15, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15))); + Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 13, 30, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "09:30 EDT"); + Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 20, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(15)), "16:00 EDT is the close"); + Assert.IsTrue(exchange.IsOpen(new DateTimeOffset(2024, 7, 2, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1))); + Assert.IsFalse(exchange.IsOpen(new DateTimeOffset(2024, 7, 3, 0, 0, 0, TimeSpan.Zero), TimeSpan.FromDays(1)), "no session that day"); + Assert.AreEqual(26, exchange.Moments(session.OpenUtc.AddHours(-2), session.CloseUtc.AddHours(2), TimeSpan.FromMinutes(15)).Count()); + Assert.AreEqual(252 * 26, exchange.PeriodsPerYear(TimeSpan.FromMinutes(15))); + Assert.AreEqual(252, exchange.PeriodsPerYear(TimeSpan.FromDays(1))); + } + + // ---- BarDataset ---- + + private static Dictionary> TwoSymbols() => new(StringComparer.Ordinal) + { + ["BBB"] = [Minute(_jan2, 1m, 2m, 0.5m, 1.5m), Minute(_jan2.AddMinutes(30), 3m, 4m, 2.5m, 3.5m), Minute(_jan2.AddMinutes(45), 5m, 6m, 4.5m, 5.5m)], + ["AAA"] = [Minute(_jan2, 10m, 20m, 5m, 15m), Minute(_jan2.AddMinutes(15), 11m, 21m, 6m, 16m), Minute(_jan2.AddMinutes(30), 12m, 22m, 7m, 17m)], + }; + + [TestMethod] + [TestCategory(Category.Unit)] + public void BarDatasetSharesOneClockAndLeavesMissingBarsEmpty() + { + var bars = TwoSymbols(); + bars["AAA"] = [.. bars["AAA"], Minute(_jan2.AddDays(4).AddHours(12), 1m, 1m, 1m, 1m)]; // Saturday: outside the FX week. + var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), bars); + + CollectionAssert.AreEqual(new[] { "AAA", "BBB" }, data.Symbols.ToArray(), "ordinal order"); + CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15), _jan2.AddMinutes(30), _jan2.AddMinutes(45) }, data.Clock.ToArray()); + Assert.AreEqual(TimeSpan.FromMinutes(15), data.Length); + Assert.AreEqual(24960, data.PeriodsPerYear); + Assert.IsTrue(data.Has("BBB", 0)); + Assert.IsFalse(data.Has("BBB", 1)); + Assert.IsTrue(double.IsNaN(data.Bars("BBB").Close[1]), "a missing bar is NaN, never the previous close"); + Assert.IsTrue(double.IsNaN(data.Bars("BBB").Open[1])); + Assert.AreEqual(3.5, data.Bars("BBB").Close[2]); + Assert.IsTrue(double.IsNaN(data.Bars("AAA").Close[3])); + Assert.AreEqual(16.0, data.Bars("AAA").Close[data.IndexOf(_jan2.AddMinutes(15))]); + Assert.AreEqual(-1, data.IndexOf(_jan2.AddMinutes(7))); + Assert.AreEqual(0, data.Dropped, "the Saturday bar is outside [from, to): not counted"); + Assert.IsNull(data.Ask("AAA")); + + var week = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddDays(7), bars); + Assert.AreEqual(1, week.Dropped, "a bar on Saturday is outside the FX week"); + Assert.AreEqual(5 * 96, week.Clock.Count, "Tuesday 00:00 UTC to the next Tuesday, without Friday 22:00 to Sunday 22:00 UTC"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void BarDatasetThroughNeverShowsABarThatHasNotClosed() + { + var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols()); + + var cut = data.Through(_jan2.AddMinutes(37)); + CollectionAssert.AreEqual(new[] { _jan2, _jan2.AddMinutes(15) }, cut.Clock.ToArray(), "the bar of 00:30 closes at 00:45"); + Assert.AreEqual(2, cut.Bars("AAA").Close.Count); + Assert.AreEqual(_jan2.AddMinutes(30), cut.ClosesAt(1)); + Assert.AreEqual(3, data.Through(_jan2.AddMinutes(45)).Clock.Count, "a bar that closes exactly at the cut is known"); + Assert.AreEqual(0, data.Through(_jan2.AddMinutes(14)).Clock.Count); + + var middle = data.Between(_jan2.AddMinutes(15), _jan2.AddMinutes(45)); + CollectionAssert.AreEqual(new[] { _jan2.AddMinutes(15), _jan2.AddMinutes(30) }, middle.Clock.ToArray()); + Assert.AreEqual(17.0, middle.Bars("AAA").Close[1]); + Assert.IsTrue(double.IsNaN(middle.Bars("BBB").Close[0])); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void BarDatasetFingerprintChangesWhenOnePriceChanges() + { + var data = BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols()); + Assert.AreEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint()); + Assert.AreEqual(64, data.Fingerprint().Length); + + var changed = TwoSymbols(); + changed["BBB"] = [changed["BBB"][0], changed["BBB"][1] with { Close = 3.5000001m }, changed["BBB"][2]]; + Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddHours(1), changed).Fingerprint()); + Assert.AreNotEqual(data.Fingerprint(), BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, _jan2, _jan2.AddHours(1), TwoSymbols()).Fingerprint(), "the calendar is part of the data"); + Assert.AreNotEqual(data.Fingerprint(), data.Through(_jan2.AddMinutes(45)).Fingerprint()); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task BarDatasetReadsBidAndAskSeriesFromTheResearchStore() + { + var folder = TempFolder.Create("bardataset"); + try + { + var store = new ResearchStore(folder); + await store.WriteAsync("dukascopy", "EURUSD-BID", Timeframes.Minutes15, [Minute(_jan2, 1.1m, 1.2m, 1.0m, 1.15m)], CancellationToken.None).ConfigureAwait(false); + await store.WriteAsync("dukascopy", "EURUSD-ASK", Timeframes.Minutes15, [Minute(_jan2, 1.1001m, 1.2001m, 1.0001m, 1.1501m)], CancellationToken.None).ConfigureAwait(false); + await store.WriteAsync("dukascopy", "USDJPY-BID", Timeframes.Minutes15, [Minute(_jan2.AddMinutes(15), 150m, 151m, 149m, 150.5m)], CancellationToken.None).ConfigureAwait(false); + + var data = await BarDataset.LoadQuotesAsync(store, "dukascopy", ["USDJPY", "EURUSD"], Timeframes.Minutes15, _jan2, _jan2.AddMinutes(30), CancellationToken.None) + .ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { "EURUSD", "USDJPY" }, data.Symbols.ToArray()); + Assert.AreEqual("24x5", data.Calendar.Name); + Assert.AreEqual(1.15, data.Bars("EURUSD").Close[0]); + Assert.AreEqual(1.1501, data.Ask("EURUSD")!.Close[0]); + Assert.IsNull(data.Ask("USDJPY"), "no ask file for the pair: no ask columns"); + Assert.AreEqual(150.5, data.Bars("USDJPY").Close[1]); + + var plain = await BarDataset.LoadAsync(store, "dukascopy", ["EURUSD-BID"], Timeframes.Minutes15, BarCalendars.Always, _jan2, _jan2.AddMinutes(30), CancellationToken.None) + .ConfigureAwait(false); + Assert.AreEqual(1.15, plain.Bars("EURUSD-BID").Close[0]); + Assert.IsTrue(double.IsNaN(plain.Bars("EURUSD-BID").Close[1])); + } + finally + { + TempFolder.Delete(folder); + } + } + + // ---- ECB crosses ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheTwentyEightPairsComeFromTheSevenEcbRates() + { + CollectionAssert.AreEquivalent(new[] { "GBP", "AUD", "NZD", "USD", "CAD", "CHF", "JPY" }, EcbCrosses.Rates.ToArray()); + var rates = Ecb.ParseHistoryCsv(Fixture.Text("free/ecb-hist.csv"), EcbCrosses.Rates); + var crosses = EcbCrosses.Build(rates); + + CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), crosses.Keys.ToArray(), "the pairs and their order come from the shared list"); + Assert.AreEqual(56, crosses.Values.Sum(b => b.Count), "28 pairs × 2 days"); + + var day = new DateTimeOffset(2026, 11, 9, 0, 0, 0, TimeSpan.Zero); + decimal On(string pair, DateTimeOffset at) => crosses[pair].Single(b => b.OpensAt == at).Close; + var usdjpy = crosses["USDJPY"].Single(b => b.OpensAt == day); + Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy.Close); + Assert.AreEqual(new ResearchBar(day, usdjpy.Close, usdjpy.Close, usdjpy.Close, usdjpy.Close, 0m), usdjpy, "O = H = L = C at 00:00 UTC, volume 0"); + Assert.AreEqual(176.79m, On("EURJPY", day), "a EUR pair is the rate itself"); + Assert.AreEqual(0.8343m, On("EURGBP", day)); + var expected = new Dictionary + { + ["USDJPY"] = 157.94693112m, + ["GBPUSD"] = 1.34160374m, + ["GBPJPY"] = 211.90219346m, + ["AUDUSD"] = 0.68939394m, + ["AUDCAD"] = 0.97222222m, + ["AUDNZD"] = 1.22819660m, + ["NZDUSD"] = 0.56130585m, + ["USDCAD"] = 1.41025641m, + ["USDCHF"] = 0.81872599m, + ["CADCHF"] = 0.58055116m, + ["CADJPY"] = 111.99873297m, + ["CHFJPY"] = 192.91793976m, + }; + foreach (var (pair, value) in expected) + { + Assert.AreEqual(value, Math.Round(On(pair, day), 8), pair); + } + + var friday = day.AddDays(-3); + Assert.AreEqual(158.32512315m, Math.Round(On("USDJPY", friday), 8)); + Assert.AreEqual(1.33848828m, Math.Round(On("GBPUSD", friday), 8)); + + // A day without the franc: only the seven pairs with CHF lose that day. + var withoutFranc = rates.Where(r => !(r.Quote == "CHF" && r.Date == new DateOnly(2026, 11, 6))).ToList(); + var partial = EcbCrosses.Build(withoutFranc); + Assert.AreEqual(49, partial.Values.Sum(b => b.Count)); + foreach (var pair in FxPairs.All) + { + Assert.AreEqual(pair.Base == "CHF" || pair.Quote == "CHF" ? 1 : 2, partial[pair.Name].Count, pair.Name); + } + } + + private static byte[] EcbZip() + { + using var zip = new MemoryStream(); + using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) + using (var writer = new StreamWriter(archive.CreateEntry("eurofxref-hist.csv").Open())) + { + writer.Write(Fixture.Text("free/ecb-hist.csv")); + } + + return zip.ToArray(); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DataEcbWritesTheTwentyEightPairsAndOfflineReusesTheCachedHistory() + { + var data = TempFolder.Create("data-ecb"); + try + { + var env = ServerHarness.DockerSqlite(); + var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip()); + using var output = new StringWriter(); + Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], output, env, http).ConfigureAwait(false), output.ToString()); + Assert.AreEqual(1, http.Requests.Count); + StringAssert.Contains(output.ToString(), "Coppie di valute dai cambi BCE: 28 coppie, 2 giorni, dal 2026-11-06 al 2026-11-09."); + + var research = Path.Combine(data, "research"); + Assert.IsTrue(File.Exists(Path.Combine(research, Ecb.HistoryFile)), "the same cached zip as backtest base"); + var store = new ResearchStore(research); + var series = store.Series(); + Assert.AreEqual(28, series.Count); + Assert.IsTrue(series.All(s => s.Venue == "ecb" && s.Timeframe == Timeframes.Day), string.Join(", ", series)); + CollectionAssert.AreEquivalent(FxPairs.All.Select(p => p.Name).ToArray(), series.Select(s => s.Symbol).ToArray()); + var usdjpy = await store.ReadAsync("ecb", "USDJPY", Timeframes.Day, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false); + Assert.AreEqual(2, usdjpy.Count); + Assert.AreEqual(Math.Round(176.79m / 1.1193m, 10), usdjpy[1].Close, "the file keeps every decimal"); + + var offline = new FakeHttp(); + using var again = new StringWriter(); + Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--offline", "--platform", "docker", "--data-dir", data], again, env, offline).ConfigureAwait(false), again.ToString()); + Assert.AreEqual(0, offline.Requests.Count, "offline with the cached zip: no request"); + StringAssert.Contains(again.ToString(), "28 coppie"); + } + finally + { + TempFolder.Delete(data); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task BacktestBaseStillPrintsTheSameEcbLineFromTheSharedLoader() + { + var research = TempFolder.Create("ecb-loader"); + try + { + var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 8, 0, 0, TimeSpan.Zero)); + var http = new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip()); + using var output = new StringWriter(); + var rates = await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, output).ConfigureAwait(false); + Assert.AreEqual("Cambi BCE EUR/USD: 2 giorni, dal 2026-11-06 al 2026-11-09." + Environment.NewLine, output.ToString()); + Assert.AreEqual(2, rates.Count); + Assert.IsTrue(rates.All(r => r.Quote == "USD"), "only the dollar, as before"); + Assert.AreEqual(1, http.Requests.Count, "offline but without the cached zip: downloaded once"); + Assert.AreEqual(Path.Combine(research, "ecb-eurofxref-hist.zip"), Ecb.HistoryPath(research)); + + await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: true, TextWriter.Null).ConfigureAwait(false); + Assert.AreEqual(1, http.Requests.Count, "offline with the cached zip: no request"); + await BacktestCommand.RatesAsync(new ApiHttp(http.Client(), clock, "ecb"), research, offline: false, TextWriter.Null).ConfigureAwait(false); + Assert.AreEqual(2, http.Requests.Count, "online: downloaded again"); + + var missing = new FakeHttp().On("eurofxref-hist.zip", "", System.Net.HttpStatusCode.NotFound); + var error = await Assert.ThrowsExactlyAsync(() => + Ecb.LoadHistoryAsync(new ApiHttp(missing.Client(), clock, "ecb"), Path.Combine(research, "empty"), offline: true, ["USD"], CancellationToken.None)).ConfigureAwait(false); + Assert.AreEqual("BCE: lo storico dei cambi non è disponibile.", error.Message); + } + finally + { + TempFolder.Delete(research); + } + } + + // ---- FX minute files ---- + + private const string HistDataFile = "fx/DAT_ASCII_EURUSD_M1_2024.csv"; + private const string DukascopyBid = "fx/EURUSD_Candlestick_1_M_BID_02.01.2024-06.01.2024.csv"; + private const string DukascopyAsk = "fx/EURUSD_Candlestick_1_M_ASK_02.01.2024-06.01.2024.csv"; + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task FifteenMinuteBarsFromMinutesMatchTheHandComputedOnesInBothFormats() + { + // Constructed samples (no real file yet): the same bid prices in both formats, HistData at fixed UTC−5. + var folder = TempFolder.Create("fx-15m"); + try + { + var store = new ResearchStore(folder); + var importer = new FxMinuteImporter(store); + var eight = new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero); + async Task> Read(string venue, string series, string timeframe) => + await store.ReadAsync(venue, series, timeframe, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false); + + var histdata = await importer.ImportAsync(Fixture.Path(HistDataFile), null, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(2, histdata.Count); + Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "1m", 5, eight, eight.AddMinutes(15), histdata[0].Notes), histdata[0]); + Assert.AreEqual(new ImportResult("histdata", "EURUSD-BID", "15m", 2, eight, eight.AddMinutes(15), histdata[1].Notes), histdata[1]); + CollectionAssert.AreEqual(new[] + { + new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 0m), + new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 0m), + }, await Read("histdata", "EURUSD-BID", "15m").ConfigureAwait(false)); + Assert.AreEqual(eight, (await Read("histdata", "EURUSD-BID", "1m").ConfigureAwait(false))[0].OpensAt, "03:00 at UTC−5 is 08:00 UTC"); + Assert.IsTrue(histdata[0].Notes.Any(n => n.StartsWith(IssueKinds.Gap, StringComparison.Ordinal)), "the missing minutes are reported against the FX week"); + + var bid = await importer.ImportAsync(Fixture.Path(DukascopyBid), null, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("dukascopy", bid[0].Venue); + Assert.AreEqual("EURUSD-BID", bid[0].Symbol); + Assert.AreEqual(5, bid[0].Bars, "the flat Saturday bar is left out"); + Assert.IsTrue(bid[0].Notes.Any(n => n.Contains("1 barre fuori dall'orario del mercato", StringComparison.Ordinal)), string.Join(" | ", bid[0].Notes)); + CollectionAssert.AreEqual(new[] + { + new ResearchBar(eight, 1.0945m, 1.0953m, 1.0941m, 1.0943m, 35.25m), + new ResearchBar(eight.AddMinutes(15), 1.0943m, 1.0946m, 1.0942m, 1.0945m, 7m), + }, await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false)); + + var ask = await importer.ImportAsync(Fixture.Path(DukascopyAsk), null, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual("EURUSD-ASK", ask[1].Symbol); + CollectionAssert.AreEqual(new[] + { + new ResearchBar(eight, 1.09462m, 1.09542m, 1.09422m, 1.09442m, 35.25m), + new ResearchBar(eight.AddMinutes(15), 1.09442m, 1.09472m, 1.09432m, 1.09462m, 7m), + }, await Read("dukascopy", "EURUSD-ASK", "15m").ConfigureAwait(false)); + + // The same minutes through the pure aggregator give the same bars. + var minutes = await Read("dukascopy", "EURUSD-BID", "1m").ConfigureAwait(false); + CollectionAssert.AreEqual(BarAggregator.Aggregate(minutes, Timeframes.Minutes15).ToList(), await Read("dukascopy", "EURUSD-BID", "15m").ConfigureAwait(false)); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DataFxWritesMinuteAndFifteenMinuteSeriesForBothFormats() + { + var data = TempFolder.Create("data-fx"); + try + { + var env = ServerHarness.DockerSqlite(); + using var output = new StringWriter(); + foreach (var file in new[] { HistDataFile, DukascopyBid, DukascopyAsk }) + { + Assert.AreEqual(0, await DataCommand.RunAsync(["fx", Fixture.Path(file), "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString()); + } + + var text = output.ToString(); + StringAssert.Contains(text, "histdata EURUSD-BID 1m: 5 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC)."); + StringAssert.Contains(text, "histdata EURUSD-BID 15m: 2 barre, dal 2024-01-02 08:00 al 2024-01-02 08:15 (UTC)."); + StringAssert.Contains(text, "dukascopy EURUSD-ASK 15m: 2 barre"); + var series = new ResearchStore(Path.Combine(data, "research")).Series(); + CollectionAssert.AreEquivalent(new[] + { + ("dukascopy", "EURUSD-ASK", "15m"), ("dukascopy", "EURUSD-ASK", "1m"), ("dukascopy", "EURUSD-BID", "15m"), ("dukascopy", "EURUSD-BID", "1m"), + ("histdata", "EURUSD-BID", "15m"), ("histdata", "EURUSD-BID", "1m"), + }, series.ToArray()); + + // A HistData file renamed: the pair comes from --symbol. + var renamed = Path.Combine(data, "import", "minuti.csv"); + File.Copy(Fixture.Path(HistDataFile), renamed); + using var named = new StringWriter(); + Assert.AreEqual(0, await DataCommand.RunAsync(["fx", renamed, "--symbol", "gbpusd", "--platform", "docker", "--data-dir", data], named, env).ConfigureAwait(false), named.ToString()); + StringAssert.Contains(named.ToString(), "histdata GBPUSD-BID 15m: 2 barre"); + using var nameless = new StringWriter(); + Assert.AreEqual(1, await DataCommand.RunAsync(["fx", renamed, "--platform", "docker", "--data-dir", data], nameless, env).ConfigureAwait(false)); + StringAssert.Contains(nameless.ToString(), "--symbol"); + } + finally + { + TempFolder.Delete(data); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DataFxRefusesAnUnknownFormatInItalian() + { + var data = TempFolder.Create("data-fx-unknown"); + try + { + var env = ServerHarness.DockerSqlite(); + var metatrader = Path.Combine(data, "DAT_MT_EURUSD_M1_2024.csv"); + await File.WriteAllTextAsync(metatrader, "2024.01.01,17:00,1.104270,1.104290,1.104270,1.104290,0\n").ConfigureAwait(false); + var local = Path.Combine(data, "EURUSD_Candlestick_1_M_BID_01.01.2024-31.12.2024.csv"); + await File.WriteAllTextAsync(local, "Local time,Open,High,Low,Close,Volume\n02.01.2024 09:00:00.000 GMT+0100,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false); + var sideless = Path.Combine(data, "EURUSD_Candlestick_1_M_01.01.2024-31.12.2024.csv"); + await File.WriteAllTextAsync(sideless, "Gmt time,Open,High,Low,Close,Volume\n02.01.2024 08:00:00.000,1.1,1.1,1.1,1.1,1\n").ConfigureAwait(false); + + foreach (var (file, words) in new[] + { + (metatrader, "Formato non riconosciuto"), (local, "ora locale"), (sideless, "_BID_"), + }) + { + using var output = new StringWriter(); + Assert.AreEqual(1, await DataCommand.RunAsync(["fx", file, "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString()); + StringAssert.StartsWith(output.ToString(), "Non riuscito: "); + StringAssert.Contains(output.ToString(), words); + } + + Assert.AreEqual(0, new ResearchStore(Path.Combine(data, "research")).Series().Count, "nothing written"); + } + finally + { + TempFolder.Delete(data); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task DataUsageListsTheNewCommandsAndTimeframes() + { + using var output = new StringWriter(); + Assert.AreEqual(2, await DataCommand.RunAsync(["nothing"], output, ServerHarness.DockerSqlite()).ConfigureAwait(false)); + var usage = output.ToString(); + StringAssert.Contains(usage, "<1d|1m|15m|30m|1h|4h|8h>"); + StringAssert.Contains(usage, "anubis data ecb [--offline]"); + StringAssert.Contains(usage, "anubis data fx [--symbol EURUSD]"); + } + + // ---- CSV importer ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void CsvParseIsPureAndReadsAFixedOffsetAllYear() + { + var mapping = new CsvMapping { Delimiter = ";", HasHeader = false, TimeFormat = "yyyyMMdd HHmmss", TimeZone = "UTC-05:00" }; + var parsed = CsvImporter.Parse(["20240102 030000;1;2;0.5;1.5;0", "", "20240702 030000;1;2;0.5;1.5;0", "20240703 0300;1;2;0.5;1.5;0"], mapping); + + Assert.AreEqual(4, parsed.Lines); + Assert.AreEqual(1, parsed.Errors); + Assert.AreEqual(new DateTimeOffset(2024, 1, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[0].OpensAt); + Assert.AreEqual(new DateTimeOffset(2024, 7, 2, 8, 0, 0, TimeSpan.Zero), parsed.Bars[1].OpensAt, "no daylight saving: still 08:00 UTC in July"); + StringAssert.StartsWith(parsed.Notes[0], "riga 4: "); + Assert.AreEqual("1 righe non lette su 4", parsed.Notes[^1]); + Assert.AreEqual(TimeSpan.FromHours(5.5), CsvImporter.ZoneOf("UTC+05:30").BaseUtcOffset); + Assert.AreEqual(TimeSpan.Zero, CsvImporter.ZoneOf("UTC").BaseUtcOffset); + Assert.ThrowsExactly(() => CsvImporter.ZoneOf("Nowhere/Atlantis")); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task CsvImporterChecksIntradayBarsAtTheirOwnLength() + { + var folder = TempFolder.Create("csv-15m"); + try + { + var csv = Path.Combine(folder, "btcusdt-15m.csv"); + await File.WriteAllTextAsync(csv, + "time,open,high,low,close,volume\n" + + "2024-01-02 00:00:00,100,101,99,100.5,1\n" + + "2024-01-02 00:15:00,100.5,102,100,101,1\n" + + "2024-01-02 00:45:00,101,103,100,102,1\n").ConfigureAwait(false); + var mapping = new CsvMapping { Timeframe = Timeframes.Minutes15, TimeFormat = "yyyy-MM-dd HH:mm:ss" }; + var store = new ResearchStore(Path.Combine(folder, "research")); + + var result = await new CsvImporter(store).ImportAsync(csv, mapping, CancellationToken.None).ConfigureAwait(false); + + Assert.AreEqual(3, result.Bars); + Assert.IsFalse(result.Notes.Any(n => n.StartsWith(IssueKinds.Duplicate, StringComparison.Ordinal)), "three bars of one day are not duplicates: " + string.Join(" | ", result.Notes)); + Assert.AreEqual("gap 2024-01-02 00:30: Manca una barra da 15m", result.Notes.Single()); + Assert.AreEqual(3, (await store.ReadAsync("import", "BTCUSDT", "15m", DateTimeOffset.MinValue, DateTimeOffset.MaxValue).ToListAsync().ConfigureAwait(false)).Count); + } + finally + { + TempFolder.Delete(folder); + } + } +} -- 2.54.1 From 8d02d028769b04a86945e03fea34f7ee7c0bca8c Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 10:51:03 +0100 Subject: [PATCH 6/6] Fix what the independent review of Phase 12 found, and close the phase - A flat window has no z-score even when its mean misses the common value by one rounding step (it gave a meaningless z of about 0.995). - A broken ECB history (a maintenance page, a cut download, a damaged cached copy) is refused in Italian instead of crashing `data ecb`, and a download is checked and moved into place in one step, so it never replaces the good copy. - A fixed time zone with 60 or more minutes is refused instead of being read as the next hour. - `data fx` says why when every bar of the file falls outside the market week. ADR 0028 records the choices of the phase; ROADMAP and STATE mark it done. refs #118, refs #119, refs #120, refs #121 Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 34 ++++++++----- docs/STATE.md | 13 +++-- docs/adr/0028-scelte-fase-12.md | 56 +++++++++++++++++++++ src/Anubis.Server/DataCommand.cs | 3 +- src/Anubis/Baskets/BasketIndex.cs | 20 ++++++++ src/Anubis/Data/FreeSources.cs | 21 +++++++- src/Anubis/Data/FxMinuteFiles.cs | 5 +- src/Anubis/Data/Importers.cs | 8 ++- tests/Anubis.Tests/BasketSignalTests.cs | 3 ++ tests/Anubis.Tests/ResearchBarsTests.cs | 67 +++++++++++++++++++++++++ 10 files changed, 209 insertions(+), 21 deletions(-) create mode 100644 docs/adr/0028-scelte-fase-12.md diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6a5905d..00aaa5d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -20,8 +20,8 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest | 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Completata | | 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Completata (pubblicazione e prova su Unraid in attesa dell'utente) | | 10 | [Nuova rotta: solo Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/37) | Completata (prova di durata dal container in attesa dell'utente) | -| 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Completata (unione e tag dopo il sì dell'utente; misura sulle azioni in attesa delle chiavi Alpaca e Finnhub) | -| 12 | [Dati e matematica dei panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/80) | Da fare | +| 11 | [Decisioni solo matematiche](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/79) | Completata (misura sulle azioni in attesa delle chiavi Alpaca e Finnhub) | +| 12 | [Dati e matematica dei panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/80) | Completata (unione e tag dopo il sì dell'utente; i formati dei file a un minuto delle valute da verificare sul primo file vero) | | 13 | [Campionato: unità di lavoro, piano e statistica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/81) | Da fare | | 14 | [Motore a panieri](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/82) | Da fare | | 15 | [Campionato: concorrenti e classifica](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/83) | Da fare | @@ -354,20 +354,28 @@ Si preparano i dati e i conti che servono alla logica del documento: barre più **Lavori** -- [ ] [#118](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/118) Giunto nel giudice delle prove, un lavoro a sé -- [ ] [#119](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/119) Matematica dei panieri, codice puro in `src/Anubis/Baskets/` -- [ ] [#120](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/120) Barre più corte di un giorno, per la ricerca -- [ ] [#121](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/121) Chiusura della fase, revisione indipendente e tag `fase-12` (dopo il sì dell'utente) +- [x] [#118](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/118) Giunto nel giudice delle prove, un lavoro a sé +- [x] [#119](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/119) Matematica dei panieri, codice puro in `src/Anubis/Baskets/` +- [x] [#120](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/120) Barre più corte di un giorno, per la ricerca +- [x] [#121](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/121) Chiusura della fase, revisione indipendente e tag `fase-12` (dopo il sì dell'utente) **Criteri di accettazione** -- [ ] Un rapporto d'oro scritto prima della modifica: `sma_cross` e `crypto_trend` danno lo stesso JSON, byte per byte, dopo l'introduzione del giunto (esclusi i secondi impiegati, con l'ora fissata dall'orologio di prova). -- [ ] Conteggi 56, 112 e 210 relazioni; l'appendice B riprodotta riga per riga; gli otto spread documentati classificati. -- [ ] Valore del pip su USDJPY, EURJPY, CHFJPY; giorno del server e pausa in quattro date, comprese le settimane in cui Stati Uniti ed Europa cambiano l'ora in giorni diversi. -- [ ] Tre acquisti AUDUSD a 0,69456, 0,69003 e 0,68739 con obiettivo 6,9 escono a 0,69089 ± 0,1 pip. -- [ ] Tabella 4.5 (1, 2, 3, 4, 5, 8 ordini → 10,00, 5,00, 3,33, 2,50, 2,00, 1,25); scala delle distanze con crescita 1,0 e 1,3 e `Rvol` 0,8, 1,5 e 4; nessuna aggiunta dopo l'ultimo livello; le otto escursioni della tabella 4.12. -- [ ] Le 28 coppie escono dai sette cambi BCE: su un giorno di prova USDJPY vale 176,79 diviso 1,1193. Le barre a 15 minuti costruite dai minuti coincidono con quelle calcolate a mano, nei due formati. -- [ ] Relazioni e segnali non guardano avanti. +- [x] Un rapporto d'oro scritto prima della modifica: `sma_cross` e `crypto_trend` danno lo stesso JSON, byte per byte, dopo l'introduzione del giunto (esclusi i secondi impiegati, con l'ora fissata dall'orologio di prova). +- [x] Conteggi 56, 112 e 210 relazioni; l'appendice B riprodotta riga per riga; gli otto spread documentati classificati. +- [x] Valore del pip su USDJPY, EURJPY, CHFJPY; giorno del server e pausa in quattro date, comprese le settimane in cui Stati Uniti ed Europa cambiano l'ora in giorni diversi. +- [x] Tre acquisti AUDUSD a 0,69456, 0,69003 e 0,68739 con obiettivo 6,9 escono a 0,69089 ± 0,1 pip. +- [x] Tabella 4.5 (1, 2, 3, 4, 5, 8 ordini → 10,00, 5,00, 3,33, 2,50, 2,00, 1,25); scala delle distanze con crescita 1,0 e 1,3 e `Rvol` 0,8, 1,5 e 4; nessuna aggiunta dopo l'ultimo livello; le otto escursioni della tabella 4.12. +- [x] Le 28 coppie escono dai sette cambi BCE: su un giorno di prova USDJPY vale 176,79 diviso 1,1193. Le barre a 15 minuti costruite dai minuti coincidono con quelle calcolate a mano, nei due formati. +- [x] Relazioni e segnali non guardano avanti. + +Prove: +- `TrialSeamTests`: tre rapporti d'oro scritti prima del giunto e confermati dalla CI su Linux su quel solo commit. +- `TrialEngineTests` (12 casi): un motore non giornaliero giudicato con i suoi numeri, l'ordine delle chiamate di oggi, la sezione dei panieri, le impronte dei piani delle sette famiglie, gli assi a scelta. +- `BasketRelationTests`, `ServerClockTests`, `BasketMathTests` e `BasketSignalTests` (94 casi). Tra questi una prova di proprietà su 200 serie: niente di ciò che si calcola alla barra t cambia se si aggiungono barre dopo. +- `ResearchBarsTests` (22 casi): le 28 coppie dai cambi BCE, `data ecb` e `data fx` dalla riga di comando, aggregazione, calendari, insieme di barre a colonne, storico della BCE mai sostituito da un file rotto. + +Scelte nell'ADR 0028. I due formati dei file a un minuto (Dukascopy e HistData) vengono da conoscenza generale e i campioni delle prove sono costruiti a mano: vanno verificati sul primo file vero dell'utente. ## Fase 13 — Campionato: unità di lavoro, piano e statistica diff --git a/docs/STATE.md b/docs/STATE.md index 67cf20c..b781fdb 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -1,10 +1,10 @@ # Stato del progetto -Aggiornato: 2026-12-03 +Aggiornato: 2026-12-04 ## Fase corrente -**Fase 11 — Decisioni solo matematiche: completata** sul branch `fase-11`, con la pull request aperta: unione in `main` e tag `fase-11` aspettano il sì dell'utente. Notizie, calendario e trimestrali non cambiano più nessuna decisione (interruttore «Notizie, calendario e trimestrali», predefinito «solo misurate»): ogni regola scrive in ombra che cosa avrebbe fatto. La Fase 10 è unita con il tag `fase-10`; resta in attesa dell'utente la prova di durata dal container (#55). Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. +**Fase 12 — Dati e matematica dei panieri: completata** sul branch `fase-12`, con la pull request aperta: unione in `main` e tag `fase-12` aspettano il sì dell'utente. Il giudice delle prove ha un giunto per un secondo motore, la matematica dei panieri del documento è scritta e provata numero per numero, le 28 coppie di valute escono dai cambi della BCE e i file a un minuto si importano. Nessuna strategia nuova gira: è tutto ricerca. La Fase 11 è unita con il tag `fase-11`. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. **Nuova rotta, decisa dall'utente il 2 dicembre 2026** e scritta negli ADR 0021–0026. Decisioni solo matematiche (ADR 0023, applicato dalla Fase 11 con l'ADR 0027): notizie, calendario e trimestrali si misurano in ombra. La logica di rientro tra strumenti del documento in `docs/ricerca/`, provata in un campionato delle strategie (ADR 0026). Leva, vendite allo scoperto e mediazioni solo su conti a margine che non possono essere reali, simulatore interno e Demo di eToro, dalla Fase 18 (ADR 0024). Le valute su eToro Demo (ADR 0025). Solo Docker (ADR 0022). Piano in `docs/piani/2026-12-02-nuova-rotta.md`: fasi dalla 10 alla 24, in `docs/ROADMAP.md`. Dove la specifica e un ADR dicono cose diverse vale l'ADR: la tabella «Da specifica ad ADR» dell'ADR 0021 dice quale. @@ -148,13 +148,19 @@ Aggiornato: 2026-12-03 - Schermate: Notizie come archivio con l'avviso fisso, «Cosa avrebbe fatto la regola»; Panoramica, Rischio, Strategie, Apprendimento, Impostazioni e Laboratorio con le frasi «solo registrato». Fotografie in `artifacts/screenshots/` (1440 px chiaro e scuro, 390 px). La modalità dimostrativa segue «misurate». - Revisione indipendente in due giri: 16 problemi confermati nel primo e corretti (tra cui la lettura dell'interruttore all'invio, il messaggio «anomalia rientrata» mentre il modello restava da parte, le trimestrali che coprivano le regole delle notizie nella pagina Notizie). +- **Fase 12 — Dati e matematica dei panieri** (#118–#120, ADR 0028, nessun pacchetto nuovo; solo ricerca): + - Giunto nel giudice delle prove (#118): `ITrialEngine` dà al giudice tutto ciò che prima prendeva dai dati giornalieri; `DailyTrialEngine` rifà il comportamento di prima. Tre rapporti d'oro (`sma_cross`, `crypto_trend`, una variante fuori griglia), scritti e confermati dalla CI su Linux prima del giunto, restano uguali byte per byte; le impronte dei piani delle sette famiglie non cambiano. `IResearchFamily` (famiglie di sola ricerca, senza strategia e quindi senza ordini), assi a scelta che l'altopiano non media mai, sezione facoltativa dei panieri nel rapporto. + - Matematica dei panieri (#119, `src/Anubis/Baskets/`): otto valute e 28 coppie in un solo elenco, elenco a 14 coppie, orologio del server (New York + 7), fine settimana, orario e pausa giornaliera; 378 relazioni (56 catene, 112 rapporti, 210 disgiunte), appendice B riga per riga, gli otto spread documentati; indici in pip e in punti base, z-score, `Rvol`, correlazione, β; somma dei pip, prezzo comune d'uscita, scala delle distanze, escursione dello stop, valore del pip, unità alzate al minimo della sede, esposizione, regola dei tre costi; stati, quattro stili, profili Fedele e Prudente. Ogni numero scritto nel documento ha la sua prova; una prova di proprietà controlla che niente guardi avanti. + - Barre più corte di un giorno (#120): durate da 15 e 30 minuti, 1, 4 e 8 ore; aggregazione esatta senza riempire buchi; calendari 24×7, 24×5 e di borsa; insieme di barre a colonne con orologio comune. `anubis data ecb` ricava le 28 coppie dai cambi BCE dal 1999 (USDJPY = 176,79 / 1,1193 sul giorno di prova); `anubis data fx` importa i file a un minuto di Dukascopy e HistData e costruisce le barre a 15 minuti. + - Revisione indipendente con verifica a contraddittorio: 5 problemi confermati e corretti (z-score su una finestra piatta, storico BCE rotto che faceva cadere il comando o sostituiva la copia buona, minuti oltre 59 in un fuso fisso, messaggio senza motivo per un file tutto nel fine settimana, una frase dell'ADR), 7 respinti. La correzione importante è stata provata rompendola apposta. + ## In corso Nulla. ## Prossimo passo -1. Il sì dell'utente per unire la pull request della Fase 11 e mettere il tag `fase-11`. Poi la **Fase 12 — Dati e matematica dei panieri**, in una nuova sessione, sul branch `fase-12` da `main`. Letture: la riga della Fase 12 nella tabella dell'ADR 0021 (punto 3) e la Fase 12 del piano. +1. Il sì dell'utente per unire la pull request della Fase 12 e mettere il tag `fase-12`. Poi la **Fase 13 — Campionato: unità di lavoro, piano e statistica**, in una nuova sessione, sul branch `fase-13` da `main`. Letture: la riga della Fase 13 nella tabella dell'ADR 0021 (punto 3) e la Fase 13 del piano. 2. L'utente decide se pubblicare l'immagine (prossimo tag `v*`) e prova il template su Unraid seguendo `docs/MANUALE.md`. 3. Il rapporto della prova di durata (#55): si raccoglie dal container sul server di casa (48 ore a `--memory=2g`), si analizza, si salva in `docs/diagnostica/` e si chiude #55. 4. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. @@ -168,6 +174,7 @@ Nulla. - **Incidenti critici**: il requisito di 12.3 conta solo l'arresto per perdita del 15%, la specifica chiede di più. - **Prova di durata (#55)** non chiusa: manca il rapporto, che ora si raccoglie dal container. - **La logica del documento della nuova rotta**, misurata dal documento stesso, è negativa o non si distingue dal caso. Il piano mette le prove davanti agli ordini, e l'esito più probabile è che resti una prova sul Demo, fuori dai totali. +- **I file a un minuto delle valute** (Dukascopy, HistData) si leggono secondo formati scritti da conoscenza generale, con campioni costruiti a mano: vanno verificati sul primo file vero. Senza quei file le valute si provano solo sui cambi giornalieri della BCE, che sono prezzi di riferimento e non prezzi a cui si negozia. - **Il modello** è appena migliore della frequenza di base e ha studiato solo `crypto_trend`. - **La misura in ombra delle regole esterne** parte ora: il primo giudizio non arriva prima di 6 mesi, e con le chiavi di oggi riguarda solo `crypto_trend` e le due regole sulle notizie. Con poche proposte d'ingresso è probabile che non arrivi a un giudizio. - **Dati**: gli universi azionari passati usano i flag di oggi; la storia crypto prima di novembre 2023 viene da Binance in USDT; gli archivi della SEC non sono mai stati letti dal vivo. diff --git a/docs/adr/0028-scelte-fase-12.md b/docs/adr/0028-scelte-fase-12.md new file mode 100644 index 0000000..84ec213 --- /dev/null +++ b/docs/adr/0028-scelte-fase-12.md @@ -0,0 +1,56 @@ +# 0028 — Scelte della Fase 12 (dati e matematica dei panieri) + +Data: 2026-12-04 · Stato: accettata · Applica gli ADR 0021, 0025 e 0026 per la parte di ricerca · Precisa SPEC 4.4, 6 e 12.1 · Nessun pacchetto nuovo + +## Contesto + +La Fase 12 prepara i dati e i conti che servono alla logica di rientro tra strumenti del documento di ricerca (`docs/ricerca/`), senza far girare nessuna strategia nuova. Il documento descrive le formule ma lascia aperti diversi dettagli: se una deviazione standard è campionaria, se una finestra comprende la barra corrente, se i limiti di un orario sono compresi. Dove c'era da scegliere si è presa la via più prudente e la si è scritta qui, prima che un risultato potesse suggerirla. + +## Decisione + +### Il giunto nel giudice delle prove (#118) + +1. **Prima il rapporto d'oro, poi il giunto.** Tre rapporti completi, scritti e messi nel repository prima di toccare il giudice (`tests/Anubis.Tests/Fixtures/golden/`): l'incrocio di medie con prove precedenti, il protocollo di `crypto_trend` e una variante giudicata fuori dalla griglia. Si confrontano byte per byte, con i secondi impiegati a zero e l'ora fissata dalla prova. La CI su Linux li ha confermati sul commit che conteneva solo loro, prima del giunto. +2. **`ITrialEngine`** (`Backtest/TrialEngines.cs`) dà al giudice tutto ciò che prima prendeva dai dati giornalieri: valuta, periodi per anno, sedute della finestra, impronta dei dati, strumenti, esecuzione di una variante (anche a costi doppi e tripli), termine di confronto, controllo contro lo sguardo in avanti, limiti dichiarati e i due valori attesi del protocollo crypto. `DailyTrialEngine` rifà esattamente il comportamento di prima: le opzioni si costruiscono una volta sola e si condividono, il termine di confronto resta «comprare e tenere» senza correttivi né rischio, le sedute vengono dal calendario dei dati. +3. Il vecchio `TrialRunner.Run` resta, e costruisce il motore giornaliero. Il nuovo accetta qualunque motore e una famiglia di sola ricerca. Le chiamate al motore avvengono nello stesso ordine di prima. +4. **`IResearchFamily`** è la base di `IStrategyFamily`: ha tutto tranne `Create`. Griglia, parametri e giudice accettano una famiglia di sola ricerca, che per costruzione non può creare una strategia e quindi non può mandare ordini (ADR 0026, punto 1). +5. **Assi a scelta.** `ParameterSpec.Choices` segna un asse i cui valori sono scelte e non numeri vicini. La regola dell'altopiano non li media mai: due varianti sono vicine su quell'asse solo se hanno lo stesso valore. Una griglia senza assi a scelta si comporta come prima; oggi nessuna famiglia ne ha. +6. **Sezione dei panieri nel rapporto**: compare in fondo, solo quando la prova ha panieri, con relazione, apertura, chiusura, unità, livelli, gambe, motivo d'uscita e risultato; al più gli ultimi 300. Senza panieri il JSON non ha la chiave. Nessun campo nuovo nel piano: le impronte dei piani di oggi non cambiano, e una prova lo controlla sulle sette famiglie del catalogo. + +### La matematica dei panieri (#119) + +Codice puro in `src/Anubis/Baskets/`, senza database né rete. Il documento è citato per numero di sezione. + +7. **Valute e coppie**: le otto valute nell'ordine di mercato (EUR, GBP, AUD, NZD, USD, CAD, CHF, JPY) e le 28 coppie nell'ordine dell'appendice A stanno in un solo file, `Currencies.cs`, che leggono sia la matematica sia le coppie della BCE. Il pip vale 0,01 sulle coppie con lo yen, 0,0001 sulle altre. L'elenco a 14 coppie (D-45) è: EURGBP, EURAUD, EURNZD, EURUSD, EURCAD, EURCHF, GBPUSD, AUDNZD, AUDUSD, AUDCAD, AUDCHF, NZDUSD, USDCAD, USDCHF. Il documento non nomina le 12 di partenza: sono le gambe degli spread documentati e i simboli dell'edizione a dieci, più EURCAD e AUDNZD. +8. **Orologio del server** = ora di New York + 7 ore: segue solo l'ora legale degli Stati Uniti. Il giorno del server cambia alle 17 di New York. Nell'ora in cui New York torna indietro vale la lettura in ora solare; quell'ora cade la domenica, nel fine settimana. +9. **Ogni finestra oraria include l'inizio ed esclude la fine.** Fine settimana: niente ingressi dal venerdì alle 16 al lunedì alle 2, ora del server. Orario di negoziazione, quando è acceso: dalle 10 alle 20, ora del server. Pausa giornaliera della sede: dalle 16:55 alle 18:10 di New York, niente ingressi né mediazioni. +10. **Relazioni.** Le 378 coppie di coppie sono 56 catene, 112 rapporti e 210 disgiunte. La classificazione non dipende dall'ordine delle gambe. Per un rapporto il cross sintetico è sempre la coppia quotata, con l'indicazione se A/B ne è l'inverso. Il segno vale +1 per le catene, −1 per i rapporti e −segno(ρ) per le disgiunte; con ρ nullo o sconosciuto una disgiunta non ha segno e non si negozia. L'appendice B si genera nell'ordine del documento e coincide riga per riga. +11. **Indici e segnali.** Indice in pip `X = A/pip(A) + s·B/pip(B)`, in punti base logaritmici `10000·(ln A − β·ln B)`. Quale prezzo entra (medio con denaro e lettera, denaro altrimenti) lo sceglie chi chiama. Lo z-score alla barra t usa media e **deviazione campionaria** degli ultimi W valori **compresa la barra t** (W predefinito 100); senza abbastanza valori, con deviazione nulla o con un valore mancante non c'è z-score. `Rvol` = deviazione campionaria delle ultime 16 differenze dell'indice diviso la mediana di quella stessa misura sulle ultime 1.920 barre (20 giorni da 96 barre); senza storia sufficiente non c'è, e senza `Rvol` nessun nuovo ingresso. Il filtro ferma i nuovi ingressi sopra 2,0. +12. **Conti in denaro** sempre in `decimal`: somma dei pip, prezzo comune d'uscita `media ± obiettivo/n × pip`, scala delle distanze `Dmin × max(1, min(Rvol, 3)) × crescita^(k−1)` misurata dall'ultimo livello, nessuna aggiunta dopo l'ultimo livello e lotto mai più grande del primo, escursione che fa scattare lo stop sul valore del conto, valore del pip in dollari (`unità × pip × valore in dollari della valuta quotata`, con lo yen a 1/USDJPY), esposizione per valuta, regola dei tre costi (si apre solo se l'obiettivo vale almeno tre volte il costo). I valori mostrati si arrotondano con l'arrotondamento bancario, come fanno le tabelle 4.12 e 6.9 del documento. +13. **Unità uguali sulle due gambe**: le unità di base si arrotondano per difetto; se una gamba vale meno del minimo della sede (1.000 USD su eToro), le due gambe salgono alle unità che portano la più debole al minimo, arrotondate **per eccesso**. Per questo, al prezzo esatto 0,5417 una gamba in NZD chiede 1.847 unità e non le 1.846 dell'appendice A, che arrotonda al più vicino e resta così un soffio sotto il minimo. +14. **Stati di una coppia**: ferma, in osservazione (|z| ≥ 1,5), pronta (|z| ≥ soglia d'ingresso ma un cancello blocca), aperta. Le soglie sono comprese. Lo spread si considera chiuso con |z| ≤ 0,5. Una coppia senza z-score è ferma. +15. **Stili e profili.** HedgeFund 3,0 / 1 spread / 2 mediazioni; Conservativo 2,5 / 2 / 3; Moderato 2,0 / 2 / 3 (predefinito); Aggressivo 1,5 / 3 / 3, oppure 4 con la crescita delle distanze. Fedele: niente stop di paniere, stop sul valore del conto al 9% con ripresa al giorno dopo del server, solo prova, simulatore e Demo; limiti di esposizione e cancello dei costi solo registrati. Prudente: la stessa logica con gli stop di paniere (z a 3,5, perdita dell'1% invece dell'1,5% del documento per SPEC 9.2, relazione rotta, 96 barre), cancello dei costi e tetto di esposizione per valuta a 2. + +### Barre più corte di un giorno, per la ricerca (#120) + +16. **Durate delle barre**: 1 e 15 minuti, 30 minuti, 1, 4 e 8 ore, 1 giorno, con gli stessi nomi degli archivi di Binance. Il controllo di qualità di un CSV con barre più corte di un giorno usa la loro durata, non quella del giorno. +17. **Aggregazione** in `decimal`, a intervalli allineati sui multipli della durata in UTC (per 15 e 30 minuti e per l'ora coincidono con New York e con l'orologio del server). Apertura la prima, massimo e minimo, chiusura l'ultima, volumi sommati. Un intervallo vuoto non dà barra: **mai riempire un buco**. Un intervallo che finisce dopo l'istante dato non esce. Le barre a 4 e 8 ore delle valute restano allineate in UTC: allinearle al giorno del server è un lavoro della Fase 14, se servirà. +18. **Calendari**: sempre aperto (crypto); valute dalla domenica alle 17 al venerdì alle 17 di New York, con una barra aperta se tocca la settimana di mercato; sedute di una borsa. L'insieme di barre a colonne (`BarDataset`) ha un orologio comune con tutti gli istanti del calendario, prezzi `double` (sono dati di analisi, SPEC 5.4), una casella vuota dove una serie non ha la barra, colonne della lettera facoltative, e un'impronta come quella dei dati giornalieri. `BacktestDataset` non cambia. +19. **Le 28 coppie dalla BCE.** Per ogni giorno ogni coppia BASEQUOTA = cambio della quota / cambio della base contro l'euro, divisione in `decimal` arrotondata a 10 decimali; EURxxx è il cambio stesso. Se un cambio manca quel giorno, mancano solo le coppie che lo usano. La barra è il giorno alle 00:00 UTC, con apertura, massimo, minimo e chiusura uguali e volume zero, sede `ecb`. Lo sguardo in avanti segue la regola dei cambi già usata per lo storico in euro: il cambio del giorno d si conosce verso le 16 di Francoforte del giorno d. Questi sono prezzi di riferimento, non prezzi a cui si negozia: servono alla scrematura del campionato (ADR 0026). +20. **`anubis data ecb`** riusa lo stesso archivio di `backtest base` (`research/ecb-eurofxref-hist.zip`) con la stessa regola di scarico: senza `--offline` lo riscarica ogni volta; con `--offline` usa quello già scaricato e lo scarica solo se manca. Prima di sostituire la copia buona, il file scaricato si controlla (deve aprirsi come lo storico della BCE) e si scrive accanto, poi si sposta al suo posto in un passo: una pagina di manutenzione o uno scarico interrotto non distruggono lo storico. Il caricamento sta ora nella libreria, e `backtest base` scrive la stessa riga di prima. +21. **`anubis data fx`** importa i file a un minuto che l'utente scarica: Dukascopy (un file per lato, denaro o lettera, UTC) e HistData in formato ASCII generico (solo denaro, ora fissa di New York a UTC−5 tutto l'anno). Il formato si riconosce dalla prima riga; qualunque altro formato è rifiutato con un messaggio in italiano. Scrive le barre al minuto e quelle a 15 minuti ricostruite da tutte le barre al minuto già salvate negli intervalli toccati, così più file dello stesso mese restano coerenti. Le barre fuori dalla settimana di mercato si lasciano fuori con una nota. I due formati vengono da conoscenza generale e i file di prova sono costruiti a mano: **vanno verificati sul primo file vero** (`docs/API-NOTES.md`). Nessuno scarico automatico senza il permesso dell'utente (ADR 0025). + +## Alternative scartate + +- **Deviazione della popolazione** per z-score e `Rvol`: il documento non lo dice, e la convenzione del progetto (`Indicators.StandardDeviation`) è campionaria. +- **Finestra dello z-score senza la barra corrente**: il documento calcola media e deviazione «sulle ultime 100 barre» e poi lo z-score della barra stessa; escluderla non cambia lo sguardo in avanti e allontanerebbe dal documento. +- **Arrotondare al più vicino le unità alzate al minimo**, come l'appendice A: lascia una gamba sotto il minimo, che la sede rifiuterebbe. +- **Nuove colonne denaro/lettera nei file dello storico di ricerca**: romperebbero il formato che il controllo dell'intestazione fissa; ogni lato è una serie a sé (`EURUSD-BID`, `EURUSD-ASK`). +- **Un elenco delle coppie per ogni modulo**: due copie divergono; il piano chiede «una casa sola». + +## Conseguenze + +- La Fase 13 può dividere il giudice in varianti e giudizio senza toccare i rapporti di oggi, e la Fase 14 può mettere il motore a panieri dietro lo stesso giudice. +- Le formule del documento hanno ora una prova per ogni numero che il documento scrive (tabelle 4.5, 4.12 e 6.9, l'esempio AUDUSD, l'appendice B, i conteggi delle relazioni) e una prova di proprietà contro lo sguardo in avanti. +- Senza i file a un minuto dell'utente le valute si provano solo sui cambi giornalieri della BCE. +- `Rvol` ricalcola la mediana a ogni chiamata: va bene per le prove e la ricerca; il motore a panieri della Fase 14 ne vorrà una versione che scorre sulla serie, con questa come riferimento. diff --git a/src/Anubis.Server/DataCommand.cs b/src/Anubis.Server/DataCommand.cs index e9e52f6..8d9c574 100644 --- a/src/Anubis.Server/DataCommand.cs +++ b/src/Anubis.Server/DataCommand.cs @@ -88,7 +88,8 @@ internal static class DataCommand } } catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or System.Text.Json.JsonException - or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException) + or InvalidOperationException or TimeZoneNotFoundException or System.Data.Common.DbException or UnauthorizedAccessException + or System.IO.InvalidDataException) { await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); return 1; diff --git a/src/Anubis/Baskets/BasketIndex.cs b/src/Anubis/Baskets/BasketIndex.cs index 4ab6d37..9a42b70 100644 --- a/src/Anubis/Baskets/BasketIndex.cs +++ b/src/Anubis/Baskets/BasketIndex.cs @@ -61,6 +61,13 @@ public static class BasketIndex return null; } + // A flat window has no z-score. Its mean can miss the common value by one rounding step, which would leave a + // deviation of 1e-12 and a meaningless z of ±0.995: so a window whose values are all equal is flat by definition. + if (Flat(index, t - window + 1, t)) + { + return null; + } + var deviation = Deviation(index, t - window + 1, t, out var mean); return deviation is > 0 ? (index[t] - mean) / deviation : null; } @@ -192,6 +199,19 @@ public static class BasketIndex private static bool Within(IReadOnlyList values, int t) => t >= 0 && t < values.Count; + private static bool Flat(IReadOnlyList values, int from, int to) + { + for (var i = from + 1; i <= to; i++) + { + if (values[i] != values[from]) + { + return false; + } + } + + return true; + } + /// Sample standard deviation of values[from..to]; null when a value is missing. private static double? Deviation(IReadOnlyList values, int from, int to, out double mean) { diff --git a/src/Anubis/Data/FreeSources.cs b/src/Anubis/Data/FreeSources.cs index 38101bd..f9784db 100644 --- a/src/Anubis/Data/FreeSources.cs +++ b/src/Anubis/Data/FreeSources.cs @@ -89,11 +89,28 @@ public static class Ecb { var zip = await http.GetBytesAsync(History, null, null, cancellationToken).ConfigureAwait(false) ?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true); + // A body that is not the history (a maintenance page, a cut download) must not replace the good copy: it is + // checked first, then written beside the cache and moved over it in one step. + _ = HistoryCsv(zip, "scaricato"); Directory.CreateDirectory(researchRoot); - await File.WriteAllBytesAsync(path, zip, cancellationToken).ConfigureAwait(false); + var partial = path + ".tmp"; + await File.WriteAllBytesAsync(partial, zip, cancellationToken).ConfigureAwait(false); + File.Move(partial, path, overwrite: true); } - return ParseHistoryCsv(ExtractHistoryCsv(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)), currencies); + return ParseHistoryCsv(HistoryCsv(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false), "già scaricato"), currencies); + } + + private static string HistoryCsv(byte[] zip, string which) + { + try + { + return ExtractHistoryCsv(zip); + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException) + { + throw new MarketDataException($"BCE: il file {which} non è lo storico dei cambi (un archivio zip con un CSV).", retryable: true, ex); + } } } diff --git a/src/Anubis/Data/FxMinuteFiles.cs b/src/Anubis/Data/FxMinuteFiles.cs index 0007503..485f803 100644 --- a/src/Anubis/Data/FxMinuteFiles.cs +++ b/src/Anubis/Data/FxMinuteFiles.cs @@ -142,7 +142,10 @@ public sealed class FxMinuteImporter(ResearchStore store) var open = ordered.Where(b => BarCalendars.Fx.IsOpen(b.OpensAt, OneMinute)).ToList(); if (open.Count == 0) { - throw new FormatException($"Nessuna barra valida nel file: {parsed.Errors} righe non lette su {parsed.Lines}."); + var outside = ordered.Count; + throw new FormatException(outside > 0 + ? $"Nessuna barra valida nel file: tutte le {outside} barre lette cadono fuori dall'orario del mercato (24×5, dalla domenica alle 17 al venerdì alle 17 di New York)." + : $"Nessuna barra valida nel file: {parsed.Errors} righe non lette su {parsed.Lines}."); } if (open.Count > 1 && !open.Zip(open.Skip(1)).Any(p => p.Second.OpensAt - p.First.OpensAt == OneMinute)) diff --git a/src/Anubis/Data/Importers.cs b/src/Anubis/Data/Importers.cs index 6cff92b..7d945cd 100644 --- a/src/Anubis/Data/Importers.cs +++ b/src/Anubis/Data/Importers.cs @@ -257,7 +257,13 @@ public sealed partial class CsvImporter(ResearchStore store) var match = FixedOffset().Match(id); if (match.Success) { - var offset = new TimeSpan(int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture), 0); + var minutes = int.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture); + if (minutes >= 60) + { + throw new TimeZoneNotFoundException($"Fuso orario «{id}» non valido: i minuti vanno da 00 a 59."); + } + + var offset = new TimeSpan(int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), minutes, 0); if (offset > TimeSpan.FromHours(14)) { throw new TimeZoneNotFoundException($"Fuso orario «{id}» fuori dai limiti (al massimo 14 ore da UTC)."); diff --git a/tests/Anubis.Tests/BasketSignalTests.cs b/tests/Anubis.Tests/BasketSignalTests.cs index 083914b..09b6e7d 100644 --- a/tests/Anubis.Tests/BasketSignalTests.cs +++ b/tests/Anubis.Tests/BasketSignalTests.cs @@ -54,6 +54,9 @@ public sealed class BasketSignalTests // Fewer than W values, a flat window or a missing value: no z. Assert.IsNull(BasketIndex.ZScore(index, 3, window: 5)); Assert.IsNull(BasketIndex.ZScore([5, 5, 5, 5, 5], 4, window: 5)); + // A flat window of a value with no exact binary form: its mean misses by one rounding step, still no z. + Assert.IsNull(BasketIndex.ZScore(Enumerable.Repeat(10856.1, 100).ToArray(), 99)); + Assert.IsNull(BasketIndex.ZScore(Enumerable.Repeat(0.1, 100).ToArray(), 99)); Assert.IsNull(BasketIndex.ZScore([1, 2, double.NaN, 4, 5], 4, window: 5)); Assert.AreEqual(100, BasketIndex.DefaultWindow); } diff --git a/tests/Anubis.Tests/ResearchBarsTests.cs b/tests/Anubis.Tests/ResearchBarsTests.cs index 8b2f01f..967c7af 100644 --- a/tests/Anubis.Tests/ResearchBarsTests.cs +++ b/tests/Anubis.Tests/ResearchBarsTests.cs @@ -559,6 +559,71 @@ public sealed class ResearchBarsTests } } + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DataFxSaysWhyWhenEveryBarFallsOutsideTheMarketWeek() + { + var data = TempFolder.Create("data-fx-weekend"); + try + { + var env = ServerHarness.DockerSqlite(); + const string NL = "\n"; + var saturday = Path.Combine(data, "EURUSD_Candlestick_1_M_BID_06.01.2024-06.01.2024.csv"); + await File.WriteAllTextAsync(saturday, "Gmt time,Open,High,Low,Close,Volume" + NL + "06.01.2024 08:00:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL + + "06.01.2024 08:01:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL + "06.01.2024 08:02:00.000,1.0945,1.0945,1.0945,1.0945,0" + NL).ConfigureAwait(false); + using var output = new StringWriter(); + Assert.AreEqual(1, await DataCommand.RunAsync(["fx", saturday, "--platform", "docker", "--data-dir", data], output, env).ConfigureAwait(false), output.ToString()); + StringAssert.StartsWith(output.ToString(), "Non riuscito: "); + StringAssert.Contains(output.ToString(), "tutte le 3 barre lette cadono fuori dall'orario del mercato"); + Assert.AreEqual(0, new ResearchStore(Path.Combine(data, "research")).Series().Count, "nothing written"); + } + finally + { + TempFolder.Delete(data); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ABrokenEcbHistoryNeverReplacesTheGoodOneAndIsRefusedInItalian() + { + var data = TempFolder.Create("data-ecb-broken"); + try + { + var env = ServerHarness.DockerSqlite(); + using (var first = new StringWriter()) + { + Assert.AreEqual(0, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], first, env, new FakeHttp().OnBytes("eurofxref-hist.zip", EcbZip())).ConfigureAwait(false), first.ToString()); + } + + var cached = Path.Combine(data, "research", Ecb.HistoryFile); + var good = await File.ReadAllBytesAsync(cached).ConfigureAwait(false); + + // The ECB answers with a page that is not the history: the command stops in Italian and the good copy stays. + var page = new FakeHttp().OnBytes("eurofxref-hist.zip", System.Text.Encoding.UTF8.GetBytes("Manutenzione")); + using (var output = new StringWriter()) + { + Assert.AreEqual(1, await DataCommand.RunAsync(["ecb", "--platform", "docker", "--data-dir", data], output, env, page).ConfigureAwait(false), output.ToString()); + StringAssert.StartsWith(output.ToString(), "Non riuscito: BCE: il file scaricato non è lo storico dei cambi"); + } + + CollectionAssert.AreEqual(good, await File.ReadAllBytesAsync(cached).ConfigureAwait(false), "the good history is untouched"); + Assert.IsFalse(File.Exists(cached + ".tmp")); + + // A cached copy cut short (an old interrupted write): offline, the command says so instead of crashing. + await File.WriteAllBytesAsync(cached, good.AsSpan(0, good.Length / 2).ToArray()).ConfigureAwait(false); + using (var output = new StringWriter()) + { + Assert.AreEqual(1, await DataCommand.RunAsync(["ecb", "--offline", "--platform", "docker", "--data-dir", data], output, env, new FakeHttp()).ConfigureAwait(false), output.ToString()); + StringAssert.StartsWith(output.ToString(), "Non riuscito: BCE: il file già scaricato non è lo storico dei cambi"); + } + } + finally + { + TempFolder.Delete(data); + } + } + [TestMethod] [TestCategory(Category.Unit)] public async Task DataUsageListsTheNewCommandsAndTimeframes() @@ -589,6 +654,8 @@ public sealed class ResearchBarsTests Assert.AreEqual(TimeSpan.FromHours(5.5), CsvImporter.ZoneOf("UTC+05:30").BaseUtcOffset); Assert.AreEqual(TimeSpan.Zero, CsvImporter.ZoneOf("UTC").BaseUtcOffset); Assert.ThrowsExactly(() => CsvImporter.ZoneOf("Nowhere/Atlantis")); + Assert.ThrowsExactly(() => CsvImporter.ZoneOf("UTC-05:60"), "a typo in the minutes is refused, not read as UTC-06:00"); + Assert.ThrowsExactly(() => CsvImporter.ZoneOf("UTC+00:90")); } [TestMethod] -- 2.54.1