Datasets:
File size: 76,436 Bytes
02412f8 | 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 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 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 | """Classical (gradient-boosted) methods for the MacroLens unified API.
One concrete class — :class:`LightGBMRegressor` — that covers all 7 tasks
via task-specific private methods. Sklearn-style ``Method`` contract::
LightGBMRegressor(*, task=..., config=...) ↦
.fit(X, y, *, seed=42) ↦ self
.predict(X) ↦ ndarray | DataFrame
.save(path) / .load(path)
Per-task feature engineering mirrors the legacy ``baselines/classical.py``
recipe verbatim (numerics preserved); only the IO / canonical-indices /
eval / subsampling layer is stripped. See plan §9 for the predict-output
shape per task.
Per-task summary (definitive — runner asserts ``predict`` shape):
T1 — Time-series forecasting:
X : ``np.ndarray`` ``(N, lookback, F)`` float32.
y : ``np.ndarray`` ``(N, horizon)`` float32 close trajectory.
Pipeline: per-horizon-step LightGBM. One booster per horizon
index ``h ∈ [0, horizon)`` predicting ``y[:, h]`` from the
flattened ``(lookback × F)`` panel + rolling-close stats.
NO scalar+tile broadcasting hack.
Output: ``(N, horizon)`` float32.
T2 / T5 — Valuation:
X : ``pd.DataFrame`` of ``stmt_*`` (+ ``derived_*`` for T2)
numeric features plus sector / industry one-hot.
y : ``np.ndarray`` ``(N,)`` market_cap.
Pipeline: log-target via sklearn ``Pipeline([scale, lgbm])``
wrapped in ``TransformedTargetRegressor`` (log1p / expm1).
Output: ``(N,)`` float32 — predicted equity value.
T3 / T6 — Per-field generation:
X : ``pd.DataFrame`` keyed by ``(ticker, fiscal_year)`` with
numeric snapshot fields + sector + industry; T6 also has a
``company_description`` text column which is DROPPED in the
default branch (``t6_text_handling="sector_industry_only"``).
y : long-form ``pd.DataFrame[ticker, fiscal_year, field, value]``.
Pipeline: ensemble of one booster per ``field``. ``fitted_fields``
is locked at fit time to ``sorted(y["field"].unique())``. At
predict, every (ticker, fiscal_year) row in ``X`` emits one row
per fitted field.
Output: long-form ``[ticker, fiscal_year, field, pred]``.
T4 — Scenario return:
X : ``pd.DataFrame`` with object-dtype ``lookback`` cells (each
a ``(L, F)`` ndarray) plus ``event_type`` and
``event_description`` string columns. ``event_description`` is
DROPPED in v1.
y : ``np.ndarray`` ``(N,)`` return_pct.
Pipeline: flatten lookback (full L*F) + event_type one-hot.
Output: ``(N,)`` float32 — predicted return %.
T7 — Real-estate valuation:
X : ``pd.DataFrame`` with property attributes (``sqft``, ``beds``,
``baths``, ``year_built``, optionally ``years_since_last_sale``)
and a property-type column.
y : ``pd.DataFrame[address, rent, price]``.
Pipeline: two boosters (one for rent, one for price) with
log-target via ``TransformedTargetRegressor``.
Output: ``pd.DataFrame[address, pred_rent, pred_price]``.
Hard rules (enforced by ``tests/test_layer_isolation.py``):
* Zero IO (no ``pd.read_parquet``, no file reads, no ``config`` imports).
* Zero ``meta`` consumption — methods take only ``X`` (and at fit time,
``y``).
* Zero canonical-indices imports / subsampling.
* Zero eval imports.
"""
from __future__ import annotations
import importlib.metadata
from typing import Any, ClassVar
import numpy as np
import pandas as pd
from ._config import LightGBMConfig, RandomForestConfig
from ._registry import register
from .base import Method, _JoblibSaveMixin
# ── Internal lib_versions helper ──────────────────────────────────────────
def _classical_lib_versions() -> dict[str, str]:
"""Versions of the libs the classical family actually uses.
Restricts the broader default in :class:`Method` (which probes torch /
transformers / vllm too) — those are not imported here.
"""
out: dict[str, str] = {}
for pkg in ("numpy", "pandas", "scikit-learn", "lightgbm"):
try:
out[pkg] = importlib.metadata.version(pkg)
except importlib.metadata.PackageNotFoundError:
pass
return out
# ── Internal helpers (private to LightGBMRegressor) ───────────────────────
def _flatten_panel(
X: np.ndarray,
*,
add_rolling_close: bool = True,
close_idx: int | None = None,
) -> np.ndarray:
"""Flatten an ``(N, L, F)`` panel and append rolling-close stats.
Rolling stats over the lookback window: mean, std, min, max, last.
Mirrors the recipe used by the legacy classical T1 baseline.
"""
if X.ndim != 3:
raise ValueError(f"_flatten_panel: expected (N, L, F); got {X.shape}")
n, lb, f = X.shape
flat = X.reshape(n, lb * f).astype(np.float32)
if not add_rolling_close or close_idx is None or close_idx < 0 or close_idx >= f:
return flat
close = X[:, :, close_idx].astype(np.float32)
stats = np.stack(
[
close.mean(axis=1),
close.std(axis=1),
close.min(axis=1),
close.max(axis=1),
close[:, -1],
],
axis=1,
)
return np.concatenate([flat, stats], axis=1)
def _align_columns(
X: pd.DataFrame,
train_columns: list[str],
*,
fillna: bool = True,
) -> pd.DataFrame:
"""Align ``X`` to ``train_columns``: add missing as zero, drop extras.
``fillna=True`` (legacy / default): zero-fill any remaining NaN cells.
``fillna=False``: preserve NaN cells (used by the LightGBM-pipeline
paths in T2/T5/T7 — LightGBM has native NaN handling and zero-filling
distorts its learned splits).
"""
df = X.copy()
for c in train_columns:
if c not in df.columns:
df[c] = 0.0
df = df[train_columns]
return df.fillna(0.0) if fillna else df
def _numeric_feature_cols(
df: pd.DataFrame, prefixes: tuple[str, ...] | None = None,
) -> list[str]:
"""Return numeric columns of ``df``, optionally filtered by prefix."""
if prefixes is None:
return [c for c in df.columns if df[c].dtype.kind in "fiub"]
return [
c for c in df.columns
if df[c].dtype.kind in "fiub" and c.startswith(prefixes)
]
# ── Concrete method ───────────────────────────────────────────────────────
@register(
name="lightgbm",
family="classical",
tasks=frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"}),
config_class=LightGBMConfig,
)
class LightGBMRegressor(_JoblibSaveMixin, Method):
"""LightGBM regressor with per-task private dispatch.
One class, one config (:class:`LightGBMConfig`); the task is fixed at
construction time. Internally ``fit`` / ``predict`` dispatch on
``self.task`` to a private per-task implementation that owns its
feature-engineering recipe and fitted state.
"""
name: ClassVar[str] = "lightgbm"
family: ClassVar[str] = "classical"
tasks: ClassVar[frozenset[str]] = frozenset(
{"T1", "T2", "T3", "T4", "T5", "T6", "T7"}
)
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: LightGBMConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"LightGBMRegressor: unsupported task {task!r}; "
f"supported = {sorted(self.tasks)}"
)
self.task = task
if config is None:
config = LightGBMConfig(**kwargs) if kwargs else LightGBMConfig()
elif kwargs:
raise ValueError(
"LightGBMRegressor: pass either ``config=`` or kwargs, not both"
)
self.config = config
# Per-task fitted state — populated by .fit().
self._state: dict[str, Any] = {}
# ── public API ────────────────────────────────────────────────────────
def fit(self, X: Any, y: Any, *, seed: int = 42) -> "LightGBMRegressor":
"""Fit the regressor on ``(X, y)``. Returns ``self`` for chaining."""
self._seed = int(seed)
if self.task == "T1":
self._fit_t1(X, y)
elif self.task in ("T2", "T5"):
self._fit_t2_t5(X, y)
elif self.task in ("T3", "T6"):
self._fit_t3_t6(X, y)
elif self.task == "T4":
self._fit_t4(X, y)
elif self.task == "T7":
self._fit_t7(X, y)
else: # pragma: no cover -- gated by __init__
raise ValueError(self.task)
return self
def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
if not self._state:
raise RuntimeError(
"LightGBMRegressor: call .fit(X, y) before .predict()."
)
if self.task == "T1":
return self._predict_t1(X)
if self.task in ("T2", "T5"):
return self._predict_t2_t5(X)
if self.task in ("T3", "T6"):
return self._predict_t3_t6(X)
if self.task == "T4":
return self._predict_t4(X)
if self.task == "T7":
return self._predict_t7(X)
raise ValueError(self.task) # pragma: no cover
def lib_versions(self) -> dict[str, str]:
return _classical_lib_versions()
@classmethod
def default_config(cls) -> LightGBMConfig:
return LightGBMConfig()
# ── LightGBM kwarg builder ────────────────────────────────────────────
def _lgbm_kwargs(self) -> dict[str, Any]:
"""Translate :class:`LightGBMConfig` → ``LGBMRegressor`` kwargs.
Drops config keys that are not LGBM hyperparameters (e.g.,
``t6_text_handling`` is a method-level switch).
"""
d = self.config.model_dump()
d.pop("t6_text_handling", None)
d["random_state"] = getattr(self, "_seed", 42)
return d
def _make_lgbm(self) -> Any:
from lightgbm import LGBMRegressor
return LGBMRegressor(**self._lgbm_kwargs())
def _make_log_pipeline(self) -> Any:
"""LightGBM wrapped in a log1p/expm1 target transform.
Used by T2 / T5 / T7 (positive-target regression).
Drops the previous ``StandardScaler`` step: LightGBM is
scale-invariant AND handles NaN natively, while ``StandardScaler``
does not tolerate NaN. With high-NaN-density T2/T5 inputs (~28%
NaN), the scaler step would either fail or, after a defensive
``np.nan_to_num(...,0)`` upstream, corrupt LightGBM's learned
missing-direction splits.
"""
from sklearn.compose import TransformedTargetRegressor
return TransformedTargetRegressor(
regressor=self._make_lgbm(), func=np.log1p, inverse_func=np.expm1,
)
# ── T1 — multi-output regression on per-window log-returns ────────────
def _fit_t1(self, X: np.ndarray, y: np.ndarray) -> None:
"""Multi-output regression on log-returns relative to last close.
T1 close prices span $0.50 to $5,000+ across the 4,416-ticker
small-cap universe. Training a regressor on raw close prices makes
per-step error scale with price level — high-price tickers dominate
the loss, low-price tickers see un-bounded predictions, and
post-hoc MSE blows up by ten or more orders of magnitude
(LightGBM T1 hit MSE 1.18e+16 on this codepath before the fix).
Fix: target the *log-return relative to the per-window last close*::
c_i = X_i[-1, close_idx] # last close in window i
y_log[i, h] = log(y[i, h] / c_i) # dimensionless O(1) target
At predict time we exponentiate and rescale by the test window's
last close. This matches Persistence's tile-last-close behaviour
as the zero-output limit, and matches what every TSFM (Chronos /
Moirai / TimesFM) does internally.
NaN handling: LightGBM still handles NaN inputs natively; we
scrub +/-inf only. Rows with non-positive c or y are dropped from
training (log undefined).
"""
from sklearn.multioutput import MultiOutputRegressor
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 fit: expected ndarray X (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
if not isinstance(y, np.ndarray) or y.ndim != 2:
raise ValueError(
f"T1 fit: expected ndarray y (N, horizon); got "
f"{type(y).__name__} {getattr(y, 'shape', '?')}"
)
if y.shape[0] != X.shape[0]:
raise ValueError(
f"T1 fit: y/X length mismatch ({y.shape[0]} vs {X.shape[0]})."
)
horizon = int(y.shape[1])
close_idx = 0
c = X[:, -1, close_idx].astype(np.float64) # (N,) last close
y_f = y.astype(np.float64) # (N, H)
# Drop windows where log target is undefined / unstable.
keep = (
np.isfinite(c) & (c > 0.0) &
np.isfinite(y_f).all(axis=1) & (y_f > 0.0).all(axis=1)
)
n_total = int(X.shape[0])
n_keep = int(keep.sum())
if n_keep < 1:
raise RuntimeError(
f"T1 fit: only {n_keep}/{n_total} training windows have "
"positive finite close + horizon prices; cannot fit "
"log-return target."
)
X_kept = X[keep]
c_kept = c[keep]
y_log = np.log(y_f[keep] / c_kept[:, None]).astype(np.float32)
X_flat = _flatten_panel(X_kept, add_rolling_close=True, close_idx=close_idx)
# Scrub +/-inf only (preserve NaN — LightGBM handles it natively).
X_flat = np.where(np.isposinf(X_flat) | np.isneginf(X_flat),
np.nan, X_flat)
model = MultiOutputRegressor(
self._make_lgbm(),
n_jobs=int(self.config.n_jobs),
)
model.fit(X_flat, y_log)
self._state = {
"model": model,
"close_idx": close_idx,
"horizon": horizon,
"n_features_flat": X_flat.shape[1],
"n_train_total": n_total,
"n_train_kept": n_keep,
# Log-return clip range: [-2, 2] = ~14% to ~700% of last close.
"log_clip": 2.0,
}
self._horizon = horizon
def _predict_t1(self, X: np.ndarray) -> np.ndarray:
st = self._state
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 predict: expected ndarray (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
close_idx = int(st["close_idx"])
c_test = X[:, -1, close_idx].astype(np.float64) # (N,)
# Where last close is missing or non-positive we cannot rescale; tile
# last close as the safest fallback (matches Persistence in that cell).
c_safe = np.where(np.isfinite(c_test) & (c_test > 0.0), c_test, np.nan)
X_flat = _flatten_panel(
X, add_rolling_close=True, close_idx=close_idx,
)
X_flat = np.where(np.isposinf(X_flat) | np.isneginf(X_flat),
np.nan, X_flat)
n_train_cols = st["n_features_flat"]
if X_flat.shape[1] > n_train_cols:
X_flat = X_flat[:, :n_train_cols]
elif X_flat.shape[1] < n_train_cols:
pad = np.zeros(
(X_flat.shape[0], n_train_cols - X_flat.shape[1]),
dtype=np.float32,
)
X_flat = np.concatenate([X_flat, pad], axis=1)
log_pred = st["model"].predict(X_flat).astype(np.float64)
if log_pred.ndim == 1:
log_pred = log_pred.reshape(-1, st["horizon"])
clip = float(st.get("log_clip", 2.0))
log_pred = np.clip(log_pred, -clip, clip)
# Rescale: y_pred = c * exp(log_return).
out = c_safe[:, None] * np.exp(log_pred)
# Where c was missing, fall back to last-close tile (NaN here would
# poison the eval; prefer Persistence-equivalent in degenerate cells).
bad = ~np.isfinite(out)
if bad.any():
tile = np.broadcast_to(c_test[:, None], out.shape).astype(np.float64)
out = np.where(bad, tile, out)
return out.astype(np.float32)
# ── T2 / T5 — log-target regression ───────────────────────────────────
def _fit_t2_t5(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
# T2 carries stmt_* + derived_* + macro snapshot (fred_*/eia_*);
# T5 is price-stripped (no derived_*) but keeps the macro snapshot.
# Prefix-picking collapses both into one code path.
if self.task == "T2":
prefixes: tuple[str, ...] = ("stmt_", "derived_", "fred_", "eia_")
else:
prefixes = ("stmt_", "fred_", "eia_")
df = X.copy()
feat_cols = [
c for c in _numeric_feature_cols(df, prefixes)
if c not in {"derived_market_cap", "actual_market_cap"}
]
# Sector / industry one-hot — same construction as the legacy code.
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(sec_dummies.columns)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(ind_dummies.columns)
# Cast numeric features to float32 WITHOUT zero-filling NaN —
# LightGBM handles NaN natively; zero-filling 28% of T2/T5 cells
# corrupted the learned missing-direction splits.
X_feat = df[feat_cols].astype(np.float32)
y_arr = pd.to_numeric(pd.Series(np.asarray(y).ravel()), errors="coerce").astype(
np.float64
)
valid = y_arr.notna() & (y_arr > 0)
X_feat = X_feat.loc[valid.values]
y_arr = y_arr.loc[valid.values]
if X_feat.empty:
raise RuntimeError(
f"{self.task} fit: no rows with positive market_cap after drop."
)
# Scrub only +/-inf; LightGBM rejects non-finite-non-NaN values
# but tolerates NaN.
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
model = self._make_log_pipeline()
model.fit(X_arr, y_arr.values)
self._state = {
"model": model,
"feat_cols": feat_cols,
"prefixes": prefixes,
}
def _predict_t2_t5(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
df = X.copy()
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
X_feat = _align_columns(
df, st["feat_cols"], fillna=False,
).astype(np.float32)
# Preserve NaN for LightGBM (matches the fit-time distribution);
# scrub only +/-inf.
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
# TransformedTargetRegressor inverts log1p → expm1 internally.
preds = st["model"].predict(X_arr)
# Floor at zero to keep the (positive) market-cap interpretation.
preds = np.clip(preds, 0.0, None)
return preds.astype(np.float32)
# ── T3 / T6 — per-field booster ensemble ──────────────────────────────
def _t3_t6_build_ticker_features(
self, X: pd.DataFrame,
) -> tuple[pd.DataFrame, list[str]]:
"""Return ``(per-ticker numeric+sector features DataFrame, feat_cols)``.
Mirrors the legacy ``run_task_3_classical`` recipe:
* Pick numeric columns excluding ``fiscal_year`` (the join key)
and ``value_num`` (an internal scratch column).
* For T6 with ``t6_text_handling="sector_industry_only"``, the NL
``company_description`` column is dropped here implicitly because
string columns are non-numeric (and the explicit drop below is a
belt-and-braces guard).
* One-hot-encode ``sector`` (prefix=``sec``) deduped per ticker.
"""
df = X.copy()
# Defensive: explicitly drop free-text columns (T6) so they cannot
# accidentally leak into a future dtype check.
for text_col in ("company_description",):
if text_col in df.columns:
df = df.drop(columns=[text_col])
ticker_feat_cols = [
c for c in _numeric_feature_cols(df)
if c not in {"fiscal_year"} and c != "value_num"
]
ticker_feats = df[["ticker"] + ticker_feat_cols].copy()
ticker_feats[ticker_feat_cols] = (
ticker_feats[ticker_feat_cols].astype(np.float32).fillna(0.0)
)
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df.set_index("ticker")["sector"], prefix="sec", dtype=np.float32,
)
sec_dummies = sec_dummies.reset_index().drop_duplicates("ticker")
ticker_feats = (
ticker_feats.drop_duplicates("ticker")
.merge(sec_dummies, on="ticker", how="left")
.fillna(0.0)
)
else:
ticker_feats = ticker_feats.drop_duplicates("ticker")
feat_cols = [c for c in ticker_feats.columns if c != "ticker"]
return ticker_feats, feat_cols
def _fit_t3_t6(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
"""Fit a SINGLE LightGBM that takes per-(ticker, fiscal_year)
numeric features concatenated with a sparse one-hot of ``field``,
predicting the scalar ``value``.
Output panel: one row per (ticker, fiscal_year, fitted_field) at
predict time. Per-field median fallback is kept for fields whose
training pool is too small (``<5`` rows) to fit.
"""
from scipy.sparse import csr_matrix, hstack as sparse_hstack
from sklearn.preprocessing import OneHotEncoder
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected long-form DataFrame y; got "
f"{type(y).__name__}"
)
for col in ("ticker", "field", "value"):
if col not in y.columns:
raise ValueError(
f"{self.task} fit: y missing required column {col!r}"
)
ticker_feats, feat_cols = self._t3_t6_build_ticker_features(X)
# Lock the field set to ``sorted(y["field"].unique())`` (per plan §1).
fitted_fields: list[str] = sorted(
str(f) for f in y["field"].astype(str).unique()
)
# Long-form labels joined with per-ticker features (broadcast across
# fiscal years). Drop rows with no parseable target.
gt = y.copy()
gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce")
gt["field"] = gt["field"].astype(str)
gt = gt.merge(ticker_feats, on="ticker", how="left").fillna(0.0)
gt = gt.dropna(subset=["value_num"])
# Per-field median fallback for fields with too few rows (the
# legacy small-pool guard, preserved field-by-field).
per_field_count = gt.groupby("field").size().to_dict()
median_fields: dict[str, float] = {}
small_field_set: set[str] = set()
for field in fitted_fields:
cnt = int(per_field_count.get(field, 0))
if cnt < 5:
sub = gt[gt["field"] == field]
med = float(sub["value_num"].median()) if not sub.empty else 0.0
median_fields[field] = med
small_field_set.add(field)
train_mask = ~gt["field"].isin(small_field_set)
gt_train = gt[train_mask]
# Decide a global log-transform heuristic (preserves legacy magnitude
# gate) using the pooled non-zero target distribution.
global_model = None
global_scaler = None
use_log = False
y_min = 0.0
y_max = 0.0
y_range = 1.0
ohe: OneHotEncoder | None = None
if not gt_train.empty:
y_tr = gt_train["value_num"].values.astype(np.float64)
nz = y_tr[y_tr != 0]
if nz.size > 0:
use_log = float(np.median(np.abs(nz))) > 1000
y_tr_t = (
np.sign(y_tr) * np.log1p(np.abs(y_tr)) if use_log else y_tr
)
# Per-ticker numerics already pass through ``.fillna(0.0)`` in
# ``_t3_t6_build_ticker_features``, so the row-side has no NaN.
# We still scrub +/-inf defensively before LightGBM.
X_num_tr = gt_train[feat_cols].values.astype(np.float32)
X_num_tr = np.where(
np.isposinf(X_num_tr) | np.isneginf(X_num_tr),
np.nan, X_num_tr,
)
# Sparse one-hot of field id. Use the LOCKED fitted_fields set
# as categories so the predict path can encode every field
# (even those whose training pool was too small to fit; for
# those we override with the median anyway).
ohe = OneHotEncoder(
categories=[fitted_fields],
handle_unknown="ignore",
sparse_output=True,
dtype=np.float32,
)
field_arr_tr = gt_train["field"].values.reshape(-1, 1)
X_field_tr = ohe.fit_transform(field_arr_tr)
X_full_tr = sparse_hstack(
[csr_matrix(X_num_tr), X_field_tr], format="csr",
)
# LightGBM accepts sparse CSR. Use a single booster.
global_model = self._make_lgbm()
global_model.fit(X_full_tr, y_tr_t)
y_min = float(y_tr.min())
y_max = float(y_tr.max())
y_range = max(abs(y_max - y_min), abs(y_max) * 0.1, 1.0)
self._state = {
"ticker_feats": ticker_feats,
"feat_cols": feat_cols,
"fitted_fields": fitted_fields,
"median_fields": median_fields,
"model": global_model,
"scaler": global_scaler, # kept for compat (always None now)
"ohe": ohe,
"use_log": use_log,
"y_min": y_min,
"y_max": y_max,
"y_range": y_range,
}
self.fitted_fields = fitted_fields # public, per plan §1
def _predict_t3_t6(self, X: pd.DataFrame) -> pd.DataFrame:
"""Predict every (ticker, fiscal_year, fitted_field) cell with the
single shared LightGBM (numeric features + sparse field one-hot),
falling back to per-field medians for small-pool fields tagged at
fit time.
"""
from scipy.sparse import csr_matrix, hstack as sparse_hstack
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
if "ticker" not in X.columns or "fiscal_year" not in X.columns:
raise ValueError(
f"{self.task} predict: X must include 'ticker' and "
f"'fiscal_year'."
)
fitted_fields: list[str] = st["fitted_fields"]
median_fields: dict[str, float] = st["median_fields"]
feat_cols: list[str] = st["feat_cols"]
# Build test-side per-ticker features using the SAME recipe as fit,
# then align columns to the train feature schema.
test_feats, _ = self._t3_t6_build_ticker_features(X)
test_feats = test_feats.set_index("ticker")
for c in feat_cols:
if c not in test_feats.columns:
test_feats[c] = 0.0
test_feats = test_feats[feat_cols].fillna(0.0)
# One row per (test row × every fitted field) — long-form predict.
# We assemble the predict matrix as the cross-product of test rows
# and fitted fields, run a single batched .predict, then map back.
n_rows = len(X)
n_fields = len(fitted_fields)
rows: list[dict[str, Any]] = []
if n_rows == 0 or n_fields == 0:
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# Pre-fetch numeric features per test row.
ticker_arr = X["ticker"].astype(str).values
fy_arr = X["fiscal_year"].values
# For tickers absent from training-side ticker_feats the feature
# vector is zero (matches the legacy behaviour for unseen tickers).
zero_vec = np.zeros(len(feat_cols), dtype=np.float32)
feats_by_ticker: dict[str, np.ndarray] = {}
for t in set(ticker_arr.tolist()):
try:
v = test_feats.loc[t]
if isinstance(v, pd.DataFrame):
v = v.iloc[0]
feats_by_ticker[t] = np.asarray(
v.values, dtype=np.float32,
)
except KeyError:
feats_by_ticker[t] = zero_vec
# Decide which (row, field) cells get the model vs. a median fallback.
model = st["model"]
# Note: ``scaler`` slot exists in state for save/load compat but is
# always None now — LightGBM is scale-invariant so we dropped it.
ohe = st["ohe"]
use_log = bool(st["use_log"])
y_min = float(st["y_min"])
y_max = float(st["y_max"])
y_range = float(st["y_range"])
# Cache one prediction per unique (ticker, field) cell to avoid
# duplicating the model call across the same ticker repeated for
# multiple fiscal years.
unique_tickers = list(dict.fromkeys(ticker_arr.tolist()))
# Build the model batch only for fields with a fitted booster.
model_fields = (
[f for f in fitted_fields if f not in median_fields]
if model is not None else []
)
cell_pred: dict[tuple[str, str], float] = {}
if model is not None and model_fields and unique_tickers:
# Cross-product matrix: rows = (ticker × model_field) pairs.
# Per-ticker numerics are already imputed to 0 in
# ``_t3_t6_build_ticker_features`` (predict-side mirrors fit);
# we only scrub +/-inf defensively for LightGBM.
X_num = np.stack(
[feats_by_ticker[t] for t in unique_tickers], axis=0,
).astype(np.float32)
X_num = np.where(
np.isposinf(X_num) | np.isneginf(X_num),
np.nan, X_num,
)
# Repeat per model-field so the one-hot lookup aligns 1-to-1.
n_t = len(unique_tickers)
n_mf = len(model_fields)
X_num_rep = np.repeat(X_num, n_mf, axis=0)
field_arr = np.tile(
np.asarray(model_fields, dtype=object), n_t,
).reshape(-1, 1)
assert ohe is not None # set whenever model is set
X_field = ohe.transform(field_arr)
X_full = sparse_hstack(
[csr_matrix(X_num_rep), X_field], format="csr",
)
y_pred_t = np.asarray(model.predict(X_full))
if use_log:
y_pred = np.sign(y_pred_t) * np.expm1(np.abs(y_pred_t))
else:
y_pred = y_pred_t
y_pred = np.clip(y_pred, y_min - y_range, y_max + y_range)
# Re-shape into (n_t, n_mf) for cell-key indexing.
y_pred = y_pred.reshape(n_t, n_mf)
for ti, t in enumerate(unique_tickers):
for fi, f in enumerate(model_fields):
cell_pred[(t, f)] = float(y_pred[ti, fi])
for i in range(n_rows):
t = ticker_arr[i]
fy = fy_arr[i]
for field in fitted_fields:
if field in median_fields:
val = median_fields[field]
else:
val = cell_pred.get((t, field), 0.0)
rows.append({
"ticker": t,
"fiscal_year": fy,
"field": field,
"pred": float(val),
})
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# ── T4 — flat-lookback + event-type one-hot ───────────────────────────
@staticmethod
def _t4_flatten_lookback(lb_col: pd.Series) -> tuple[np.ndarray, int]:
"""Stack object-dtype ``lookback`` cells into ``(N, L*F)`` float32.
Each cell is a ``(L, F)`` ndarray. Empty / malformed cells are
replaced with zeros sized to the modal panel shape.
"""
arrays: list[np.ndarray] = []
for cell in lb_col.values:
if isinstance(cell, np.ndarray) and cell.ndim == 2:
arrays.append(cell.astype(np.float32))
if not arrays:
raise RuntimeError(
"T4: no usable lookback ndarrays in X['lookback']."
)
L = arrays[0].shape[0]
F = arrays[0].shape[1]
flat_rows: list[np.ndarray] = []
for cell in lb_col.values:
if isinstance(cell, np.ndarray) and cell.shape == (L, F):
flat_rows.append(cell.reshape(-1).astype(np.float32))
else:
flat_rows.append(np.zeros(L * F, dtype=np.float32))
flat = np.stack(flat_rows, axis=0)
return flat, L * F
def _fit_t4(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 fit: expected DataFrame X; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 fit: X must include 'lookback' and 'event_type' columns."
)
flat, n_lb_flat = self._t4_flatten_lookback(X["lookback"])
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# Preserve NaN for LightGBM; scrub only +/-inf.
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
y_arr = np.asarray(y, dtype=np.float32).ravel()
if y_arr.shape[0] != X_arr.shape[0]:
raise ValueError(
f"T4 fit: y/X length mismatch ({y_arr.shape[0]} vs "
f"{X_arr.shape[0]})."
)
model = self._make_lgbm()
model.fit(X_arr, y_arr)
self._state = {
"model": model,
"evt_columns": list(et_dummies.columns),
"n_lb_flat": int(n_lb_flat),
}
def _predict_t4(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 predict: expected DataFrame; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 predict: X must include 'lookback' and 'event_type'."
)
flat, _ = self._t4_flatten_lookback(X["lookback"])
# Align lookback flat-width to train (defensive — tolerate small
# column drift coming from a slightly-different feature panel).
if flat.shape[1] > st["n_lb_flat"]:
flat = flat[:, : st["n_lb_flat"]]
elif flat.shape[1] < st["n_lb_flat"]:
pad = np.zeros(
(flat.shape[0], st["n_lb_flat"] - flat.shape[1]),
dtype=np.float32,
)
flat = np.concatenate([flat, pad], axis=1)
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
for c in st["evt_columns"]:
if c not in et_dummies.columns:
et_dummies[c] = 0.0
et_dummies = et_dummies[st["evt_columns"]].fillna(0.0)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# Preserve NaN for LightGBM; scrub only +/-inf.
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
return st["model"].predict(X_arr).astype(np.float32)
# ── T7 — dual-output (rent, price) ────────────────────────────────────
@staticmethod
def _t7_first_col(
df: pd.DataFrame, candidates: tuple[str, ...],
) -> str | None:
"""Return the first column whose name (lowercased) contains any of
``candidates`` (substring match), else ``None``.
"""
for c in df.columns:
cl = c.lower()
if any(cand in cl for cand in candidates):
return c
return None
def _t7_build_features(
self, X: pd.DataFrame, *, fit: bool,
) -> tuple[pd.DataFrame, list[str], str | None]:
"""Build the property-feature frame; returns ``(X_feat, feat_cols,
prop_type_col)``.
Same numeric feature recipe as the legacy T7 baseline.
"""
df = X.copy()
feat_cols: list[str] = []
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
feat_cols.append(col)
prop_type_col = next(
(c for c in ("property_type", "propertyType", "type")
if c in df.columns),
None,
)
if prop_type_col:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(prop_dummies.columns)
if not feat_cols:
raise RuntimeError(
f"T7 {'fit' if fit else 'predict'}: no usable property features."
)
return df, feat_cols, prop_type_col
def _fit_t7(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 fit: expected DataFrame X; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 fit: X must include 'address'.")
df, feat_cols, prop_type_col = self._t7_build_features(X, fit=True)
# Targets: prefer rent / price columns already on X (canonical T7
# train carries them); fall back to a per-address merge with y.
rent_col = self._t7_first_col(df, ("rent",))
price_col = self._t7_first_col(df, ("price", "lastsaleprice"))
if isinstance(y, pd.DataFrame) and "address" in y.columns:
if rent_col is None and "rent" in y.columns:
df = df.merge(
y[["address", "rent"]], on="address", how="left",
)
rent_col = "rent"
if price_col is None and "price" in y.columns:
df = df.merge(
y[["address", "price"]], on="address", how="left",
)
price_col = "price"
if rent_col is None and price_col is None:
raise RuntimeError("T7 fit: no rent or price target found.")
# Preserve NaN for LightGBM's native missing-value handling;
# scrub only +/-inf (LightGBM rejects them but tolerates NaN).
X_feat = df[feat_cols].astype(np.float32)
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
models: dict[str, Any] = {}
for target_name, target_col in (("rent", rent_col), ("price", price_col)):
if target_col is None:
continue
y_all = pd.to_numeric(df[target_col], errors="coerce")
valid = y_all.notna() & (y_all > 0)
n_valid = int(valid.sum())
if n_valid < 1:
continue
X_tr = X_arr[valid.values]
y_tr = y_all.loc[valid].values.astype(np.float64)
if n_valid < 2:
# LightGBM rejects n<2; emit a constant-predictor (the single
# training value) so eval is well-defined. Real T7 trains
# have ~10k rows; this branch only triggers in micro-scale
# smoke runs where dedup-by-address leaves 1 row.
models[target_name] = ("constant", float(y_tr.mean()))
continue
m = self._make_log_pipeline()
m.fit(X_tr, y_tr)
models[target_name] = m
if not models:
raise RuntimeError(
f"T7 fit: insufficient training data "
f"(rent_col={rent_col!r}, price_col={price_col!r}, "
f"n_rows={len(df)}); need >=1 row with a positive target."
)
self._state = {
"feat_cols": feat_cols,
"prop_type_col": prop_type_col,
"models": models,
}
def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 predict: expected DataFrame; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 predict: X must include 'address'.")
df = X.copy()
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
prop_type_col = st["prop_type_col"]
if prop_type_col and prop_type_col in df.columns:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
X_feat = _align_columns(
df, st["feat_cols"], fillna=False,
).astype(np.float32)
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
out = pd.DataFrame({"address": X["address"].astype(str).values})
for target_name in ("rent", "price"):
model = st["models"].get(target_name)
if model is None:
out[f"pred_{target_name}"] = np.full(
len(X), np.nan, dtype=np.float32,
)
continue
if isinstance(model, tuple) and model[0] == "constant":
out[f"pred_{target_name}"] = np.full(
len(X), float(model[1]), dtype=np.float32,
)
continue
preds = model.predict(X_arr)
preds = np.clip(preds, 0.0, None)
out[f"pred_{target_name}"] = preds.astype(np.float32)
return out
# ── RandomForest variant ──────────────────────────────────────────────────
def _make_rf_estimator(
cfg: RandomForestConfig, *, seed: int,
) -> Any:
"""Build a fresh sklearn ``RandomForestRegressor`` from ``cfg``.
Lazy-imports sklearn so the import-time cost is only paid when the
classical/random_forest method is actually instantiated.
"""
from sklearn.ensemble import RandomForestRegressor
return RandomForestRegressor(
n_estimators=int(cfg.n_estimators),
max_depth=cfg.max_depth,
min_samples_leaf=int(cfg.min_samples_leaf),
n_jobs=int(cfg.n_jobs),
random_state=int(seed),
)
def _make_rf_log_pipeline(
cfg: RandomForestConfig, *, seed: int,
) -> Any:
"""RandomForest wrapped in a log1p/expm1 target transform.
Used by T2 / T5 / T7 (positive-target regression). Mirrors
:meth:`LightGBMRegressor._make_log_pipeline` but with sklearn's RF
as the regressor. RF is scale-invariant; no StandardScaler step.
"""
from sklearn.compose import TransformedTargetRegressor
return TransformedTargetRegressor(
regressor=_make_rf_estimator(cfg, seed=seed),
func=np.log1p,
inverse_func=np.expm1,
)
@register(
name="random_forest",
family="classical",
tasks=frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"}),
config_class=RandomForestConfig,
)
class RandomForestMethod(_JoblibSaveMixin, Method):
"""sklearn RandomForestRegressor with per-task private dispatch.
Mirrors :class:`LightGBMRegressor` per-task adapter shape (T1..T7) but
swaps the base estimator for ``sklearn.ensemble.RandomForestRegressor``.
Reuses the module-level helpers (``_flatten_panel``, ``_align_columns``,
``_numeric_feature_cols``, plus the ``_t3_t6_build_ticker_features`` /
``_t7_build_features`` helpers from :class:`LightGBMRegressor`).
Key behaviour differences from LightGBM:
* sklearn RandomForest does NOT handle NaN inputs natively; every fit /
predict path zero-fills NaN before calling the estimator.
* sklearn RandomForest does NOT accept sparse CSR matrices on the T3/T6
ensemble path; we densify with ``.toarray()`` before fit/predict
(acceptable for the small-pool T3/T6 train sets).
* The class is named ``RandomForestMethod`` (not
``RandomForestRegressor``) to avoid the name collision with
``sklearn.ensemble.RandomForestRegressor``.
"""
name: ClassVar[str] = "random_forest"
family: ClassVar[str] = "classical"
tasks: ClassVar[frozenset[str]] = frozenset(
{"T1", "T2", "T3", "T4", "T5", "T6", "T7"}
)
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: RandomForestConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"RandomForestMethod: unsupported task {task!r}; "
f"supported = {sorted(self.tasks)}"
)
self.task = task
if config is None:
config = (
RandomForestConfig(**kwargs) if kwargs else RandomForestConfig()
)
elif kwargs:
raise ValueError(
"RandomForestMethod: pass either ``config=`` or kwargs, not both"
)
self.config = config
self._state: dict[str, Any] = {}
# ── public API ────────────────────────────────────────────────────────
def fit(self, X: Any, y: Any, *, seed: int = 42) -> "RandomForestMethod":
self._seed = int(seed)
if self.task == "T1":
self._fit_t1(X, y)
elif self.task in ("T2", "T5"):
self._fit_t2_t5(X, y)
elif self.task in ("T3", "T6"):
self._fit_t3_t6(X, y)
elif self.task == "T4":
self._fit_t4(X, y)
elif self.task == "T7":
self._fit_t7(X, y)
else: # pragma: no cover -- gated by __init__
raise ValueError(self.task)
return self
def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
if not self._state:
raise RuntimeError(
"RandomForestMethod: call .fit(X, y) before .predict()."
)
if self.task == "T1":
return self._predict_t1(X)
if self.task in ("T2", "T5"):
return self._predict_t2_t5(X)
if self.task in ("T3", "T6"):
return self._predict_t3_t6(X)
if self.task == "T4":
return self._predict_t4(X)
if self.task == "T7":
return self._predict_t7(X)
raise ValueError(self.task) # pragma: no cover
def lib_versions(self) -> dict[str, str]:
return _classical_lib_versions()
@classmethod
def default_config(cls) -> RandomForestConfig:
return RandomForestConfig()
# ── helpers (re-use LightGBM's T3/T6 + T7 feature builders) ───────────
def _t3_t6_build_ticker_features(
self, X: pd.DataFrame,
) -> tuple[pd.DataFrame, list[str]]:
return LightGBMRegressor._t3_t6_build_ticker_features(self, X)
def _t7_build_features(
self, X: pd.DataFrame, *, fit: bool,
) -> tuple[pd.DataFrame, list[str], str | None]:
return LightGBMRegressor._t7_build_features(self, X, fit=fit)
@staticmethod
def _t4_flatten_lookback(lb_col: pd.Series) -> tuple[np.ndarray, int]:
return LightGBMRegressor._t4_flatten_lookback(lb_col)
@staticmethod
def _t7_first_col(
df: pd.DataFrame, candidates: tuple[str, ...],
) -> str | None:
return LightGBMRegressor._t7_first_col(df, candidates)
# ── T1 — multi-output regression on per-window log-returns ────────────
def _fit_t1(self, X: np.ndarray, y: np.ndarray) -> None:
"""Multi-output log-return regression; mirrors LightGBM T1.
sklearn RandomForest natively supports multi-output targets — fit
ONE forest with ``y.shape == (N, horizon)`` rather than wrapping in
``MultiOutputRegressor`` (which trains horizon-many forests
sequentially). The ONE-forest path is ~horizon× faster and matches
what sklearn's reference docs recommend for vector-valued targets.
sklearn RandomForest does NOT handle NaN natively, so we zero-fill
any NaN cells before fitting (in addition to scrubbing +/-inf).
"""
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 fit: expected ndarray X (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
if not isinstance(y, np.ndarray) or y.ndim != 2:
raise ValueError(
f"T1 fit: expected ndarray y (N, horizon); got "
f"{type(y).__name__} {getattr(y, 'shape', '?')}"
)
if y.shape[0] != X.shape[0]:
raise ValueError(
f"T1 fit: y/X length mismatch ({y.shape[0]} vs {X.shape[0]})."
)
horizon = int(y.shape[1])
close_idx = 0
c = X[:, -1, close_idx].astype(np.float64)
y_f = y.astype(np.float64)
keep = (
np.isfinite(c) & (c > 0.0) &
np.isfinite(y_f).all(axis=1) & (y_f > 0.0).all(axis=1)
)
n_total = int(X.shape[0])
n_keep = int(keep.sum())
if n_keep < 1:
raise RuntimeError(
f"T1 fit: only {n_keep}/{n_total} training windows have "
"positive finite close + horizon prices; cannot fit "
"log-return target."
)
X_kept = X[keep]
c_kept = c[keep]
y_log = np.log(y_f[keep] / c_kept[:, None]).astype(np.float32)
X_flat = _flatten_panel(
X_kept, add_rolling_close=True, close_idx=close_idx,
)
# Scrub +/-inf AND zero-fill NaN — sklearn RF rejects all non-finite.
X_flat = np.nan_to_num(
X_flat, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
# NATIVE multi-output: one RF tree set predicts all horizon steps.
model = _make_rf_estimator(self.config, seed=self._seed)
model.fit(X_flat, y_log)
self._state = {
"model": model,
"close_idx": close_idx,
"horizon": horizon,
"n_features_flat": X_flat.shape[1],
"n_train_total": n_total,
"n_train_kept": n_keep,
"log_clip": 2.0,
}
self._horizon = horizon
def _predict_t1(self, X: np.ndarray) -> np.ndarray:
st = self._state
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 predict: expected ndarray (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
close_idx = int(st["close_idx"])
c_test = X[:, -1, close_idx].astype(np.float64)
c_safe = np.where(np.isfinite(c_test) & (c_test > 0.0), c_test, np.nan)
X_flat = _flatten_panel(
X, add_rolling_close=True, close_idx=close_idx,
)
# Zero-fill NaN and scrub +/-inf — sklearn RF cannot handle them.
X_flat = np.nan_to_num(
X_flat, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
n_train_cols = st["n_features_flat"]
if X_flat.shape[1] > n_train_cols:
X_flat = X_flat[:, :n_train_cols]
elif X_flat.shape[1] < n_train_cols:
pad = np.zeros(
(X_flat.shape[0], n_train_cols - X_flat.shape[1]),
dtype=np.float32,
)
X_flat = np.concatenate([X_flat, pad], axis=1)
log_pred = st["model"].predict(X_flat).astype(np.float64)
if log_pred.ndim == 1:
log_pred = log_pred.reshape(-1, st["horizon"])
clip = float(st.get("log_clip", 2.0))
log_pred = np.clip(log_pred, -clip, clip)
out = c_safe[:, None] * np.exp(log_pred)
bad = ~np.isfinite(out)
if bad.any():
tile = np.broadcast_to(c_test[:, None], out.shape).astype(np.float64)
out = np.where(bad, tile, out)
return out.astype(np.float32)
# ── T2 / T5 — log-target regression ───────────────────────────────────
def _fit_t2_t5(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if self.task == "T2":
prefixes: tuple[str, ...] = ("stmt_", "derived_", "fred_", "eia_")
else:
prefixes = ("stmt_", "fred_", "eia_")
df = X.copy()
feat_cols = [
c for c in _numeric_feature_cols(df, prefixes)
if c not in {"derived_market_cap", "actual_market_cap"}
]
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(sec_dummies.columns)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(ind_dummies.columns)
X_feat = df[feat_cols].astype(np.float32)
y_arr = pd.to_numeric(
pd.Series(np.asarray(y).ravel()), errors="coerce",
).astype(np.float64)
valid = y_arr.notna() & (y_arr > 0)
X_feat = X_feat.loc[valid.values]
y_arr = y_arr.loc[valid.values]
if X_feat.empty:
raise RuntimeError(
f"{self.task} fit: no rows with positive market_cap after drop."
)
# sklearn RF rejects NaN/inf — zero-fill before fit.
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
model = _make_rf_log_pipeline(self.config, seed=self._seed)
model.fit(X_arr, y_arr.values)
self._state = {
"model": model,
"feat_cols": feat_cols,
"prefixes": prefixes,
}
def _predict_t2_t5(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
df = X.copy()
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
# Zero-fill NaN at align time (RF can't handle them); also scrub
# any straggler +/-inf below.
X_feat = _align_columns(
df, st["feat_cols"], fillna=True,
).astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
preds = st["model"].predict(X_arr)
preds = np.clip(preds, 0.0, None)
return preds.astype(np.float32)
# ── T3 / T6 — per-field booster ensemble (sparse field one-hot) ───────
def _fit_t3_t6(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
"""Single RandomForest with per-(ticker, fiscal_year) numeric
features + one-hot of ``field``. sklearn RF does NOT accept sparse
CSR — we densify with ``.toarray()`` before fit (acceptable for
the small-pool T3/T6 train sets).
"""
from sklearn.preprocessing import OneHotEncoder
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected long-form DataFrame y; got "
f"{type(y).__name__}"
)
for col in ("ticker", "field", "value"):
if col not in y.columns:
raise ValueError(
f"{self.task} fit: y missing required column {col!r}"
)
ticker_feats, feat_cols = self._t3_t6_build_ticker_features(X)
fitted_fields: list[str] = sorted(
str(f) for f in y["field"].astype(str).unique()
)
gt = y.copy()
gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce")
gt["field"] = gt["field"].astype(str)
gt = gt.merge(ticker_feats, on="ticker", how="left").fillna(0.0)
gt = gt.dropna(subset=["value_num"])
per_field_count = gt.groupby("field").size().to_dict()
median_fields: dict[str, float] = {}
small_field_set: set[str] = set()
for field in fitted_fields:
cnt = int(per_field_count.get(field, 0))
if cnt < 5:
sub = gt[gt["field"] == field]
med = float(sub["value_num"].median()) if not sub.empty else 0.0
median_fields[field] = med
small_field_set.add(field)
train_mask = ~gt["field"].isin(small_field_set)
gt_train = gt[train_mask]
global_model = None
global_scaler = None
use_log = False
y_min = 0.0
y_max = 0.0
y_range = 1.0
ohe: OneHotEncoder | None = None
if not gt_train.empty:
y_tr = gt_train["value_num"].values.astype(np.float64)
nz = y_tr[y_tr != 0]
if nz.size > 0:
use_log = float(np.median(np.abs(nz))) > 1000
y_tr_t = (
np.sign(y_tr) * np.log1p(np.abs(y_tr)) if use_log else y_tr
)
X_num_tr = gt_train[feat_cols].values.astype(np.float32)
# sklearn RF rejects NaN/inf — zero-fill.
X_num_tr = np.nan_to_num(
X_num_tr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
ohe = OneHotEncoder(
categories=[fitted_fields],
handle_unknown="ignore",
sparse_output=True,
dtype=np.float32,
)
field_arr_tr = gt_train["field"].values.reshape(-1, 1)
X_field_tr = ohe.fit_transform(field_arr_tr).toarray().astype(np.float32)
X_full_tr = np.concatenate([X_num_tr, X_field_tr], axis=1)
global_model = _make_rf_estimator(self.config, seed=self._seed)
global_model.fit(X_full_tr, y_tr_t)
y_min = float(y_tr.min())
y_max = float(y_tr.max())
y_range = max(abs(y_max - y_min), abs(y_max) * 0.1, 1.0)
self._state = {
"ticker_feats": ticker_feats,
"feat_cols": feat_cols,
"fitted_fields": fitted_fields,
"median_fields": median_fields,
"model": global_model,
"scaler": global_scaler,
"ohe": ohe,
"use_log": use_log,
"y_min": y_min,
"y_max": y_max,
"y_range": y_range,
}
self.fitted_fields = fitted_fields
def _predict_t3_t6(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
if "ticker" not in X.columns or "fiscal_year" not in X.columns:
raise ValueError(
f"{self.task} predict: X must include 'ticker' and "
f"'fiscal_year'."
)
fitted_fields: list[str] = st["fitted_fields"]
median_fields: dict[str, float] = st["median_fields"]
feat_cols: list[str] = st["feat_cols"]
test_feats, _ = self._t3_t6_build_ticker_features(X)
test_feats = test_feats.set_index("ticker")
for c in feat_cols:
if c not in test_feats.columns:
test_feats[c] = 0.0
test_feats = test_feats[feat_cols].fillna(0.0)
n_rows = len(X)
n_fields = len(fitted_fields)
rows: list[dict[str, Any]] = []
if n_rows == 0 or n_fields == 0:
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
ticker_arr = X["ticker"].astype(str).values
fy_arr = X["fiscal_year"].values
zero_vec = np.zeros(len(feat_cols), dtype=np.float32)
feats_by_ticker: dict[str, np.ndarray] = {}
for t in set(ticker_arr.tolist()):
try:
v = test_feats.loc[t]
if isinstance(v, pd.DataFrame):
v = v.iloc[0]
feats_by_ticker[t] = np.asarray(
v.values, dtype=np.float32,
)
except KeyError:
feats_by_ticker[t] = zero_vec
model = st["model"]
ohe = st["ohe"]
use_log = bool(st["use_log"])
y_min = float(st["y_min"])
y_max = float(st["y_max"])
y_range = float(st["y_range"])
unique_tickers = list(dict.fromkeys(ticker_arr.tolist()))
model_fields = (
[f for f in fitted_fields if f not in median_fields]
if model is not None else []
)
cell_pred: dict[tuple[str, str], float] = {}
if model is not None and model_fields and unique_tickers:
X_num = np.stack(
[feats_by_ticker[t] for t in unique_tickers], axis=0,
).astype(np.float32)
X_num = np.nan_to_num(
X_num, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
n_t = len(unique_tickers)
n_mf = len(model_fields)
X_num_rep = np.repeat(X_num, n_mf, axis=0)
field_arr = np.tile(
np.asarray(model_fields, dtype=object), n_t,
).reshape(-1, 1)
assert ohe is not None
X_field = ohe.transform(field_arr).toarray().astype(np.float32)
X_full = np.concatenate([X_num_rep, X_field], axis=1)
y_pred_t = np.asarray(model.predict(X_full))
if use_log:
y_pred = np.sign(y_pred_t) * np.expm1(np.abs(y_pred_t))
else:
y_pred = y_pred_t
y_pred = np.clip(y_pred, y_min - y_range, y_max + y_range)
y_pred = y_pred.reshape(n_t, n_mf)
for ti, t in enumerate(unique_tickers):
for fi, f in enumerate(model_fields):
cell_pred[(t, f)] = float(y_pred[ti, fi])
for i in range(n_rows):
t = ticker_arr[i]
fy = fy_arr[i]
for field in fitted_fields:
if field in median_fields:
val = median_fields[field]
else:
val = cell_pred.get((t, field), 0.0)
rows.append({
"ticker": t,
"fiscal_year": fy,
"field": field,
"pred": float(val),
})
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# ── T4 — flat-lookback + event-type one-hot ───────────────────────────
def _fit_t4(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 fit: expected DataFrame X; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 fit: X must include 'lookback' and 'event_type' columns."
)
flat, n_lb_flat = self._t4_flatten_lookback(X["lookback"])
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# sklearn RF rejects NaN/inf — zero-fill.
X_arr = np.nan_to_num(
X_arr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
y_arr = np.asarray(y, dtype=np.float32).ravel()
if y_arr.shape[0] != X_arr.shape[0]:
raise ValueError(
f"T4 fit: y/X length mismatch ({y_arr.shape[0]} vs "
f"{X_arr.shape[0]})."
)
model = _make_rf_estimator(self.config, seed=self._seed)
model.fit(X_arr, y_arr)
self._state = {
"model": model,
"evt_columns": list(et_dummies.columns),
"n_lb_flat": int(n_lb_flat),
}
def _predict_t4(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 predict: expected DataFrame; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 predict: X must include 'lookback' and 'event_type'."
)
flat, _ = self._t4_flatten_lookback(X["lookback"])
if flat.shape[1] > st["n_lb_flat"]:
flat = flat[:, : st["n_lb_flat"]]
elif flat.shape[1] < st["n_lb_flat"]:
pad = np.zeros(
(flat.shape[0], st["n_lb_flat"] - flat.shape[1]),
dtype=np.float32,
)
flat = np.concatenate([flat, pad], axis=1)
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
for c in st["evt_columns"]:
if c not in et_dummies.columns:
et_dummies[c] = 0.0
et_dummies = et_dummies[st["evt_columns"]].fillna(0.0)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
X_arr = np.nan_to_num(
X_arr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
return st["model"].predict(X_arr).astype(np.float32)
# ── T7 — dual-output (rent, price) ────────────────────────────────────
def _fit_t7(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 fit: expected DataFrame X; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 fit: X must include 'address'.")
df, feat_cols, prop_type_col = self._t7_build_features(X, fit=True)
rent_col = self._t7_first_col(df, ("rent",))
price_col = self._t7_first_col(df, ("price", "lastsaleprice"))
if isinstance(y, pd.DataFrame) and "address" in y.columns:
if rent_col is None and "rent" in y.columns:
df = df.merge(
y[["address", "rent"]], on="address", how="left",
)
rent_col = "rent"
if price_col is None and "price" in y.columns:
df = df.merge(
y[["address", "price"]], on="address", how="left",
)
price_col = "price"
if rent_col is None and price_col is None:
raise RuntimeError("T7 fit: no rent or price target found.")
# sklearn RF rejects NaN/inf — zero-fill.
X_feat = df[feat_cols].astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
models: dict[str, Any] = {}
for target_name, target_col in (("rent", rent_col), ("price", price_col)):
if target_col is None:
continue
y_all = pd.to_numeric(df[target_col], errors="coerce")
valid = y_all.notna() & (y_all > 0)
n_valid = int(valid.sum())
if n_valid < 1:
continue
X_tr = X_arr[valid.values]
y_tr = y_all.loc[valid].values.astype(np.float64)
if n_valid < 2:
# RandomForest tolerates n=1 but eval is degenerate; emit a
# constant predictor to match LightGBM's degenerate-case
# behaviour exactly (smoke-run path only).
models[target_name] = ("constant", float(y_tr.mean()))
continue
m = _make_rf_log_pipeline(self.config, seed=self._seed)
m.fit(X_tr, y_tr)
models[target_name] = m
if not models:
raise RuntimeError(
f"T7 fit: insufficient training data "
f"(rent_col={rent_col!r}, price_col={price_col!r}, "
f"n_rows={len(df)}); need >=1 row with a positive target."
)
self._state = {
"feat_cols": feat_cols,
"prop_type_col": prop_type_col,
"models": models,
}
def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 predict: expected DataFrame; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 predict: X must include 'address'.")
df = X.copy()
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
prop_type_col = st["prop_type_col"]
if prop_type_col and prop_type_col in df.columns:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
# Zero-fill NaN at align time and scrub stragglers — RF rejects them.
X_feat = _align_columns(
df, st["feat_cols"], fillna=True,
).astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
out = pd.DataFrame({"address": X["address"].astype(str).values})
for target_name in ("rent", "price"):
model = st["models"].get(target_name)
if model is None:
out[f"pred_{target_name}"] = np.full(
len(X), np.nan, dtype=np.float32,
)
continue
if isinstance(model, tuple) and model[0] == "constant":
out[f"pred_{target_name}"] = np.full(
len(X), float(model[1]), dtype=np.float32,
)
continue
preds = model.predict(X_arr)
preds = np.clip(preds, 0.0, None)
out[f"pred_{target_name}"] = preds.astype(np.float32)
return out
|