PineForge HPO 0.1.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 dataclasses import dataclass, field
6from fractions import Fraction
7import json
8import math
9from pathlib import Path
10from typing import Any, Mapping
11
12
13
14
15@dataclass(frozen=True)
17 """One path-qualified StudySpec validation failure."""
18
19 path: str
20 message: str
21
22 def __str__(self) -> str:
23 return f"{self.path}: {self.message}"
24
25
26class StudySpecError(ValueError):
27 """Aggregate error containing every issue found in one StudySpec."""
28
29 def __init__(self, issues: list[ValidationIssue] | tuple[ValidationIssue, ...]):
30 self.issues = tuple(issues)
31 super().__init__("; ".join(str(issue) for issue in self.issues))
32
33
34@dataclass(frozen=True)
36 """Normalized integer, real, Boolean, or categorical search dimension."""
37
38 kind: str
39 low: int | float | None = None
40 high: int | float | None = None
41 step: int | float | None = None
42 log: bool = False
43 choices: tuple[JsonScalar, ...] = ()
44
45
46@dataclass(frozen=True)
48 """One Pine source or compiled artifact and its runtime inputs."""
49
50 id: str
51 source: Path | None
52 artifact: Path | None
53 dataset_ids: tuple[str, ...]
54 fixed_inputs: Mapping[str, JsonScalar]
55 strategy_overrides: Mapping[str, JsonScalar]
56 search_space: Mapping[str, ParameterSpec]
57
58
59@dataclass(frozen=True)
61 """One OHLCV source and its PineForge timeframe interpretation."""
62
63 id: str
64 ohlcv: Path
65 input_tf: str
66 script_tf: str
67 chart_timezone: str
68
69
70@dataclass(frozen=True)
72 """Objective direction, expression or registration, and constraints."""
73
74 kind: str
75 direction: str
76 expression: str | None = None
77 name: str | None = None
78 constraints: tuple[str, ...] = ()
79 requires: tuple[str, ...] = ()
80 config: Mapping[str, Any] = field(default_factory=dict)
81 nan_policy: str = "fail_trial"
82 division_by_zero: str = "fail_trial"
83
84
85@dataclass(frozen=True)
87 """Validated native TPE model and batching controls."""
88
89 startup_trials: int = 10
90 ei_candidates: int = 24
91 gamma_fraction: float = 0.10
92 gamma_cap: int = 25
93 prior_weight: float = 1.0
94 constant_liar: bool = True
95
96
97@dataclass(frozen=True)
99 """Sampler selection, deterministic seed, budget, and candidate policy."""
100
101 kind: str
102 seed: int
103 trials: int
104 candidate_policy: str = "sampler_default"
105 config: TpeSamplerConfig | None = None
106
107
108@dataclass(frozen=True)
110 """Native trial worker and failure-policy configuration."""
111
112 workers: int
113 isolation: str
114 timeout_seconds: float | None = None
115 fail_fast: bool = False
116
117
118@dataclass(frozen=True)
120 """Fully validated and path-resolved executable StudySpec v1."""
121
122 schema_version: int
123 mode: str
124 strategy: StrategySpec
125 datasets: tuple[DatasetSpec, ...]
126 objective: ObjectiveSpec
127 sampler: SamplerSpec
128 execution: ExecutionSpec
129 spec_path: Path
130
131 @property
132 def search_space(self) -> Mapping[str, ParameterSpec]:
133 """Return the selected strategy's tunable input dimensions."""
134
135 return self.strategy.search_space
136
137 @property
138 def fixed_inputs(self) -> Mapping[str, JsonScalar]:
139 """Return Pine inputs applied unchanged to every trial."""
140
141 return self.strategy.fixed_inputs
142
143 @property
144 def overrides(self) -> Mapping[str, JsonScalar]:
145 """Return runtime ``strategy(...)`` overrides applied to every trial."""
146
147 return self.strategy.strategy_overrides
148
149 @classmethod
150 def from_json(cls, path: str | Path, *, require_files: bool = False) -> "StudySpec":
151 """Load a StudySpec with the same validation as :func:`load_study_spec`."""
152
153 return load_study_spec(path, require_files=require_files)
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
926def load_study_spec(path: str | Path, *, require_files: bool = False) -> StudySpec:
927 """Load StudySpec v1 and resolve every filesystem path relative to its JSON file."""
928
929 spec_path = Path(path).expanduser().resolve()
930 try:
931 source = spec_path.read_text(encoding="utf-8")
932 except OSError as error:
933 raise StudySpecError(
934 [ValidationIssue("$", f"cannot read {spec_path}: {error}")]
935 ) from error
936 try:
937 document = json.loads(
938 source,
939 object_pairs_hook=_reject_duplicate_keys,
940 parse_constant=_reject_json_constant,
941 )
942 except StudySpecError:
943 raise
944 except json.JSONDecodeError as error:
945 raise StudySpecError(
946 [
948 "$",
949 f"invalid JSON at line {error.lineno}, "
950 f"column {error.colno}: {error.msg}",
951 )
952 ]
953 ) from error
954
955 issues: list[ValidationIssue] = []
956 root = _object(document, "$", issues)
957 _check_unknown(
958 root,
959 {
960 "schema_version",
961 "mode",
962 "strategies",
963 "datasets",
964 "objective",
965 "sampler",
966 "execution",
967 },
968 "$",
969 issues,
970 )
971 schema_version = root.get("schema_version")
972 if schema_version != 1:
973 issues.append(ValidationIssue("$.schema_version", "must equal 1"))
974 mode = root.get("mode")
975 if mode != "single_strategy":
976 issues.append(
977 ValidationIssue("$.mode", "this loader currently supports single_strategy")
978 )
979
980 strategies = root.get("strategies")
981 strategy_raw: Any = {}
982 if not isinstance(strategies, list) or len(strategies) != 1:
983 issues.append(
984 ValidationIssue("$.strategies", "must contain exactly one strategy")
985 )
986 if isinstance(strategies, list) and strategies:
987 strategy_raw = strategies[0]
988 else:
989 strategy_raw = strategies[0]
990 strategy = _parse_strategy(strategy_raw, spec_path.parent, issues)
991
992 datasets_raw = root.get("datasets")
993 datasets: list[DatasetSpec] = []
994 if not isinstance(datasets_raw, list) or not datasets_raw:
995 issues.append(ValidationIssue("$.datasets", "must be a non-empty array"))
996 else:
997 datasets = [
998 _parse_dataset(value, index, spec_path.parent, issues)
999 for index, value in enumerate(datasets_raw)
1000 ]
1001 dataset_ids = [dataset.id for dataset in datasets if dataset.id]
1002 if len(set(dataset_ids)) != len(dataset_ids):
1003 issues.append(ValidationIssue("$.datasets", "dataset ids must be unique"))
1004 unknown_dataset_ids = sorted(set(strategy.dataset_ids) - set(dataset_ids))
1005 if unknown_dataset_ids:
1006 issues.append(
1008 "$.strategies[0].datasets",
1009 "unknown dataset ids: " + ", ".join(unknown_dataset_ids),
1010 )
1011 )
1012
1013 objective = _parse_objective(root.get("objective"), issues)
1014 sampler = _parse_sampler(root.get("sampler"), issues)
1015 _validate_candidate_policy(strategy, sampler, issues)
1016 execution = _parse_execution(root.get("execution"), issues)
1017
1018 if require_files:
1019 strategy_path = strategy.source or strategy.artifact
1020 if strategy_path is not None and not strategy_path.is_file():
1021 issues.append(
1023 "$.strategies[0]", f"file does not exist: {strategy_path}"
1024 )
1025 )
1026 for index, dataset in enumerate(datasets):
1027 if not dataset.ohlcv.is_file():
1028 issues.append(
1030 f"$.datasets[{index}].ohlcv",
1031 f"file does not exist: {dataset.ohlcv}",
1032 )
1033 )
1034
1035 if issues:
1036 raise StudySpecError(issues)
1037 return StudySpec(
1038 schema_version=1,
1039 mode="single_strategy",
1040 strategy=strategy,
1041 datasets=tuple(datasets),
1042 objective=objective,
1043 sampler=sampler,
1044 execution=execution,
1045 spec_path=spec_path,
1046 )
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
__init__(self, list[ValidationIssue]|tuple[ValidationIssue,...] issues)
Definition study_spec.py:29
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)