-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_pipeline.py
More file actions
1613 lines (1358 loc) · 67.7 KB
/
run_pipeline.py
File metadata and controls
1613 lines (1358 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
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
"""
run_pipeline.py — Master entry point for the Trading-Crab market regime pipeline.
Runs all 9 pipeline steps in order, or any selected subset, with a consistent
RunConfig passed through every module.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PIPELINE STEPS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1 ingest Scrape multpl.com (46 series) + FRED API → macro_raw.parquet;
also loads ETF prices into ``data/raw/asset_prices.parquet``
(same cache step 6 uses unless ``--refresh-assets``).
2 features Log transforms, derivatives, gap-fill → features.parquet
3 cluster PCA + KMeans → cluster_labels.parquet
4 regime_label Statistical profiling + human-readable names → profiles.parquet
5 predict Supervised classifiers (current + forward horizons)
6 asset_returns ETF returns by regime via yfinance
7 dashboard Print dashboard + save outputs/reports/dashboard.csv
8 diagnostics Ratio + RRG diagnostics → outputs/reports/diagnostics/
9 tactics Per-asset tactics signals → tactics_signals.parquet
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ALL CLI FLAGS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
--refresh Re-scrape multpl.com + re-hit FRED API (~10 min).
Without this flag, steps 1–2 load from cached checkpoints
if younger than ``data.checkpoint_max_age_days`` in
``config/settings.yaml`` (default 7; raise to refresh less often).
--recompute Recompute derived features (step 2) from cached raw data.
Use after editing config/settings.yaml feature lists or
transforms.py without wanting to re-scrape.
--refresh-assets Re-fetch ETF prices from yfinance (step 6 only).
Without this flag, step 6 reuses data/raw/asset_prices.parquet
if it already exists. Useful when behind a firewall or when
ETF data hasn't changed since the last run.
--plots Generate and save matplotlib figures to outputs/plots/.
Each step produces its own set of charts.
--show-plots Also call plt.show() after each figure.
Off by default; do NOT use in CI or headless environments.
--verbose Set logging level to DEBUG (very chatty).
--steps 1,3,5 Run only the listed step numbers (comma-separated integers).
Example: --steps 3,4,5,6,7 skips ingestion and features.
If 7 is listed together with 8 and/or 9, steps 8 and 9 run before 7
so weekly_report.md can include diagnostics and tactics in one run.
Valid values: 1 2 3 4 5 6 7 8 9
--no-constrained Skip the k-means-constrained package even if installed.
Falls back to plain KMeans for balanced clustering.
Use if you haven't run: pip install k-means-constrained
--no-drop-tail Include the most-recent (potentially incomplete) quarter.
By default the trailing row is dropped when it contains NaN
in any feature column — a side effect of the centered
np.gradient edge window in step 2.
--market-code NAME Inject a market_code label column into macro_raw so that
downstream models and notebooks can overlay regime labels.
NAME must be one of:
grok Load the original Grok AI-generated labels
from data/grok_*.pickle (cached automatically
to market_code_grok checkpoint on first use)
clustered Load labels saved by a prior --save-market-code
run (checkpoint: market_code_clustered)
predicted Load labels auto-saved by step 5 on its last
run (checkpoint: market_code_predicted)
<any name> Load checkpoint "market_code_<NAME>"
Omit entirely for a fully data-driven run with no label seed.
--save-market-code After step 3 completes, save the balanced_cluster column as
the "market_code_clustered" checkpoint. Use this so future
runs can reference these cluster assignments with
--market-code clustered.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
AUTO-SAVED CHECKPOINTS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 5 automatically saves the predicted current-regime labels as the
"market_code_predicted" checkpoint every time it runs. No flag needed.
--refresh-preservation
Force-overwrite preservation secondaries (macro_raw_secondary,
features_secondary, features_supervised_secondary) even when
they already exist. Default: update only when missing or when
--refresh / --recompute would rewrite the primary checkpoint.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMMON WORKFLOWS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
① FRESH START — scrape everything, seed with Grok labels (recommended first run):
python run_pipeline.py --refresh --recompute --plots \\
--market-code grok --save-market-code
② FULLY DATA-DRIVEN — no label seed, cluster from data only:
python run_pipeline.py --refresh --recompute --plots --save-market-code
③ FAST RE-RUN — skip scraping, use cached checkpoints, regenerate plots:
python run_pipeline.py --steps 3,4,5,6,7 --plots
④ RE-CLUSTER ONLY — update cluster assignments, save for downstream:
python run_pipeline.py --steps 3 --save-market-code --plots
⑤ DOWNSTREAM WITH NEW CLUSTER LABELS — use labels saved in ④:
python run_pipeline.py --steps 4,5,6,7 --market-code clustered --plots
⑥ DOWNSTREAM WITH GROK SEED — overlay original AI labels:
python run_pipeline.py --steps 4,5,6,7 --market-code grok --plots
⑦ DOWNSTREAM WITH PREDICTED LABELS — use last step-5 predictions:
python run_pipeline.py --steps 4,5,6,7 --market-code predicted --plots
⑧ RECOMPUTE FEATURES WITHOUT RE-SCRAPING (e.g., after editing settings.yaml):
python run_pipeline.py --recompute --steps 2,3,4,5,6,7 --plots
⑨ ETF DATA REFRESH ONLY (no macro re-scrape):
python run_pipeline.py --steps 6,7 --refresh-assets --plots
⑩ DEBUG A SINGLE STEP:
python run_pipeline.py --steps 3 --verbose --plots --show-plots
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MARKET CODE EXPLAINED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The "market_code" is a per-quarter integer label (0-4) that serves as the
reference regime assignment. It is attached to macro_raw in step 1 and
propagated through all downstream steps as an overlay/reference column.
Four sources are available:
grok Original AI-assisted labels (circa 2026-02-16). Useful as a
stable reference baseline — these never change.
clustered Labels from the most recent --save-market-code run. Updated
every time you run step 3 with --save-market-code.
predicted Labels from the most recent step 5 run. Reflects the current
trained classifier's best guess for historical quarters.
(omitted) Run without a market_code column. Clustering is fully
data-driven; no external label is injected.
To list all available market_code checkpoints:
python -c "
from trading_crab_lib.checkpoints import CheckpointManager
cm = CheckpointManager()
mc = [e for e in cm.list() if e['name'].startswith('market_code_')]
for e in mc: print(e['name'], '—', e.get('rows', '?'), 'rows')
"
"""
from __future__ import annotations
import argparse
import logging
import shutil
import sys
from datetime import date
from pathlib import Path
# Allow running from repo root without `pip install -e .`
sys.path.insert(0, str(Path(__file__).parent / "src"))
import trading_crab_lib as crab
DATA_DIR = crab.DATA_DIR
OUTPUT_DIR = crab.OUTPUT_DIR
CONFIG_DIR = crab.CONFIG_DIR
load = crab.load
load_portfolio = crab.load_portfolio
setup_logging = crab.setup_logging
RunConfig = crab.RunConfig
import pandas as pd
from trading_crab_lib.checkpoints import CheckpointManager, preservation_checkpoint_should_write
from trading_crab_lib.email import (
build_weekly_email_body,
load_email_config,
send_weekly_email,
)
log = logging.getLogger(__name__)
# Orchestration only: argparse lives here; individual steps are implemented in
# trading_crab_lib and pipelines/*.py so tests can call the same functions without CLI.
#
# Data-flow mental model (quarterly time index throughout):
# raw macro wide table → engineered features (centered + causal) → PCA space → cluster IDs
# → named regimes + transition stats → supervised models → asset returns conditional on regime
# → dashboard / portfolios. Each arrow is checkpointed so you can resume mid-pipeline.
# ── I/O helpers ───────────────────────────────────────────────────────────────
def _load_parquet(canonical_path: Path, checkpoint_name: str) -> pd.DataFrame:
"""
Load a DataFrame from its canonical inter-step path, falling back to the
CheckpointManager when the file doesn't exist.
This lets steps 3-7 work even when the upstream step was run on a different
machine and only its checkpoint was committed to the repo.
"""
if canonical_path.exists():
return pd.read_parquet(canonical_path)
log.info(
"%s not found — loading from checkpoint '%s'",
canonical_path.name,
checkpoint_name,
)
df = CheckpointManager().load(checkpoint_name)
# Materialize under data/raw/ or data/processed/ so other tools (pandas, DuckDB) see the same path.
# Backfill the canonical file so subsequent reads are fast
canonical_path.parent.mkdir(parents=True, exist_ok=True)
df.to_parquet(canonical_path)
return df
def _repair_macro_raw_missing_columns(
combined: pd.DataFrame,
required: set[str],
cm: CheckpointManager,
) -> tuple[pd.DataFrame, list[str]]:
"""
When data/raw/macro_raw.parquet is missing columns (e.g. stale file vs checkpoint),
copy any available series from the ``macro_raw`` checkpoint so step 2 can run
without forcing a full --refresh ingest.
"""
missing = sorted(required - set(combined.columns))
if not missing:
return combined, []
try:
ck = cm.load("macro_raw")
except FileNotFoundError:
return combined, []
out = combined.copy()
added: list[str] = []
for col in missing:
if col in ck.columns:
out[col] = ck[col].reindex(out.index)
added.append(col)
return out, added
def _checkpoint_ttl_days(cfg: dict) -> float:
"""Max age for macro_raw / features / cluster_labels / asset_prices cache hits."""
return float(cfg.get("data", {}).get("checkpoint_max_age_days", 7))
def _sync_etf_prices_cache(cfg: dict, run_cfg: RunConfig, cm: CheckpointManager) -> None:
"""Fetch or reuse ETF prices during step 1 so later steps share one cache path."""
from trading_crab_lib.ingestion.assets import load_or_fetch_quarterly_prices
ttl = _checkpoint_ttl_days(cfg)
prices = load_or_fetch_quarterly_prices(
cfg,
data_dir=DATA_DIR,
refresh=run_cfg.refresh_asset_prices,
cm=cm,
max_age_days=ttl,
)
if prices is not None and not prices.empty:
log.info(
"Step 1: ETF price cache ready (%d quarters × %d tickers)",
len(prices),
len(prices.columns),
)
# ── market_code helpers ───────────────────────────────────────────────────────
def _load_market_code(
source: str,
cfg: dict,
) -> pd.Series | None:
"""
Load a market_code Series from the specified source.
Args:
source: "grok" to load from the grok pickle, or any other string to
load checkpoint "market_code_{source}".
Returns:
pd.Series of integer codes indexed by quarter-end dates, or None on failure.
"""
from trading_crab_lib.checkpoints import CheckpointManager
cm = CheckpointManager()
if source == "grok":
from trading_crab_lib.ingestion.grok import load_grok_labels
mc = load_grok_labels(DATA_DIR)
if mc is not None:
# Cache so subsequent runs don't need to reload the pickle
cm.save(mc.to_frame(), "market_code_grok")
return mc
# Load from checkpoint
ckpt_name = f"market_code_{source}"
try:
df = cm.load(ckpt_name)
mc = df.iloc[:, 0] # single-column DataFrame → Series
mc.name = "market_code"
log.info("Loaded market_code from checkpoint: %s (%d rows)", ckpt_name, len(mc))
return mc
except FileNotFoundError:
log.error(
"market_code checkpoint '%s' not found. Available checkpoints: %s",
ckpt_name,
[e["name"] for e in cm.list() if e["name"].startswith("market_code_")],
)
return None
def _save_market_code(labels: pd.Series, name: str) -> None:
"""Persist a market_code variant (any integer-coded label Series) to a checkpoint."""
from trading_crab_lib.checkpoints import CheckpointManager
cm = CheckpointManager()
ckpt_name = f"market_code_{name}"
df = labels.rename("market_code").to_frame()
cm.save(df, ckpt_name)
log.info("Saved market_code checkpoint: %s (%d rows)", ckpt_name, len(labels))
# ── Step registry ──────────────────────────────────────────────────────────────
def step1_ingest(cfg: dict, run_cfg: RunConfig) -> None:
"""Ingest macro + ETF prices → ``data/raw/``.
Writes ``macro_raw.parquet`` (FRED + multpl) and ``asset_prices.parquet`` (or
restores ETF data from checkpoint) so all network-heavy loading happens here.
Optionally attaches ``market_code`` from the configured source."""
import pandas as pd
from trading_crab_lib import plotting
from trading_crab_lib.checkpoints import CheckpointManager
from trading_crab_lib.ingestion import fred as fred_module
from trading_crab_lib.ingestion import multpl as multpl_module
from trading_crab_lib.ingestion.macro_partial import (
REQUIRED_MACRO_RAW_FOR_STEP2,
merge_missing_macro_columns,
)
cm = CheckpointManager()
ttl = _checkpoint_ttl_days(cfg)
required_for_step2 = set(REQUIRED_MACRO_RAW_FOR_STEP2)
raw_path = DATA_DIR / "raw" / "macro_raw.parquet"
# Fast path: reuse disk + checkpoint when age and settings hash still match — avoids ~10 min scrape.
if (
not run_cfg.refresh_source_datasets
and cm.is_fresh("macro_raw", max_age_days=ttl, require_config_match=True)
and raw_path.exists()
):
combined = pd.read_parquet(raw_path)
# Stale on-disk files may miss columns added in config later; repair from checkpoint first.
missing = sorted(required_for_step2 - set(combined.columns))
repaired_cols: list[str] = []
dirty = False
partial_merge_written = False
if missing:
combined, repaired_cols = _repair_macro_raw_missing_columns(
combined, required_for_step2, cm
)
if repaired_cols:
log.info(
"Step 1: restored %d macro_raw column(s) from checkpoint: %s",
len(repaired_cols),
repaired_cols,
)
dirty = True
missing = sorted(required_for_step2 - set(combined.columns))
if missing:
log.info(
"Step 1: cached macro_raw missing %d column(s); trying partial FRED/multpl merge: %s",
len(missing),
missing,
)
before_merge_cols = set(combined.columns)
try:
combined = merge_missing_macro_columns(combined, set(missing), cfg)
except Exception as exc:
log.warning("Step 1: partial macro ingest failed (%s)", exc)
missing = sorted(required_for_step2 - set(combined.columns))
added = set(combined.columns) - before_merge_cols
if added:
dirty = True
partial_merge_written = True
# Persist partial merge so data/raw/macro_raw.parquet and the checkpoint
# are not left stale if we later fall through to full fetch or exit early.
combined.to_parquet(raw_path)
cm.save(combined, "macro_raw")
log.info(
"Step 1: wrote macro_raw after partial merge (+%d column(s): %s)",
len(added),
sorted(added),
)
if not missing:
log.info("Step 1: using cached macro_raw checkpoint")
if run_cfg.market_code_source:
mc = _load_market_code(run_cfg.market_code_source, cfg)
if mc is not None:
combined["market_code"] = mc.reindex(combined.index)
dirty = True
log.info(
"Step 1: refreshed market_code=%s in cached macro_raw",
run_cfg.market_code_source,
)
if dirty:
combined.to_parquet(raw_path)
cm.save(combined, "macro_raw")
log.info("Step 1: wrote updated macro_raw → %s", raw_path)
# Seed preservation snapshot on cache hit (not after partial column repair —
# those paths skip secondary so a full --refresh can repopulate later).
if not partial_merge_written and not cm.exists("macro_raw_secondary"):
cm.save(combined, "macro_raw_secondary", preservation=True)
log.info("Step 1: seeded preservation macro_raw_secondary from cached macro")
_sync_etf_prices_cache(cfg, run_cfg, cm)
return
log.warning(
"Step 1: macro_raw still missing required columns (%d) after partial merge — "
"full FRED + multpl fetch (all multpl series in config). Missing: %s",
len(missing),
missing,
)
elif not raw_path.exists():
log.info("Step 1: macro_raw.parquet missing — recomputing ingestion")
# Full ingest: FRED = official macro series; multpl = market valuation / rate history from HTML tables.
log.info("Step 1: fetching FRED data …")
fred_df = fred_module.fetch_all(cfg)
log.info(
"Step 1: scraping multpl.com (%d series) …",
len(cfg["multpl"]["datasets"]),
)
multpl_df = multpl_module.fetch_all(cfg)
# Outer join: align on calendar quarter-end; missing cells remain NaN until step 2 gap-fill.
combined = fred_df.join(multpl_df, how="outer") if not multpl_df.empty else fred_df
start = cfg["data"]["start_date"]
combined = combined[combined.index >= start]
if run_cfg.market_code_source:
mc = _load_market_code(run_cfg.market_code_source, cfg)
if mc is not None:
combined["market_code"] = mc.reindex(combined.index)
log.info(
"Step 1: attached market_code (%s), %d/%d rows have labels",
run_cfg.market_code_source,
combined["market_code"].notna().sum(),
len(combined),
)
raw_dir = DATA_DIR / "raw"
raw_dir.mkdir(parents=True, exist_ok=True)
combined.to_parquet(raw_dir / "macro_raw.parquet")
cm.save(combined, "macro_raw")
if preservation_checkpoint_should_write(
"macro_raw_secondary",
cm,
refresh_preservation=run_cfg.refresh_preservation_checkpoints,
refresh_source=run_cfg.refresh_source_datasets,
recompute_derived=run_cfg.recompute_derived_datasets,
):
cm.save(combined, "macro_raw_secondary", preservation=True)
log.info("Step 1: saved preservation checkpoint macro_raw_secondary")
else:
log.info(
"Step 1: macro_raw_secondary unchanged "
"(exists; use --refresh or --refresh-preservation to overwrite)"
)
_sync_etf_prices_cache(cfg, run_cfg, cm)
if run_cfg.generate_plots:
plotting.plot_raw_series_coverage(combined, run_cfg)
sample_series = [
c
for c in [
"sp500",
"fred_gdp",
"us_infl",
"10yr_ustreas",
"div_yield",
"fred_baa",
]
if c in combined.columns
]
if sample_series:
plotting.plot_raw_series_sample(combined, sample_series, run_cfg)
log.info("Step 1 done: %d rows × %d cols", len(combined), len(combined.columns))
def step2_features(cfg: dict, run_cfg: RunConfig) -> None:
"""Engineer features from macro_raw → data/processed/features.parquet"""
engineer_all = crab.transforms.engineer_all
CheckpointManager = crab.checkpoints.CheckpointManager
plotting = crab.plotting
import pandas as pd
cm = CheckpointManager()
feats_path = DATA_DIR / "processed" / "features.parquet"
sup_path = DATA_DIR / "processed" / "features_supervised.parquet"
ttl = _checkpoint_ttl_days(cfg)
if not run_cfg.recompute_derived_datasets and cm.is_fresh(
"features", max_age_days=ttl, require_config_match=True
):
have_files = feats_path.exists() and sup_path.exists()
if not have_files:
try:
f_df = cm.load("features")
fs_df = cm.load("features_supervised")
except FileNotFoundError:
f_df = fs_df = None
if f_df is not None and fs_df is not None:
feats_path.parent.mkdir(parents=True, exist_ok=True)
f_df.to_parquet(feats_path)
fs_df.to_parquet(sup_path)
log.info(
"Step 2: materialized %s + %s from checkpoints",
feats_path.name,
sup_path.name,
)
have_files = True
if have_files:
import pandas as pd
if feats_path.exists() and not cm.exists("features_secondary"):
cm.save(
pd.read_parquet(feats_path),
"features_secondary",
preservation=True,
)
log.info(
"Step 2: seeded preservation checkpoint features_secondary from %s",
feats_path.name,
)
if sup_path.exists() and not cm.exists("features_supervised_secondary"):
cm.save(
pd.read_parquet(sup_path),
"features_supervised_secondary",
preservation=True,
)
log.info(
"Step 2: seeded preservation checkpoint features_supervised_secondary from %s",
sup_path.name,
)
log.info("Step 2: using cached features checkpoint")
return
raw = _load_parquet(DATA_DIR / "raw" / "macro_raw.parquet", "macro_raw")
log.info("Step 2: engineering features from %d × %d raw data …", len(raw), len(raw.columns))
# Centered features (forward + backward window) — used for clustering (steps 3-4)
features = engineer_all(raw, cfg, causal=False)
out_dir = DATA_DIR / "processed"
out_dir.mkdir(parents=True, exist_ok=True)
features.to_parquet(out_dir / "features.parquet")
cm.save(features, "features")
# Causal features (backward-only window) — used for supervised learning (steps 5-7).
# Identical column names to features.parquet but no look-ahead in any derivative.
features_sup = engineer_all(raw, cfg, causal=True)
features_sup.to_parquet(out_dir / "features_supervised.parquet")
cm.save(features_sup, "features_supervised")
# Backwards-compatible aliases for plan-level artifact names.
# These mirror the non-causal and causal feature sets produced above so
# downstream plans can reference features_noncausal / features_causal
# explicitly without changing the core pipeline semantics.
cm.save(features, "features_noncausal")
cm.save(features_sup, "features_causal")
log.info("Step 2: wrote features.parquet (centered) and features_supervised.parquet (causal)")
_pc_kw = dict(
refresh_preservation=run_cfg.refresh_preservation_checkpoints,
refresh_source=run_cfg.refresh_source_datasets,
recompute_derived=run_cfg.recompute_derived_datasets,
)
if preservation_checkpoint_should_write("features_secondary", cm, **_pc_kw):
cm.save(features, "features_secondary", preservation=True)
log.info("Step 2: saved preservation checkpoint features_secondary")
else:
log.info(
"Step 2: features_secondary unchanged "
"(exists; use --recompute or --refresh-preservation to overwrite)"
)
if preservation_checkpoint_should_write("features_supervised_secondary", cm, **_pc_kw):
cm.save(features_sup, "features_supervised_secondary", preservation=True)
log.info("Step 2: saved preservation checkpoint features_supervised_secondary")
else:
log.info(
"Step 2: features_supervised_secondary unchanged "
"(exists; use --recompute or --refresh-preservation to overwrite)"
)
if run_cfg.generate_plots:
feat_only = features.drop(columns=["market_code"], errors="ignore")
plotting.plot_feature_distributions(feat_only, run_cfg)
plotting.plot_feature_correlations(feat_only, run_cfg)
log.info("Step 2 done: %d rows × %d feature cols", len(features), len(features.columns))
def step3_cluster(cfg: dict, run_cfg: RunConfig, save_market_code: bool = False) -> None:
"""PCA + KMeans clustering → data/regimes/cluster_labels.parquet.
When save_market_code=True, also checkpoints balanced_cluster as market_code_clustered."""
reduce_pca = crab.clustering.reduce_pca
evaluate_kmeans = crab.clustering.evaluate_kmeans
pick_best_k = crab.clustering.pick_best_k
fit_clusters = crab.clustering.fit_clusters
build_clustering_manifest = crab.clustering.build_clustering_manifest
clustering_manifest_matches = crab.clustering.clustering_manifest_matches
write_clustering_manifest = crab.clustering.write_clustering_manifest
is_constrained_kmeans_available = crab.clustering.is_constrained_kmeans_available
CheckpointManager = crab.checkpoints.CheckpointManager
plotting = crab.plotting
import pandas as pd
from sklearn.preprocessing import StandardScaler
cm = CheckpointManager()
clust_cfg = cfg["clustering"]
ttl = _checkpoint_ttl_days(cfg)
features = _load_parquet(DATA_DIR / "processed" / "features.parquet", "features")
X = features.drop(columns=["market_code"], errors="ignore").dropna()
n_dropped = len(features) - len(X)
if n_dropped:
log.info(
"Step 3: dropped %d quarter(s) with NaN features before PCA "
"(expected when market_code source doesn't cover all dates)",
n_dropped,
)
out_dir = DATA_DIR / "regimes"
manifest_path = out_dir / "clustering_manifest.json"
labels_path = out_dir / "cluster_labels.parquet"
pca_path = out_dir / "pca_components.parquet"
scores_path = out_dir / "kmeans_scores.parquet"
constrained_available = is_constrained_kmeans_available()
new_manifest = build_clustering_manifest(
features,
clust_cfg,
use_constrained_requested=run_cfg.use_constrained_kmeans,
constrained_available=constrained_available,
)
# Enforce "recluster only on intentional change" via manifest match.
if (
not run_cfg.recompute_derived_datasets
and manifest_path.exists()
and clustering_manifest_matches(manifest_path, new_manifest)
and labels_path.exists()
and pca_path.exists()
and scores_path.exists()
):
log.info(
"Step 3: inputs/config unchanged — skipping reclustering (use --recompute to override)."
)
# Ensure checkpoints exist for downstream step runners.
if labels_path.exists():
df_labels = pd.read_parquet(labels_path)
label_cols = [
c for c in ["cluster", "balanced_cluster", "market_code"] if c in df_labels.columns
]
cm.save(df_labels[label_cols], "cluster_labels")
if pca_path.exists():
cm.save(pd.read_parquet(pca_path), "pca_components")
if save_market_code and labels_path.exists():
df_labels = pd.read_parquet(labels_path)
if "balanced_cluster" in df_labels.columns:
_save_market_code(df_labels["balanced_cluster"], "clustered")
return
# Backfill fallback caching (age-based) when manifest doesn't exist (older runs).
if not run_cfg.recompute_derived_datasets and cm.is_fresh(
"cluster_labels", max_age_days=ttl, require_config_match=True
):
log.info("Step 3: using cached cluster_labels checkpoint (age/config ok)")
return
# PCA reduces correlated macro features to a few orthogonal axes — "regime geometry" lives here.
pca_df, pca_model, scaler = reduce_pca(
X,
n_components=clust_cfg["n_pca_components"],
random_state=clust_cfg["random_state"],
)
# Re-scale PC scores before k-sweep so Euclidean distance in KMeans is not dominated by PC1 variance.
X_scaled = StandardScaler().fit_transform(pca_df.values)
scores = evaluate_kmeans(
X_scaled,
k_range=range(2, clust_cfg["n_clusters_search"] + 1),
random_state=clust_cfg["random_state"],
)
best_k = pick_best_k(scores, k_cap=clust_cfg["k_cap"])
log.info("K-sweep: chose k=%d (cap=%d)", best_k, clust_cfg["k_cap"])
clustered = fit_clusters(
pca_df,
best_k=best_k,
balanced_k=clust_cfg["balanced_k"],
random_state=clust_cfg["random_state"],
use_constrained=run_cfg.use_constrained_kmeans,
)
if "market_code" in features.columns:
clustered["market_code"] = features["market_code"]
out_dir = DATA_DIR / "regimes"
out_dir.mkdir(parents=True, exist_ok=True)
label_cols = ["cluster", "balanced_cluster"] + (
["market_code"] if "market_code" in clustered.columns else []
)
clustered[label_cols].to_parquet(out_dir / "cluster_labels.parquet")
clustered.drop(columns=label_cols, errors="ignore").to_parquet(
out_dir / "pca_components.parquet"
)
scores.to_parquet(out_dir / "kmeans_scores.parquet", index=False)
cm.save(clustered[label_cols], "cluster_labels")
cm.save(pca_df, "pca_components")
# Write/refresh clustering manifest after successful clustering.
write_clustering_manifest(manifest_path, new_manifest)
# Optionally save balanced_cluster as a market_code checkpoint
if save_market_code:
_save_market_code(clustered["balanced_cluster"], "clustered")
log.info(
"Step 3: saved balanced_cluster as market_code_clustered checkpoint "
"(use --market-code clustered on future runs)"
)
if run_cfg.generate_plots:
regime_names: dict[int, str] = {} # populated in step 4; use IDs for now
plotting.plot_pca_scatter(pca_df, clustered["balanced_cluster"], regime_names, run_cfg)
plotting.plot_elbow_curve(scores, best_k, run_cfg)
plotting.plot_cluster_sizes(clustered["balanced_cluster"], regime_names, run_cfg)
log.info("Step 3 done: balanced_k=%d", clust_cfg["balanced_k"])
def step4_regime_label(cfg: dict, run_cfg: RunConfig) -> None:
"""Profile clusters → data/regimes/profiles.parquet + transition_matrix.parquet"""
build_profiles = crab.regime.build_profiles
suggest_names = crab.regime.suggest_names
build_transition_matrix = crab.regime.build_transition_matrix
load_name_overrides = crab.regime.load_name_overrides
CheckpointManager = crab.checkpoints.CheckpointManager
plotting = crab.plotting
import yaml
labels_path = DATA_DIR / "regimes" / "cluster_labels.parquet"
cm = CheckpointManager()
if not labels_path.exists() and not (cm.dir / "cluster_labels.parquet").exists():
raise FileNotFoundError(
"cluster_labels.parquet not found and no cluster_labels checkpoint. "
"Run step 3 first: python run_pipeline.py --steps 3"
)
features = _load_parquet(DATA_DIR / "processed" / "features.parquet", "features")
labels = _load_parquet(labels_path, "cluster_labels")["balanced_cluster"]
common = features.index.intersection(labels.index)
features = features.loc[common]
labels = labels.loc[common]
profile = build_profiles(features, labels)
profile.to_parquet(DATA_DIR / "regimes" / "profiles.parquet")
auto_names = suggest_names(features, labels)
overrides = load_name_overrides(CONFIG_DIR)
regime_names = {**auto_names, **overrides}
suggestions_path = DATA_DIR / "regimes" / "regime_names_suggested.yaml"
with open(suggestions_path, "w") as f:
yaml.dump(regime_names, f, default_flow_style=False)
tm = build_transition_matrix(labels)
tm.to_parquet(DATA_DIR / "regimes" / "transition_matrix.parquet")
if run_cfg.generate_plots:
plotting.plot_transition_matrix(tm, regime_names, run_cfg)
plotting.plot_regime_timeline(labels, regime_names, run_cfg)
key_cols = [
c
for c in [
"us_infl",
"gdp_growth",
"credit_spread",
"sp500_pe",
"log_cpi_d1",
"10yr_ustreas_d1",
"log_earn_d1",
]
if c in features.columns
]
if key_cols:
plotting.plot_regime_profiles(features, labels, regime_names, key_cols, run_cfg)
for rid, name in sorted(regime_names.items()):
n = (labels == rid).sum()
log.info("Cluster %d: %r (%d quarters)", rid, name, n)
log.info("Step 4 done")
def step5_predict(cfg: dict, run_cfg: RunConfig) -> None:
"""Train supervised classifiers → outputs/models/"""
import pickle
import pandas as pd
from sklearn.tree import export_text
from trading_crab_lib import plotting
from trading_crab_lib.asset_returns import compute_proxy_returns, compute_quarterly_returns
from trading_crab_lib.prediction.classifier import (
train_current_regime,
train_forward_behavior_models,
train_forward_classifiers,
train_interpretability_tree,
)
from trading_crab_lib.prediction.feature_gating import select_step5_feature_path
from trading_crab_lib.prediction.model_metrics_artifacts import write_model_metrics_artifacts
feature_path, feature_source, noncausal_used = select_step5_feature_path(
DATA_DIR / "processed",
allow_noncausal_features=run_cfg.allow_noncausal_features,
)
features = _load_parquet(feature_path, feature_source)
labels = _load_parquet(DATA_DIR / "regimes" / "cluster_labels.parquet", "cluster_labels")[
"balanced_cluster"
]
common = features.index.intersection(labels.index)
X = (
features.loc[common]
.drop(columns=["market_code"], errors="ignore")
.dropna(axis=1, how="any")
)
y = labels.loc[common]
# Regime-model horizons / CV
cv_splits = int(cfg.get("prediction", {}).get("cv_splits", 5))
forward_horizons = cfg.get("prediction", {}).get("forward_horizons_quarters", [1, 2, 4, 8])
behavior_horizons = cfg.get("prediction", {}).get("behavior_horizons_quarters", [1])
# ── Regime: current + forward CV bundles ────────────────────────────────
current_bundle = train_current_regime(X, y, cv_splits=cv_splits)
rf_model = current_bundle["models"]["rf"]
dt_model = current_bundle["models"]["dt"]
# Latest quarter: RF probability vector is the "now-cast" regime mix (not a single deterministic label).
# Latest quarter prediction (rf_model gives proba)
latest_proba = rf_model.predict_proba(X.iloc[[-1]])[0]
classes = rf_model.classes_
prob_by_class = {int(c): float(p) for c, p in zip(classes, latest_proba, strict=False)}
latest_regime = max(prob_by_class.items(), key=lambda kv: kv[1])[0]
log.info("Latest quarter → regime %d", latest_regime)
for r, p in sorted(prob_by_class.items(), key=lambda x: -x[1]):
log.info(" Regime %d: %.1f%%", r, p * 100)
forward_models = train_forward_classifiers(X, y, horizons=forward_horizons, cv_splits=cv_splits)
model_dir = OUTPUT_DIR / "models"
model_dir.mkdir(parents=True, exist_ok=True)
with open(model_dir / "current_regime.pkl", "wb") as f:
pickle.dump(rf_model, f)
with open(model_dir / "decision_tree.pkl", "wb") as f:
pickle.dump(dt_model, f)
if "gb" in current_bundle["models"]:
with open(model_dir / "current_regime_gb.pkl", "wb") as f:
pickle.dump(current_bundle["models"]["gb"], f)
log.info("Step 5: saved gradient boosting model → current_regime_gb.pkl")
with open(model_dir / "forward_classifiers.pkl", "wb") as f:
pickle.dump(forward_models, f)
# Optionally save predicted labels as a market_code checkpoint
predicted_labels = pd.Series(rf_model.predict(X), index=X.index, name="market_code").astype(int)
_save_market_code(predicted_labels, "predicted")
log.info(
"Step 5: saved predicted regime labels as market_code_predicted checkpoint "
"(use --market-code predicted on future runs)"
)
# Behavior models: relate macro features to asset return *sign* paths — complements pure regime classification.
# ── Behavior: train per-asset up/flat/down models ─────────────────────
raw_dir = DATA_DIR / "raw"
asset_prices_path = raw_dir / "asset_prices.parquet"
macro_raw_path = raw_dir / "macro_raw.parquet"
returns: pd.DataFrame | None = None
if asset_prices_path.exists():
prices = pd.read_parquet(asset_prices_path)
if not prices.empty:
returns = compute_quarterly_returns(prices)
if returns is None or returns.empty:
if not macro_raw_path.exists():
raise FileNotFoundError(
"Step 5 behavior models require returns input.\n"
f"Neither {asset_prices_path} nor {macro_raw_path} was found."
)
macro_df = pd.read_parquet(macro_raw_path)
returns = compute_proxy_returns(macro_df)
common_ret = returns.index.intersection(X.index)
returns_aligned = returns.loc[common_ret]
behavior_bundle = train_forward_behavior_models(
X,
y,
returns_aligned,
horizons=behavior_horizons,
cv_splits=cv_splits,
)
with open(model_dir / "behavior_models.pkl", "wb") as f:
pickle.dump(behavior_bundle, f)
# ── Metrics artifacts (MODEL-04) ───────────────────────────────────────
metrics_dir = OUTPUT_DIR / "reports" / "model_metrics"
write_model_metrics_artifacts(
output_dir=metrics_dir,
feature_source=feature_source,
noncausal_used=noncausal_used,
regime_current_bundle=current_bundle,
forward_models=forward_models,
behavior_bundle=behavior_bundle,
)
if run_cfg.generate_plots:
try:
regime_names_path = DATA_DIR / "regimes" / "regime_names_suggested.yaml"
import yaml
regime_names = {}
if regime_names_path.exists():
with open(regime_names_path) as f:
regime_names = yaml.safe_load(f) or {}
regime_names = {int(k): v for k, v in regime_names.items()}
plotting.plot_feature_importance(rf_model, X.columns.tolist(), run_cfg)
plotting.plot_forward_probabilities(
{"regime": latest_regime, "probabilities": prob_by_class},
regime_names,
run_cfg,
)
plotting.plot_predicted_vs_actual(X, y, rf_model, regime_names, run_cfg)
cm_path = metrics_dir / "confusion_matrices.parquet"
if cm_path.exists():
conf_df = pd.read_parquet(cm_path)
plotting.plot_regime_confusion_matrix(conf_df, regime_names, run_cfg)
else:
log.warning("Step 5 plots: %s not found — skip confusion matrix", cm_path.name)
except Exception as exc:
log.warning("Could not generate prediction plots: %s", exc)
# ── Interpretability tree (Phase 9) — RF top features ─────────────────────
report_dir = OUTPUT_DIR / "reports"
report_dir.mkdir(parents=True, exist_ok=True)
try:
tree_model, tree_features = train_interpretability_tree(rf_model, X, y, cfg)
tree_txt = export_text(tree_model, feature_names=tree_features)
tree_path = report_dir / "current_regime_tree.txt"
tree_path.write_text(tree_txt, encoding="utf-8")
log.info("Wrote interpretability tree → %s", tree_path)
except Exception as exc: # pragma: no cover - defensive
log.warning("Could not generate interpretability tree: %s", exc)
# ── Interpretability tree on gradient boosting (Phase 19 / MODEL-11) ─────
pred_cfg = cfg.get("prediction", {})
if "gb" in current_bundle["models"] and pred_cfg.get("interpret_tree_on_boosted", True):
try:
gb_model = current_bundle["models"]["gb"]