File size: 33,677 Bytes
5995ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Centralised configuration for the What-If Scenario Benchmark pipeline.

Every tunable parameter lives here so that notebooks and scripts have a
single source of truth.

Architecture:
  Layer 1 (Raw Collection)  -> data/{source}/
  Layer 2 (Preprocessing)   -> data/processed/{GRANULARITY}/
  Layer 3 (Benchmark)       -> data/benchmark/{GRANULARITY}/
"""

from pathlib import Path

# ---------------------------------------------------------------------------
# Paths -- Layer 1 (raw data)
# ---------------------------------------------------------------------------
import os as _os

BASE_DIR = Path(__file__).resolve().parent
# Small-cap rebuild: all data lives under data_small_caps/ for the
# clean-slate small-cap-and-below universe rebuild (Apr 2026).
DATA_DIR = BASE_DIR / _os.environ.get("WHATIF_DATA_DIR", "data_small_caps")

UNIVERSE_DIR = DATA_DIR / "universe"
FUNDAMENTALS_DIR = DATA_DIR / "fundamentals"
PRICES_DIR = DATA_DIR / "prices"
FILINGS_DIR = DATA_DIR / "filings"
MACRO_DIR = DATA_DIR / "macro"
REAL_ESTATE_DIR = DATA_DIR / "real_estate"
NEWS_DIR = DATA_DIR / "news"
XBRL_DIR = DATA_DIR / "xbrl"

# ---------------------------------------------------------------------------
# Paths -- Layer 2 & 3 (derived from GRANULARITY)
# ---------------------------------------------------------------------------
GRANULARITY: str = "daily"  # "daily", "weekly", or "monthly"


def get_processed_dir(granularity: str | None = None) -> Path:
    """Return the processed-data directory for *granularity* (default: GRANULARITY)."""
    return DATA_DIR / "processed" / (granularity or GRANULARITY)


def get_benchmark_dir(granularity: str | None = None) -> Path:
    """Return the benchmark-output directory for *granularity* (default: GRANULARITY)."""
    return DATA_DIR / "benchmark" / (granularity or GRANULARITY)


# Legacy module-level aliases (point to the default granularity).
# Use the functions above when the caller might override granularity.
PROCESSED_DIR = get_processed_dir()
BENCHMARK_DIR = get_benchmark_dir()

# ---------------------------------------------------------------------------
# Date range (fixed for reproducibility)
# ---------------------------------------------------------------------------
START_DATE = "2021-01-01"
END_DATE = "2026-04-01"
START_YEAR = int(START_DATE[:4])  # 2021 — used by collect_filings.py
END_YEAR = int(END_DATE[:4])      # 2026 — used by collect_filings.py

# ---------------------------------------------------------------------------
# Global reproducibility seed
# ---------------------------------------------------------------------------
BENCHMARK_SEED = 42

# ---------------------------------------------------------------------------
# Ticker universe
# ---------------------------------------------------------------------------
# iShares Russell 2000 ETF holdings CSV URL
IWM_HOLDINGS_URL = (
    "https://www.ishares.com/us/products/239710/"
    "ishares-russell-2000-etf/1467271812596.ajax?"
    "fileType=csv&fileName=IWM_holdings&dataType=fund"
)
# iShares Core S&P SmallCap ETF (IJR) — tracks S&P SmallCap 600 index
# Defines official "small-cap" range: $1B – $7.4B (S&P methodology, 2025).
IJR_HOLDINGS_URL = (
    "https://www.ishares.com/us/products/239774/"
    "ishares-core-sp-smallcap-etf/1467271812596.ajax?"
    "fileType=csv&fileName=IJR_holdings&dataType=fund"
)
# iShares Micro-Cap ETF holdings CSV URL (micro-caps below small-cap threshold)
IWC_HOLDINGS_URL = (
    "https://www.ishares.com/us/products/239724/"
    "ishares-microcap-etf/1467271812596.ajax?"
    "fileType=csv&fileName=IWC_holdings&dataType=fund"
)

# Market-cap upper bound for the "small-cap and below" universe.
# $7.4B = official S&P 600 SmallCap upper bound (S&P Dow Jones Indices, 2025).
# Tickers with median derived_market_cap above this are filtered out as
# mid-cap or larger and excluded from the benchmark.
SMALL_CAP_MAX_MEDIAN_MCAP: float = 7.4e9

# Market-cap percentile threshold to label "lower end" of Russell 2000
LOWER_END_PERCENTILE = 50  # bottom 50 %

# Cap the total number of tickers (set to None for full universe)
MAX_TICKERS: int | None = None

# Tickers excluded from the universe (none — filter is applied via market cap).
EXCLUDED_TICKERS: list[str] = []

# ---------------------------------------------------------------------------
# Fundamentals collection
# ---------------------------------------------------------------------------
FUNDAMENTALS_WORKERS = 2  # ThreadPoolExecutor parallelism (low to avoid yfinance rate limits)

# ---------------------------------------------------------------------------
# Price collection
# ---------------------------------------------------------------------------
PRICE_BATCH_SIZE = 50  # tickers per yf.download() call

# ---------------------------------------------------------------------------
# SEC filings
# ---------------------------------------------------------------------------
SEC_FILING_TYPES: list[str] = ["10-K", "10-Q", "8-K", "20-F", "6-K", "N-CSR", "N-CSRS"]
SEC_FILING_WORKERS = 4  # asyncio.Semaphore concurrency

# ---------------------------------------------------------------------------
# FRED macro series
# ---------------------------------------------------------------------------
FRED_SERIES: dict[str, str] = {
    # ── Rates & monetary policy ──
    "FEDFUNDS": "Federal Funds Effective Rate",
    "SOFR": "Secured Overnight Financing Rate",
    "DGS2": "2-Year Treasury Constant Maturity Rate",
    "DGS10": "10-Year Treasury Constant Maturity Rate",
    "DGS30": "30-Year Treasury Constant Maturity Rate",
    "T10Y3M": "10-Year Treasury Minus 3-Month Treasury",
    "T10Y2Y": "10-Year Treasury Minus 2-Year Treasury",
    "MORTGAGE30US": "30-Year Fixed Rate Mortgage Average",
    # ── Equity & volatility ──
    "SP500": "S&P 500 Index",
    "NASDAQCOM": "NASDAQ Composite Index",
    "DJIA": "Dow Jones Industrial Average",
    "VIXCLS": "CBOE Volatility Index (VIX)",
    # ── Commodities (FRED daily) ──
    "DCOILWTICO": "Crude Oil Prices: West Texas Intermediate (WTI)",
    "DHHNGSP": "Henry Hub Natural Gas Spot Price",
    # ── Currency & exchange rates ──
    "DTWEXBGS": "Trade Weighted U.S. Dollar Index",
    "DEXUSEU": "U.S. / Euro Foreign Exchange Rate",
    "DEXJPUS": "Japan / U.S. Foreign Exchange Rate",
    "DEXUSUK": "U.S. / U.K. Foreign Exchange Rate",
    "DEXCHUS": "China / U.S. Foreign Exchange Rate",
    # ── Inflation & prices ──
    "CPIAUCSL": "Consumer Price Index For All Urban Consumers (All Items)",
    "CPILFESL": "Consumer Price Index Less Food and Energy (Core CPI)",
    "PPIACO": "Producer Price Index (All Commodities)",
    "T10YIE": "10-Year Breakeven Inflation Rate",
    "T5YIE": "5-Year Breakeven Inflation Rate",
    "PCEPI": "Personal Consumption Expenditures: Chain-type Price Index",
    # ── Labor market ──
    "UNRATE": "Unemployment Rate",
    "ICSA": "Initial Claims (Weekly Jobless Claims)",
    "PAYEMS": "All Employees Total Nonfarm (Payrolls)",
    "JTSJOL": "Job Openings: Total Nonfarm (JOLTS)",
    "CES0500000003": "Average Hourly Earnings of All Employees (Total Private)",
    # ── Credit & financial stress ──
    "BAMLH0A0HYM2": "ICE BofA US High Yield Option-Adjusted Spread",
    "BAMLC0A0CM": "ICE BofA US Corporate Master Option-Adjusted Spread",
    "TEDRATE": "TED Spread (3-Month LIBOR minus 3-Month T-Bill)",
    "STLFSI2": "St. Louis Fed Financial Stress Index",
    "NFCI": "Chicago Fed National Financial Conditions Index",
    # ── Economic activity ──
    "INDPRO": "Industrial Production Index",
    "RSAFS": "Advance Retail Sales: Retail and Food Services",
    "UMCSENT": "University of Michigan Consumer Sentiment",
    "TOTALSA": "Total Vehicle Sales",
    "PERMIT": "New Privately-Owned Housing Units Authorized (Building Permits)",
    # ── Housing ──
    "CSUSHPISA": "S&P/Case-Shiller U.S. National Home Price Index",
    "HOUST": "Housing Starts: Total New Privately Owned",
    # ── Money supply & central bank ──
    "M2SL": "M2 Money Stock",
    "BOGMBASE": "Monetary Base; Total",
    "WALCL": "Federal Reserve Total Assets (Balance Sheet)",
    # ── Business lending ──
    "BUSLOANS": "Commercial and Industrial Loans, All Commercial Banks",
}

# ---------------------------------------------------------------------------
# Real estate metros (address anchors for RentCast radius search)
# ---------------------------------------------------------------------------
_ALL_METROS: list[str] = [
    # ── Top 20 (original) ──
    "350 5th Ave, New York, NY 10118",
    "233 S Wacker Dr, Chicago, IL 60606",
    "1000 Vin Scully Ave, Los Angeles, CA 90012",
    "600 Travis St, Houston, TX 77002",
    "400 S Tryon St, Charlotte, NC 28202",
    "100 Peachtree St NW, Atlanta, GA 30303",
    "200 E Las Olas Blvd, Fort Lauderdale, FL 33301",
    "700 2nd Ave S, Nashville, TN 37210",
    "1 N Central Ave, Phoenix, AZ 85004",
    "2001 Ross Ave, Dallas, TX 75201",
    "200 E Colfax Ave, Denver, CO 80203",
    "1 S Broad St, Philadelphia, PA 19107",
    "100 Summer St, Boston, MA 02110",
    "700 5th Ave, Seattle, WA 98104",
    "50 Fremont St, San Francisco, CA 94105",
    "401 E Pratt St, Baltimore, MD 21202",
    "1 S Main St, Salt Lake City, UT 84111",
    "400 S Orange Ave, Orlando, FL 32801",
    "100 NE 2nd Ave, Portland, OR 97232",
    "325 John Knox Rd, Tallahassee, FL 32303",
    # ── 21-40: Large metros ──
    "1 Riverfront Plz, Newark, NJ 07102",
    "100 N Main St, Memphis, TN 38103",
    "200 W Washington St, Indianapolis, IN 46204",
    "100 S Main St, Las Vegas, NV 89101",
    "600 E Market St, San Antonio, TX 78205",
    "200 E Pratt St, Milwaukee, WI 53202",
    "100 N Broadway, Oklahoma City, OK 73102",
    "500 Main St, Louisville, KY 40202",
    "100 N Main St, Richmond, VA 23219",
    "1 S Pinckney St, Madison, WI 53703",
    "200 E Main St, Norfolk, VA 23510",
    "100 W Capitol Ave, Little Rock, AR 72201",
    "100 S Main St, Tulsa, OK 74103",
    "1 Canal St, New Orleans, LA 70130",
    "100 E Capitol St, Jackson, MS 39201",
    "200 W Adams St, Jacksonville, FL 32202",
    "100 N Main St, Wichita, KS 67202",
    "100 State St, Hartford, CT 06103",
    "1 Exchange Pl, Providence, RI 02903",
    "100 N Tryon St, Raleigh, NC 27601",
    # ── 41-60: Mid-size metros ──
    "200 E Main St, Lexington, KY 40507",
    "100 N Main St, Dayton, OH 45402",
    "100 W 10th St, Wilmington, DE 19801",
    "100 S Main St, Akron, OH 44308",
    "200 N Main St, Greenville, SC 29601",
    "100 E Washington St, Boise, ID 83702",
    "1 City Hall Plz, Durham, NC 27701",
    "100 W Trade St, Winston-Salem, NC 27101",
    "100 S Virginia St, Reno, NV 89501",
    "200 E Main St, Chattanooga, TN 37402",
    "100 N Main St, Columbia, SC 29201",
    "1 S Main St, Spokane, WA 99201",
    "100 E Congress St, Tucson, AZ 85701",
    "200 W Markham St, Birmingham, AL 35203",
    "100 S Main St, Omaha, NE 68102",
    "100 W Broad St, Columbus, OH 43215",
    "100 W Michigan Ave, Kalamazoo, MI 49007",
    "200 N Main St, Ann Arbor, MI 48104",
    "100 E 8th St, Cincinnati, OH 45202",
    "100 S 4th St, Minneapolis, MN 55401",
    # ── 61-80: Growing metros ──
    "100 N Main St, Knoxville, TN 37902",
    "200 W Camelback Rd, Scottsdale, AZ 85251",
    "100 S State St, Provo, UT 84601",
    "100 N College Ave, Fort Collins, CO 80524",
    "200 E Main St, Lakeland, FL 33801",
    "100 S Main St, Savannah, GA 31401",
    "100 W Liberty St, Roanoke, VA 24011",
    "200 E Bay St, Charleston, SC 29401",
    "100 N Main St, Greensburg, PA 15601",
    "100 S Palafox St, Pensacola, FL 32502",
    "200 W Capitol Dr, Baton Rouge, LA 70801",
    "100 E Main St, Mesa, AZ 85201",
    "100 N Central Ave, St. Louis, MO 63101",
    "200 Ross St, Pittsburgh, PA 15219",
    "100 Woodward Ave, Detroit, MI 48226",
    "100 W Main St, Bozeman, MT 59715",
    "100 S 1st Ave, Sioux Falls, SD 57104",
    "200 N Main St, Santa Fe, NM 87501",
    "100 N Stone Ave, Albuquerque, NM 87102",
    "100 S Capitol Blvd, Boise, ID 83702",
    # ── 81-100: Smaller / emerging metros ──
    "200 E Main St, Asheville, NC 28801",
    "100 Congress Ave, Austin, TX 78701",
    "200 E Commerce St, San Jose, CA 95113",
    "100 W Flagler St, Miami, FL 33130",
    "200 S Orange Ave, Sarasota, FL 34236",
    "100 N Main St, Gainesville, FL 32601",
    "200 E College Ave, Tallahassee, FL 32301",
    "100 N Main St, Fayetteville, AR 72701",
    "100 E Market St, Des Moines, IA 50309",
    "200 N Main St, McAllen, TX 78501",
    "100 S Broadway, Wichita Falls, TX 76301",
    "100 W Front St, Missoula, MT 59802",
    "200 E Main St, Rapid City, SD 57701",
    "100 N 1st St, Bismarck, ND 58501",
    "200 W Superior St, Duluth, MN 55802",
    "100 E Main St, Rochester, NY 14604",
    "200 S Warren St, Syracuse, NY 13202",
    "100 Main St, Buffalo, NY 14202",
    "200 E State St, Trenton, NJ 08608",
    "100 S Main St, Harrisburg, PA 17101",
]
# For testing: set MAX_METROS to limit (None = all 100)
MAX_METROS: int | None = None
METROS: list[str] = _ALL_METROS[:MAX_METROS] if MAX_METROS else _ALL_METROS
RENTCAST_PROPERTY_TYPES = ["Multi-Family", "Apartment", "Single Family", "Condo", "Townhouse"]
RENTCAST_RADIUS_MILES = 5.0
RENTCAST_MAX_RESULTS = 500  # max properties per endpoint per metro (1 page)

# ---------------------------------------------------------------------------
# Preprocessing (Layer 2)
# ---------------------------------------------------------------------------
# Key metrics to extract from per-ticker financial statement CSVs
INCOME_KEYS: dict[str, str] = {
    "Total Revenue": "stmt_revenue",
    "Net Income": "stmt_net_income",
    "EBITDA": "stmt_ebitda",
    "EBIT": "stmt_ebit",
    "Gross Profit": "stmt_gross_profit",
    "Operating Income": "stmt_operating_income",
    "Basic EPS": "stmt_basic_eps",
    # Valuation inputs (WACC / effective tax rate / cost of debt)
    "Tax Provision": "stmt_tax_provision",
    "Pretax Income": "stmt_pretax_income",
    "Interest Expense": "stmt_interest_expense",
    "Tax Rate For Calcs": "stmt_tax_rate",
    # Income-statement detail items
    "Cost Of Revenue": "stmt_cogs",
    "Operating Expense": "stmt_operating_expenses",
}
BALANCE_KEYS: dict[str, str] = {
    "Total Assets": "stmt_total_assets",
    "Total Liabilities Net Minority Interest": "stmt_total_liabilities",
    "Total Debt": "stmt_total_debt",
    "Total Equity Gross Minority Interest": "stmt_total_equity",
    "Cash And Cash Equivalents": "stmt_cash",
    "Ordinary Shares Number": "stmt_shares_outstanding",
    "Share Issued": "stmt_shares_issued",
    # Balance-sheet detail items
    "Accounts Receivable": "stmt_accounts_receivable",
    "Net Receivables": "stmt_accounts_receivable",
    "Inventory": "stmt_inventory",
    "Current Assets": "stmt_current_assets",
    "Net PPE": "stmt_ppe_net",
    "Goodwill": "stmt_goodwill",
    "Accounts Payable": "stmt_accounts_payable",
    "Current Liabilities": "stmt_current_liabilities",
    "Long Term Debt": "stmt_lt_debt",
}
CASHFLOW_KEYS: dict[str, str] = {
    "Operating Cash Flow": "stmt_operating_cashflow",
    "Free Cash Flow": "stmt_free_cashflow",
    "Capital Expenditure": "stmt_capex",
    "Financing Cash Flow": "stmt_financing_cashflow",
}

# XBRL tag → stmt_ column mapping (SEC EDGAR).
# Each stmt_ column maps to a list of XBRL tags tried in priority order;
# the first non-null value wins.  Tags are US-GAAP concepts reported in
# 10-K / 10-Q filings stored in data/xbrl/parsed/company_facts.parquet.
XBRL_TAG_MAP: dict[str, list[str]] = {
    "stmt_revenue": [
        "Revenues",
        "RevenueFromContractWithCustomerExcludingAssessedTax",
        "SalesRevenueNet",
        "RevenueFromContractWithCustomerIncludingAssessedTax",
        # Banking / Financial Services equivalents
        "InterestAndDividendIncomeOperating",
        "InterestIncomeExpenseNet",
        "NetInterestIncome",
        "NoninterestIncome",
        "FinancialServicesRevenue",
        # Insurance equivalents
        "PremiumsEarnedNet",
        "InsuranceServicesRevenue",
        "PremiumsWrittenNet",
        # IFRS equivalents
        "Revenue",
        "RevenueFromContractsWithCustomers",
    ],
    "stmt_net_income": [
        "NetIncomeLoss",
        # IFRS
        "ProfitLoss",
        "ProfitLossAttributableToOwnersOfParent",
    ],
    "stmt_ebit": [
        "OperatingIncomeLoss",
        # IFRS
        "ProfitLossBeforeFinanceCostsAndTax",
        "OperatingProfitLoss",
    ],
    "stmt_gross_profit": [
        "GrossProfit",
    ],
    "stmt_operating_income": [
        "OperatingIncomeLoss",
        # IFRS
        "ProfitLossFromOperatingActivities",
        "OperatingProfitLoss",
    ],
    "stmt_basic_eps": [
        "EarningsPerShareBasic",
        # IFRS
        "BasicEarningsLossPerShare",
    ],
    "stmt_tax_provision": [
        "IncomeTaxExpenseBenefit",
        # IFRS
        "IncomeTaxExpenseContinuingOperations",
    ],
    "stmt_pretax_income": [
        "IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest",
        # IFRS
        "ProfitLossBeforeTax",
    ],
    "stmt_interest_expense": [
        "InterestExpense",
        # IFRS
        "FinanceCosts",
        "InterestExpenseOnBorrowings",
    ],
    "stmt_operating_cashflow": [
        "NetCashProvidedByUsedInOperatingActivities",
        # IFRS
        "CashFlowsFromUsedInOperatingActivities",
    ],
    "stmt_capex": [
        "PaymentsToAcquirePropertyPlantAndEquipment",
        # IFRS
        "PurchaseOfPropertyPlantAndEquipmentClassifiedAsInvestingActivities",
    ],
    "stmt_total_assets": ["Assets"],
    "stmt_total_liabilities": ["Liabilities"],
    "stmt_total_debt": [
        "LongTermDebt",
        "LongTermDebtNoncurrent",
        # IFRS
        "NoncurrentFinancialLiabilities",
        "BorrowingsNoncurrent",
        "NoncurrentPortionOfNoncurrentBorrowings",
    ],
    "stmt_total_equity": [
        "StockholdersEquity",
        "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest",
        # IFRS
        "Equity",
        "EquityAttributableToOwnersOfParent",
    ],
    "stmt_cash": [
        "CashAndCashEquivalentsAtCarryingValue",
        "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents",
        # IFRS
        "CashAndCashEquivalents",
    ],
    "stmt_shares_outstanding": [
        "CommonStockSharesOutstanding",
        "EntityCommonStockSharesOutstanding",
        # Fallback: weighted-average for dual-class companies (CRWD, DDOG, etc.)
        "WeightedAverageNumberOfSharesOutstandingBasic",
        "WeightedAverageNumberOfDilutedSharesOutstanding",
        "CommonSharesOutstanding",
    ],
    "stmt_shares_issued": [
        "CommonStockSharesIssued",
        # IFRS
        "IssuedCapital",
    ],
    # ── Balance-sheet detail items ──
    "stmt_accounts_receivable": [
        "AccountsReceivableNetCurrent",
        "AccountsReceivableNet",
        # IFRS
        "TradeAndOtherCurrentReceivables",
    ],
    "stmt_inventory": [
        "InventoryNet",
        "Inventories",
        # IFRS
        "CurrentInventories",
    ],
    "stmt_current_assets": [
        "AssetsCurrent",
        # IFRS
        "CurrentAssets",
    ],
    "stmt_ppe_net": [
        "PropertyPlantAndEquipmentNet",
        # IFRS
        "PropertyPlantAndEquipment",
    ],
    "stmt_goodwill": [
        "Goodwill",
        # IFRS
        "GoodwillGross",
    ],
    "stmt_accounts_payable": [
        "AccountsPayableCurrent",
        "AccountsPayable",
        # IFRS
        "TradeAndOtherCurrentPayables",
    ],
    "stmt_current_liabilities": [
        "LiabilitiesCurrent",
        # IFRS
        "CurrentLiabilities",
    ],
    "stmt_lt_debt": [
        "LongTermDebtNoncurrent",
        "LongTermDebt",
        "LongTermDebtAndCapitalLeaseObligations",
        # IFRS
        "NoncurrentFinancialLiabilities",
        "BorrowingsNoncurrent",
    ],
    # ── Income-statement detail items ──
    "stmt_cogs": [
        "CostOfGoodsAndServicesSold",
        "CostOfRevenue",
        "CostOfGoodsSold",
        # IFRS
        "CostOfSales",
    ],
    "stmt_operating_expenses": [
        "OperatingExpenses",
        # IFRS
        "AdministrativeExpense",
    ],
    # ── Cash-flow detail items ──
    "stmt_financing_cashflow": [
        "NetCashProvidedByUsedInFinancingActivities",
        # IFRS
        "CashFlowsFromUsedInFinancingActivities",
    ],
}

# Auxiliary XBRL tags used to derive composite metrics (EBITDA, FCF, tax rate).
XBRL_DA_TAGS: list[str] = [
    "DepreciationDepletionAndAmortization",
    "DepreciationAndAmortization",
    "Depreciation",
    # IFRS
    "DepreciationAmortisationAndImpairmentLossReversalOfImpairmentLossRecognisedInProfitOrLoss",
    "DepreciationAndAmortisationExpense",
]

# ---------------------------------------------------------------------------
# Benchmark assembly (Layer 3)
# ---------------------------------------------------------------------------
# Temporal split configuration.
# Set TEMPORAL_SPLIT_DATE to a fixed date string (e.g. "2024-01-01") to split
# at that exact date, OR set it to None and use TEMPORAL_SPLIT_RATIO instead.
TEMPORAL_SPLIT_DATE: str | None = None

# Train fraction of unique panel dates (e.g. 0.7 = 70% train, 30% test).
# Only used when TEMPORAL_SPLIT_DATE is None.
TEMPORAL_SPLIT_RATIO: float = 0.7

# Forecasting task parameters -- granularity-aware.
# Values are in *panel periods* (not calendar days).
#   daily:   5d≈1w, 21d≈1mo, 63d≈1q, 126d≈6mo, 252d≈1y
#   weekly:  4w≈1mo, 13w≈1q, 26w≈6mo, 52w≈1y
#   monthly: 1mo, 3mo≈1q, 6mo, 12mo≈1y
HORIZONS_BY_GRANULARITY: dict[str, list[int]] = {
    "daily":   [5, 21, 63, 126, 252],
    "weekly":  [4, 13, 26, 52],
    "monthly": [1, 3, 6, 12],
}
LOOKBACK_WINDOWS_BY_GRANULARITY: dict[str, list[int]] = {
    "daily":   [63, 126, 252],
    "weekly":  [13, 26, 52],
    "monthly": [3, 6, 12],
}

# Legacy flat aliases (default granularity) -- prefer the dicts above.
HORIZONS: list[int] = HORIZONS_BY_GRANULARITY[GRANULARITY]
LOOKBACK_WINDOWS: list[int] = LOOKBACK_WINDOWS_BY_GRANULARITY[GRANULARITY]


def get_horizons(granularity: str | None = None) -> list[int]:
    """Return forecast horizons for *granularity*."""
    return HORIZONS_BY_GRANULARITY[granularity or GRANULARITY]


def get_lookback_windows(granularity: str | None = None) -> list[int]:
    """Return lookback windows for *granularity*."""
    return LOOKBACK_WINDOWS_BY_GRANULARITY[granularity or GRANULARITY]

# ---------------------------------------------------------------------------
# Scenario detection thresholds (Layer 3 -- generate_scenarios.py)
# ---------------------------------------------------------------------------
# Fed funds: minimum absolute change in rate (percentage points) between
# consecutive monthly observations to flag as a rate-change event.
SCENARIO_FEDFUNDS_DELTA = 0.25  # 25 bps

# VIX: spike ratio -- current value / rolling mean must exceed this.
SCENARIO_VIX_SPIKE_RATIO = 1.4
SCENARIO_VIX_ROLLING_WINDOW = 63  # observations (daily)

# Oil (EIA commodity or FRED DCOILWTICO): pct move over rolling window.
SCENARIO_OIL_PCT_CHANGE = 0.09  # 9 %
SCENARIO_OIL_ROLLING_WINDOW = 21  # observations (daily)

# Natural gas: minimum percentage move over a rolling window.
SCENARIO_NATGAS_PCT_CHANGE = 0.15  # 15 %
SCENARIO_NATGAS_ROLLING_WINDOW = 4  # observations (weekly data)

# Market drawdown: minimum percentage drop in S&P 500 over a rolling window.
SCENARIO_SP500_DRAWDOWN = 0.025  # 2.5 %
SCENARIO_SP500_ROLLING_WINDOW = 21  # observations (daily)

# NASDAQ: minimum percentage move (crash or rally divergence).
SCENARIO_NASDAQ_PCT_CHANGE = 0.045  # 4.5 %
SCENARIO_NASDAQ_ROLLING_WINDOW = 21  # observations (daily)

# Yield curve: DGS10 - DGS2 spread thresholds.
SCENARIO_YIELD_CURVE_INVERSION = 0.0  # spread crosses below 0 = inversion
SCENARIO_YIELD_CURVE_STEEPENING = 0.50  # spread widens by ≥ 50bps over window
SCENARIO_YIELD_CURVE_WINDOW = 63  # observations (daily)

# Treasury rate (DGS10): large absolute move in 10-year yield.
SCENARIO_DGS10_DELTA = 0.45  # 45 bps move over window
SCENARIO_DGS10_ROLLING_WINDOW = 21  # observations (daily)

# USD index (DTWEXBGS): large percentage move in trade-weighted dollar.
SCENARIO_USD_PCT_CHANGE = 0.025  # 2.5 %
SCENARIO_USD_ROLLING_WINDOW = 21  # observations (daily)

# CPI / Inflation: large month-over-month change in annualized rate.
SCENARIO_CPI_MOM_THRESHOLD = 0.004  # 0.4% month-over-month (≈4.8% annualized)

# PPI: large month-over-month change.
SCENARIO_PPI_MOM_THRESHOLD = 0.01  # 1% month-over-month

# Unemployment: jump in rate between consecutive observations.
SCENARIO_UNRATE_DELTA = 0.3  # 30 bps increase

# Jobless claims (ICSA): spike ratio vs rolling mean.
SCENARIO_ICSA_SPIKE_RATIO = 1.3
SCENARIO_ICSA_ROLLING_WINDOW = 8  # observations (weekly)

# Payrolls (PAYEMS): large month-over-month change in thousands.
SCENARIO_PAYROLLS_DELTA = 0.002  # 0.2% month-over-month change

# High-yield credit spread: large move over rolling window.
SCENARIO_HY_SPREAD_DELTA = 1.0  # 100 bps widening/tightening over window
SCENARIO_HY_SPREAD_WINDOW = 21  # observations (daily)

# IG corporate spread: large move over rolling window.
SCENARIO_IG_SPREAD_DELTA = 0.30  # 30 bps over window
SCENARIO_IG_SPREAD_WINDOW = 21

# TED spread: spike above threshold.
SCENARIO_TED_SPIKE = 0.50  # 50 bps

# Financial stress index: large move.
SCENARIO_FSI_THRESHOLD = 1.0  # standard deviation units (index is z-scored)

# Mortgage rate: large move over rolling window.
SCENARIO_MORTGAGE_DELTA = 0.50  # 50 bps move over window
SCENARIO_MORTGAGE_ROLLING_WINDOW = 4  # observations (weekly)

# Consumer sentiment (UMCSENT): large drop.
SCENARIO_SENTIMENT_PCT_CHANGE = 0.10  # 10% drop
SCENARIO_SENTIMENT_ROLLING_WINDOW = 2  # observations (monthly)

# Industrial production: large month-over-month change.
SCENARIO_INDPRO_PCT_CHANGE = 0.01  # 1% month-over-month

# Retail sales: large month-over-month change.
SCENARIO_RETAIL_PCT_CHANGE = 0.02  # 2% month-over-month

# Housing starts: large month-over-month change.
SCENARIO_HOUSING_PCT_CHANGE = 0.10  # 10% month-over-month

# Home prices (Case-Shiller): year-over-year deceleration/acceleration.
SCENARIO_HOME_PRICE_YOY_DELTA = 0.03  # 3pp change in YoY rate

# Money supply (M2): year-over-year contraction.
SCENARIO_M2_YOY_THRESHOLD = -0.01  # YoY growth below -1% (contraction)

# 30-year Treasury: large move.
SCENARIO_DGS30_DELTA = 0.50  # 50 bps over window
SCENARIO_DGS30_ROLLING_WINDOW = 21

# Cross-asset: S&P 500 vs NASDAQ divergence.
SCENARIO_SP_NASDAQ_DIVERGENCE = 0.05  # 5% divergence over window
SCENARIO_SP_NASDAQ_WINDOW = 21

# VIX regime: sustained elevated volatility.
SCENARIO_VIX_REGIME_THRESHOLD = 25.0  # VIX above 25
SCENARIO_VIX_REGIME_MIN_DAYS = 10  # sustained for at least 10 days

# ── NEW: Major FX pair shocks (EUR, JPY, GBP, CNY) ──
SCENARIO_FX_PCT_CHANGE = 0.03         # 3% move over window
SCENARIO_FX_ROLLING_WINDOW = 21

# ── NEW: Breakeven inflation shocks (T10YIE, T5YIE) ──
SCENARIO_BEI_DELTA = 0.30             # 30 bps move over window
SCENARIO_BEI_ROLLING_WINDOW = 21

# ── NEW: DJIA large moves ──
SCENARIO_DJIA_PCT_CHANGE = 0.03       # 3% move over window
SCENARIO_DJIA_ROLLING_WINDOW = 21

# ── NEW: JOLTS job openings ──
SCENARIO_JOLTS_PCT_CHANGE = 0.05      # 5% month-over-month change
SCENARIO_JOLTS_DEDUP_DAYS = 28

# ── NEW: Average hourly earnings ──
SCENARIO_EARNINGS_MOM_THRESHOLD = 0.005  # 0.5% month-over-month

# ── NEW: Vehicle sales ──
SCENARIO_VEHICLE_PCT_CHANGE = 0.08    # 8% month-over-month

# ── NEW: Building permits ──
SCENARIO_PERMIT_PCT_CHANGE = 0.08     # 8% month-over-month

# ── NEW: Existing home sales ──
SCENARIO_EXISTING_HOME_SALES_PCT = 0.05  # 5% month-over-month

# ── NEW: Chicago Fed NFCI ──
SCENARIO_NFCI_THRESHOLD = 0.0         # NFCI crosses above 0 (tighter than avg)

# ── NEW: Fed balance sheet (WALCL) ──
SCENARIO_FED_BS_PCT_CHANGE = 0.05     # 5% change over window (quarterly)
SCENARIO_FED_BS_ROLLING_WINDOW = 13   # ~quarterly for weekly data

# ── NEW: Monetary base (BOGMBASE) ──
SCENARIO_MONETARY_BASE_PCT = 0.05     # 5% month-over-month

# ── NEW: Business loans (BUSLOANS) ──
SCENARIO_BUSLOANS_PCT_CHANGE = 0.02   # 2% month-over-month

# ── NEW: PCE inflation ──
SCENARIO_PCEPI_MOM_THRESHOLD = 0.004  # 0.4% month-over-month

# ── NEW: SOFR rate shocks ──
SCENARIO_SOFR_DELTA = 0.25            # 25 bps move
SCENARIO_SOFR_WINDOW = 10             # observations

# ── NEW: Cross-asset composites ──
# Real yield: DGS10 - T10YIE (breakeven inflation)
SCENARIO_REAL_YIELD_DELTA = 0.40      # 40 bps change in real yield
SCENARIO_REAL_YIELD_WINDOW = 21
# Credit compression: HY spread minus IG spread
SCENARIO_CREDIT_COMPRESSION_DELTA = 0.75  # 75 bps change
SCENARIO_CREDIT_COMPRESSION_WINDOW = 21
# Term premium: DGS30 - DGS2
SCENARIO_TERM_PREMIUM_DELTA = 0.50    # 50 bps change
SCENARIO_TERM_PREMIUM_WINDOW = 21
# ── NEW: Short-term shock windows (5-day) for daily series ──
SCENARIO_SP500_SHORT_DRAWDOWN = 0.03  # 3% over 5 days (acute crash)
SCENARIO_SP500_SHORT_WINDOW = 5
SCENARIO_NASDAQ_SHORT_PCT = 0.04      # 4% over 5 days
SCENARIO_NASDAQ_SHORT_WINDOW = 5
SCENARIO_OIL_SHORT_PCT = 0.08         # 8% over 5 days
SCENARIO_OIL_SHORT_WINDOW = 5
SCENARIO_DGS10_SHORT_DELTA = 0.25     # 25 bps over 5 days
SCENARIO_DGS10_SHORT_WINDOW = 5

# Pre/post event windows for scenario context (calendar days).
SCENARIO_PRE_WINDOW_DAYS = 63
SCENARIO_POST_WINDOW_DAYS = 63

# ---------------------------------------------------------------------------
# News collection (Layer 1 -- collect_news.py, Step 10)
# ---------------------------------------------------------------------------
NEWS_WORKERS = 4          # ThreadPoolExecutor parallelism for yfinance news
NEWS_PER_TICKER_COUNT = 50  # articles per ticker per tab (news / press releases)
NEWS_SCENARIO_LIMIT = 10   # Firecrawl results per scenario event
NEWS_RATE_LIMIT_SEC = 1.0  # seconds between API calls

# ---------------------------------------------------------------------------
# Synthetic property generation (agents/synthetic_re/)
# ---------------------------------------------------------------------------
COMMERCIAL_RE_TYPES = ["Office", "Retail", "Industrial", "Mixed-Use"]
COMMERCIAL_RE_SEED_LIMIT = 20  # Firecrawl results per type per metro

# ---------------------------------------------------------------------------
# Valuation (agents/valuation/)
# ---------------------------------------------------------------------------
VALUATION_DIR = DATA_DIR / "valuation"

# DCF parameters
DCF_PROJECTION_YEARS = 5
DCF_TERMINAL_GROWTH_DEFAULT = 0.025   # 2.5% long-term GDP growth
MARKET_RISK_PREMIUM = 0.06            # 6% historical equity risk premium
BETA_LOOKBACK_DAYS = 252              # 1 year of trading days for rolling beta

# Comparable company analysis
COMPS_MAX_PEERS = 10
COMPS_MARKET_CAP_BAND = 0.5           # +/- 50 % for peer filtering by size

# Valuation benchmark
VALUATION_BENCHMARK_TASKS = [
    "valuation_accuracy",              # Task A: estimate intrinsic value
    "statement_generation",            # Task B: generate plausible financials
    "scenario_forecast",               # Task C: forecast impact of what-if
]
VALUATION_HOLDOUT_RATIO = 0.3          # 30 % of tickers held out for eval (Hwang: 50/50 or 70/30)

# ---------------------------------------------------------------------------
# XBRL collection & ontology (Layer 1 -- collected via collect_filings.py)
# ---------------------------------------------------------------------------
# SEC XBRL API base URL (no auth, just User-Agent required)
XBRL_COMPANY_FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json"
XBRL_WORKERS = 8           # asyncio.Semaphore concurrency
XBRL_RATE_LIMIT_SEC = 0.12 # seconds between requests (≤10 req/s SEC limit)
# Filing forms to include in ontology extraction.
# Policy: include EVERY form on which SEC accepts XBRL facts from our universe
# (enumerated from raw responses — 37 distinct forms). Do not gate the
# benchmark by form type: the parser keeps everything SEC deems a valid
# XBRL-bearing filing, and downstream preprocessing picks the latest value
# per (ticker, tag, unit) regardless of form.
XBRL_FORMS: list[str] = [
    # US domestic periodic statements
    "10-K", "10-K/A", "10-Q", "10-Q/A",
    "10-KT", "10-KT/A", "10-QT",  # fiscal-year transition period filings
    # Foreign private issuer periodic (file US-GAAP or IFRS via these)
    "20-F", "20-F/A", "40-F", "40-F/A", "6-K", "6-K/A",
    # Current / event reports (earnings releases often carry full financials)
    "8-K", "8-K/A",
    # Registration statements — IPO, shelf, M&A, employee plans
    "S-1", "S-1/A", "S-1MEF",
    "F-1/A", "F-1MEF",
    "S-3", "S-3ASR",
    "S-4", "S-4/A",
    "S-8",
    "POS AM",
    # Investment company filings (cef / invest taxonomy)
    "N-CSR", "N-2",
    # Prospectus supplements
    "424B2", "424B5", "424B7",
    # Proxy statements
    "DEF 14A", "PRE 14A", "DEFR14A", "DEFC14A", "PREM14A",
    # Tender offers
    "SC TO-I",
]
# Ontology classification thresholds (fraction of companies in an industry)
XBRL_CORE_THRESHOLD = 0.70     # tag appears in ≥70% → core
XBRL_COMMON_THRESHOLD = 0.30   # tag appears in ≥30% → common (else extension)