PineForge HPO 1.11.0
Native hyperparameter optimization for PineForge strategies
Loading...
Searching...
No Matches
study_spec.py
Go to the documentation of this file.
1"""Dependency-free StudySpec v1 JSON loader and validator."""
2
3from __future__ import annotations
4
5from .error import HpoError
6
7from dataclasses import dataclass, field
8from fractions import Fraction
9import json
10import math
11from pathlib import Path
12from typing import Any, Mapping
13
14
15
16
17@dataclass(frozen=True)
19 """One path-qualified StudySpec validation failure."""
20
21 path: str
22 message: str
23
24 def __str__(self) -> str:
25 return f"{self.path}: {self.message}"
26
27
28class StudySpecError(HpoError, ValueError):
29 """Aggregate error containing every issue found in one StudySpec."""
30
31 def __init__(self, issues: list[ValidationIssue] | tuple[ValidationIssue, ...]):
32 self.issues = tuple(issues)
33 super().__init__("; ".join(str(issue) for issue in self.issues))
34 self.with_failure("hpo_study_spec_invalid", {"reason": "study"})
35
36
37@dataclass(frozen=True)
39 """Normalized integer, real, Boolean, or categorical search dimension."""
40
41 kind: str
42 low: int | float | None = None
43 high: int | float | None = None
44 step: int | float | None = None
45 log: bool = False
46 choices: tuple[JsonScalar, ...] = ()
47
48
49@dataclass(frozen=True)
51 """One Pine source or compiled artifact and its runtime inputs."""
52
53 id: str
54 source: Path | None
55 artifact: Path | None
56 dataset_ids: tuple[str, ...]
57 fixed_inputs: Mapping[str, JsonScalar]
58 strategy_overrides: Mapping[str, JsonScalar]
59 search_space: Mapping[str, ParameterSpec]
60
61
62@dataclass(frozen=True)
64 """One OHLCV source and its PineForge timeframe interpretation."""
65
66 id: str
67 ohlcv: Path | None
68 input_tf: str
69 script_tf: str
70 chart_timezone: str
71 ohlcv_bin: Path | None = None
72 verify_bin: str = "full"
73
74
75@dataclass(frozen=True)
77 """Objective direction, expression or registration, and constraints."""
78
79 kind: str
80 direction: str
81 expression: str | None = None
82 name: str | None = None
83 constraints: tuple[str, ...] = ()
84 requires: tuple[str, ...] = ()
85 config: Mapping[str, Any] = field(default_factory=dict)
86 nan_policy: str = "fail_trial"
87 division_by_zero: str = "fail_trial"
88
89
90@dataclass(frozen=True)
92 """Validated native TPE model and batching controls."""
93
94 startup_trials: int = 10
95 ei_candidates: int = 24
96 gamma_fraction: float = 0.10
97 gamma_cap: int = 25
98 prior_weight: float = 1.0
99 constant_liar: bool = True
100 history_switch: int | None = None
101 max_threads: int = 0
102
103
104@dataclass(frozen=True)
106 """Sampler selection, deterministic seed, budget, and candidate policy."""
107
108 kind: str
109 seed: int
110 trials: int
111 candidate_policy: str = "sampler_default"
112 config: TpeSamplerConfig | None = None
113 candidates_file: Path | None = None
114 scramble: str | None = None
115
116
117@dataclass(frozen=True)
119 """Native trial worker and failure-policy configuration."""
120
121 workers: int
122 isolation: str
123 timeout_seconds: float | None = None
124 fail_fast: bool = False
125 batch_size: int | None = None
126 batch_lag: int = 0
127 # Schedule selector. "batches" is the default and stays byte-identical to 0.12.0;
128 # "rolling" refills a free worker slot at once from whatever has finished.
129 schedule: str = "batches"
130 pruner: str = "none"
131 pruner_rungs: tuple[float, ...] = (0.25, 0.5)
132 pruner_eta: int = 2
133
134
135@dataclass(frozen=True)
137 """Fully validated and path-resolved executable StudySpec v1."""
138
139 schema_version: int
140 mode: str
141 strategy: StrategySpec
142 datasets: tuple[DatasetSpec, ...]
143 objective: ObjectiveSpec
144 sampler: SamplerSpec
145 execution: ExecutionSpec
146 spec_path: Path
147 symbol_feeds: Path | Mapping[str, Any] | None = None
148
149 @property
150 def search_space(self) -> Mapping[str, ParameterSpec]:
151 """Return the selected strategy's tunable input dimensions."""
152
153 return self.strategy.search_space
154
155 @property
156 def fixed_inputs(self) -> Mapping[str, JsonScalar]:
157 """Return Pine inputs applied unchanged to every trial."""
158
159 return self.strategy.fixed_inputs
160
161 @property
162 def overrides(self) -> Mapping[str, JsonScalar]:
163 """Return runtime ``strategy(...)`` overrides applied to every trial."""
164
165 return self.strategy.strategy_overrides
166
167 @classmethod
168 def from_json(cls, path: str | Path, *, require_files: bool = False) -> "StudySpec":
169 """Load a StudySpec with the same validation as :func:`load_study_spec`."""
170
171 return load_study_spec(path, require_files=require_files)
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124def load_study_spec(
1125 path: str | Path, *, require_files: bool = False, continuation: bool = False
1126) -> StudySpec:
1127 """Load StudySpec v1 and resolve every filesystem path relative to its JSON file."""
1128
1129 spec_path = Path(path).expanduser().resolve()
1130 try:
1131 source = spec_path.read_text(encoding="utf-8")
1132 except OSError as error:
1133 raise StudySpecError(
1134 [ValidationIssue("$", f"cannot read {spec_path}: {error}")]
1135 ).with_failure("hpo_input_file_invalid", {}) from error
1136 try:
1137 document = json.loads(
1138 source,
1139 object_pairs_hook=_reject_duplicate_keys,
1140 parse_constant=_reject_json_constant,
1141 )
1142 except StudySpecError:
1143 raise
1144 except json.JSONDecodeError as error:
1145 raise StudySpecError(
1146 [
1148 "$",
1149 f"invalid JSON at line {error.lineno}, "
1150 f"column {error.colno}: {error.msg}",
1151 )
1152 ]
1153 ) from error
1154
1155 issues: list[ValidationIssue] = []
1156 root = _object(document, "$", issues)
1157 _check_unknown(
1158 root,
1159 {
1160 "schema_version",
1161 "mode",
1162 "strategies",
1163 "datasets",
1164 "objective",
1165 "sampler",
1166 "execution",
1167 "symbol_feeds",
1168 },
1169 "$",
1170 issues,
1171 )
1172 schema_version = root.get("schema_version")
1173 if schema_version != 1:
1174 issues.append(ValidationIssue("$.schema_version", "must equal 1"))
1175 mode = root.get("mode")
1176 if mode != "single_strategy":
1177 issues.append(
1178 ValidationIssue("$.mode", "this loader currently supports single_strategy")
1179 )
1180
1181 strategies = root.get("strategies")
1182 strategy_raw: Any = {}
1183 if not isinstance(strategies, list) or len(strategies) != 1:
1184 issues.append(
1185 ValidationIssue("$.strategies", "must contain exactly one strategy")
1186 )
1187 if isinstance(strategies, list) and strategies:
1188 strategy_raw = strategies[0]
1189 else:
1190 strategy_raw = strategies[0]
1191 strategy = _parse_strategy(strategy_raw, spec_path.parent, issues)
1192
1193 symbol_feeds = root.get("symbol_feeds")
1194 if isinstance(symbol_feeds, str) and symbol_feeds:
1195 symbol_feeds = (spec_path.parent / Path(symbol_feeds).expanduser()).resolve()
1196 elif symbol_feeds is not None and not isinstance(symbol_feeds, dict):
1197 issues.append(
1199 "$.symbol_feeds", "must be an index path or inline index object"
1200 )
1201 )
1202
1203 datasets_raw = root.get("datasets")
1204 datasets: list[DatasetSpec] = []
1205 if not isinstance(datasets_raw, list) or not datasets_raw:
1206 issues.append(ValidationIssue("$.datasets", "must be a non-empty array"))
1207 else:
1208 datasets = [
1209 _parse_dataset(value, index, spec_path.parent, issues)
1210 for index, value in enumerate(datasets_raw)
1211 ]
1212 dataset_ids = [dataset.id for dataset in datasets if dataset.id]
1213 if len(set(dataset_ids)) != len(dataset_ids):
1214 issues.append(ValidationIssue("$.datasets", "dataset ids must be unique"))
1215 unknown_dataset_ids = sorted(set(strategy.dataset_ids) - set(dataset_ids))
1216 if unknown_dataset_ids:
1217 issues.append(
1219 "$.strategies[0].datasets",
1220 "unknown dataset ids: " + ", ".join(unknown_dataset_ids),
1221 )
1222 )
1223
1224 objective = _parse_objective(root.get("objective"), issues)
1225 sampler = _parse_sampler(root.get("sampler"), spec_path.parent, issues)
1226 _validate_candidate_policy(strategy, sampler, issues, continuation=continuation)
1227 execution = _parse_execution(root.get("execution"), issues)
1228 if sampler.kind == "candidates" and execution.pruner != "none":
1229 # A pruned row has only a prefix score, so a listed vector could end without a
1230 # full-window score. The native runner refuses the combination as well.
1231 issues.append(
1233 "$.execution.pruner", "must be none when sampler.kind is candidates"
1234 )
1235 )
1236
1237 if (
1238 sampler.kind == "tpe"
1239 and execution.batch_lag == 1
1240 and sampler.config is not None
1241 and not sampler.config.constant_liar
1242 ):
1243 issues.append(
1245 "$.execution.batch_lag",
1246 "lag-one TPE requires sampler.config.constant_liar=true",
1247 )
1248 )
1249
1250 if (
1251 sampler.kind == "tpe"
1252 and execution.schedule == "rolling"
1253 and sampler.config is not None
1254 and not sampler.config.constant_liar
1255 ):
1256 # Every rolling proposal is made while other trials are still running, and constant liar
1257 # is what lets TPE use those outstanding candidates.
1258 issues.append(
1260 "$.execution.schedule",
1261 "rolling TPE requires sampler.config.constant_liar=true",
1262 )
1263 )
1264
1265 if require_files:
1266 strategy_path = strategy.source or strategy.artifact
1267 if strategy_path is not None and not strategy_path.is_file():
1268 issues.append(
1270 "$.strategies[0]", f"file does not exist: {strategy_path}"
1271 )
1272 )
1273 listed = sampler.candidates_file
1274 if listed is not None and not listed.is_file():
1275 # Existence only; the native runner validates the list. The path is not
1276 # echoed.
1277 issues.append(
1279 "$.sampler.config.candidates_file",
1280 "candidate list file does not exist",
1281 )
1282 )
1283 for index, dataset in enumerate(datasets):
1284 source = (
1285 dataset.ohlcv_bin if dataset.ohlcv_bin is not None else dataset.ohlcv
1286 )
1287 source_key = "ohlcv_bin" if dataset.ohlcv_bin is not None else "ohlcv"
1288 if source is not None and not source.is_file():
1289 issues.append(
1291 f"$.datasets[{index}].{source_key}",
1292 f"file does not exist: {source}",
1293 )
1294 )
1295
1296 if issues:
1297 raise StudySpecError(issues)
1298 return StudySpec(
1299 schema_version=1,
1300 mode="single_strategy",
1301 strategy=strategy,
1302 datasets=tuple(datasets),
1303 objective=objective,
1304 sampler=sampler,
1305 execution=execution,
1306 spec_path=spec_path,
1307 symbol_feeds=symbol_feeds,
1308 )
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
with_failure(self, str|None code, dict[str, Any]|None args, str origin="hpo")
Definition error.py:25
__init__(self, list[ValidationIssue]|tuple[ValidationIssue,...] issues)
Definition study_spec.py:31
Mapping[str, ParameterSpec] search_space(self)
"StudySpec" from_json(cls, str|Path path, *bool require_files=False)
Mapping[str, JsonScalar] overrides(self)
Mapping[str, JsonScalar] fixed_inputs(self)