RegimeDetector¶
Defined in fynance.features.regime
- class RegimeDetector(n_regimes=3, w=21, period=252, seed=0)[source]
Bases:
objectCausal market-regime detector (fit on the past, assign online).
Unlike
detect_regimes(which clusters in-sample and therefore peeks at the whole series), this fits k-means on a training slice only and assigns any later point to the nearest training centroid — so labels are a strictly causal feature usable in a backtest. Labels are ordered by increasing mean volatility (0 = calmest), likedetect_regimes.- Parameters:
- n_regimesint
Number of regimes (clusters).
- wint
Rolling window for the features.
- periodint
Annualization factor for the volatility feature.
- seedint
Seed for the k-means initialization.
Examples
>>> import numpy as np >>> from fynance.features import RegimeDetector >>> rng = np.random.default_rng(0) >>> p = 100 * np.exp(np.cumsum(rng.standard_normal(400) * 0.01)) >>> det = RegimeDetector(n_regimes=2, w=10).fit(p[:300]) >>> labels = det.predict(p) >>> labels.shape, set(np.unique(labels)) <= {0, 1} ((400,), True)
- fit(X)[source]
Fit k-means on the training series
X(past only).
- fit_predict(X)[source]
Convenience:
fitthenpredicton the same series.
- predict(X)[source]
Assign each point of
Xto the nearest training centroid.