Robustness and regimes
Test whether a result survives nearby parameters, other periods, other universes and different market regimes, and read what the evidence says about fragility.
A backtest reports one number at one parameter setting, on one sample, over one universe. The question that matters is whether that number is a feature of the idea or an accident of the choices: a lookback that happens to sit on a lucky peak, a stretch of years that carries the whole profit, a universe that excludes the instruments that would have hurt. Robustness analysis re-evaluates the result across a neighbourhood and reports how much it moves.
lacuna.robustness does this along three axes: perturbing parameters (continuous_perturbation), splitting time (subperiod_analysis) and changing the instruments (universe_perturbation). lacuna.regime adds a fourth: conditioning the result on the state of the market (quantile_regimes, regime_analysis). None of these runs your strategy. You supply the evaluation. Only continuous_perturbation chooses the points to evaluate; subperiods and universes are exactly the ones you declare. Lacuna records every evaluation including the failures, and summarises the spread. Draws that are rejected before evaluation are counted in the rejections table and are not recorded as attempts.
The evaluator contract
Each robustness function takes an evaluate callable. It receives one point (a parameter dictionary, a Subperiod or a UniverseScenario), does your analysis, and returns an lc.AnalysisResult whose metrics hold finite numbers. You name the metric to optimise with objective.
Three things follow from this.
- Lacuna never slices your data. The subperiod evaluator must itself keep the rows in
[start, end), and the universe evaluator must keep theinstrument_ids. The windows and universes Lacuna reports are exactly the ones you declared; whether your evaluator honoured them is yours to verify. - The identity arguments are declarations.
sample_idnames the data sample,code_idthe version of your evaluator code (a git hash, for example),evaluator_nameandevaluator_versionthe method. Lacuna folds them into fingerprints and the experiment registry but does not hash your data or inspect your code, so choose ids that change whenever the data or code does. - A failing evaluation is information. With
failure_policy="record", the default, an exception from the evaluator, a non-finite metric, or a return value that is not anAnalysisResultis stored as a failed row with its exception class name and counted. OnlyKeyboardInterruptandSystemExitpropagate. With"raise"the first failure propagates. Medians, fractions and dispersions are computed over the successful evaluations only. A failed point is not hidden: it stays in the table withstatus="failed", is counted (failed_evaluations,failed_periods,failed_universes), and adds aPERTURBATION_EVALUATION_FAILURES,SUBPERIOD_EVALUATION_FAILURESorUNIVERSE_EVALUATION_FAILURESwarning. Check those before reading a summary, because a summary over the survivors can look stable when the failures were the bad neighbours.
A first example
A one-instrument strategy goes long when the trailing mean return over lookback days exceeds threshold, short when it is below minus threshold, and is flat otherwise. The returns contain a persistent drift that exists only in the first half of the sample, so the strategy has real edge for a while and then none.
from datetime import date, timedelta
import lacuna as lc
import numpy as np
import polars as pl
from lacuna.robustness import PerturbationSpec, Subperiod, UniverseScenario
rng = np.random.default_rng(11)
n = 600
weekdays = (date(2023, 1, 2) + timedelta(days=k) for k in range(900))
days = [day for day in weekdays if day.weekday() < 5][:n]
drift = np.zeros(n)
for t in range(1, n):
drift[t] = 0.95 * drift[t - 1] + rng.normal(0, 0.0004)
drift[300:] = 0.0
series = pl.DataFrame({"time": days, "ret": drift + rng.normal(0, 0.01, n)})
def strategy_pnl(returns, lookback, threshold):
r = returns.to_numpy()
position = np.zeros(len(r))
for t in range(int(lookback), len(r)):
mean = r[t - int(lookback) : t].mean()
position[t] = 1.0 if mean > threshold else (-1.0 if mean < -threshold else 0.0)
return position * r
def summarize(pnl):
sd = pnl.std(ddof=1)
sharpe = float(pnl.mean() / sd * np.sqrt(252)) if sd > 0 else 0.0
return lc.AnalysisResult(
metadata=lc.ResultMetadata(method="docs.sharpe", input_fingerprint="synthetic-v1"),
metrics={"sharpe": sharpe, "n_obs": len(pnl), "total_pnl": float(pnl.sum())},
)
def evaluate(parameters):
return summarize(strategy_pnl(series["ret"], parameters["lookback"], parameters["threshold"])) summarize is the evaluator’s return value: a result carrying sharpe, the observation count and the total profit. Any AnalysisResult works, including one returned by a Lacuna function.
Parameter perturbation
A parameter search picks the best point on a grid. The winner of that search is biased upward, and what you want to know is how the strategy behaves around it. continuous_perturbation draws random points near the selected values, evaluates each one, and summarises the objective.
First pick a winner from a grid, then perturb around it.
grid = [(lookback, threshold) for lookback in range(5, 61, 5) for threshold in (0.0, 0.0005, 0.001)]
scores = {point: evaluate({"lookback": point[0], "threshold": point[1]}).metrics["sharpe"] for point in grid}
best = max(scores, key=scores.get)
print(best, round(scores[best], 3))
result = lc.robustness.continuous_perturbation(
evaluate,
selected_parameters={"lookback": best[0], "threshold": best[1]},
perturbations={
"lookback": PerturbationSpec(distribution="lognormal", scale=0.3, lower=3, integer=True),
"threshold": PerturbationSpec(distribution="uniform", scale=0.0005, lower=0.0),
},
objective="sharpe",
evaluator_name="docs.momentum",
sample_id="series-v1",
code_id="docs-example-1",
draws=200,
seed=7,
evidence_threshold=0.0,
)
keys = ("accepted_samples", "rejection_rate", "objective_median", "objective_dispersion", "positive_fraction", "passing_fraction")
print({key: round(result.metrics[key], 3) for key in keys})
print([(f.code, f.state.value) for f in result.findings]) (5, 0.0) 0.995
{'accepted_samples': 200, 'rejection_rate': 0.485, 'objective_median': 0.772, 'objective_dispersion': 0.178, 'positive_fraction': 1.0, 'passing_fraction': 1.0}
[('PERTURBATION_REPRODUCIBLE', 'PASS')] The grid winner scored 0.995, and the median over 200 nearby points is 0.77. The gap shows how sensitive the result is to the exact setting: the winner sits above its neighbours. It is not out-of-sample performance and not a correction for selection bias, because every neighbour is evaluated on the same data that picked the winner. The draws are also dependent, correlated through the same series, so 200 draws are not 200 independent confirmations. Within this neighbourhood the strategy stays profitable at every neighbour (positive_fraction is 1.0), so the sign of the result is stable even though its size is not.
The rejection rate of 0.485 comes almost entirely from threshold. The winner’s threshold is 0.0, which is already the lower bound, so about half of the symmetric uniform draws are negative and are rejected. The lookback bound rejects about 1% of draws on its own (run alone, the two parameters give rejection rates of 0.005 and 0.483). The rate is slightly under the 0.5 level that triggers a warning. A winner sitting on a bound of the grid, as both parameters do here, is a sign the search range may be too narrow.
How draws are made
For each perturbed parameter with selected value and spec scale :
So scale is in the parameter’s own units for normal and uniform draws, and is a multiplicative, log-scale spread for lognormal draws (a scale of 0.3 moves a value by roughly 30%). Lognormal needs a positive selected value. After sampling, integer=True rounds to the nearest integer (halves go to the even integer), and then the bounds apply: a draw outside lower or upper is rejected and redrawn, not clipped to the bound. Clipping would pile draws on the boundary. Rejection truncates the distribution instead.
Parameters you do not list in perturbations stay at their selected_parameters values, and parameters are drawn in sorted name order, independently of each other, from a generator seeded with seed. The same seed and inputs give the same draws. Perturbations are independent: there is no way to correlate two parameters.
The selected point itself is not evaluated. If you want it in the comparison, evaluate it yourself.
Constraints
Some parameter pairs are invalid, such as a fast window longer than the slow one. A constraint is a function from the proposed parameter dictionary to bool. A draw for which it returns False is rejected and redrawn. A constraint that returns anything other than a bool raises a DataContractError. A constraint that raises an exception is counted as a constraint_error rejection under failure_policy="record" and propagates under "raise". A constraint must come with a constraint_name, which is recorded so the constraint’s identity travels with the result.
constrained = lc.robustness.continuous_perturbation(
evaluate,
selected_parameters={"lookback": best[0], "threshold": best[1]},
perturbations={"lookback": PerturbationSpec(distribution="uniform", scale=10.0, lower=3.0, integer=True)},
objective="sharpe",
evaluator_name="docs.momentum",
sample_id="series-v1",
code_id="docs-example-1",
draws=50,
seed=7,
constraint=lambda parameters: parameters["lookback"] >= 8,
constraint_name="lookback_at_least_8:v1",
)
print(constrained.table("rejections"))
print(constrained.metrics["attempted_samples"], constrained.metrics["accepted_samples"])
print([(f.code, f.state.value) for f in constrained.findings]) [{'reason': 'bounds', 'count': 52, 'fraction_of_attempts': 0.3795620437956204}, {'reason': 'constraint', 'count': 35, 'fraction_of_attempts': 0.25547445255474455}]
137 50
[('PERTURBATION_HIGH_REJECTION_RATE', 'WARN'), ('PERTURBATION_REPRODUCIBLE', 'PASS')] Sampling continues until draws points are accepted or max_attempts (by default 100 * draws) draws have been tried. If the budget runs out first, the result carries PERTURBATION_ACCEPTANCE_SHORTFALL, a FAIL. If more than half of all attempts were rejected, it carries PERTURBATION_HIGH_REJECTION_RATE: the evidence then describes a narrow feasible region and should be read that way. The rejections table breaks rejections down by reason (bounds, constraint, constraint_error). In the example above, 137 attempts were needed to accept 50 draws, and the high-rejection warning fires.
Reading the result
| Metric | What it tells you |
|---|---|
accepted_samples, successful_evaluations, failed_evaluations | How many points were evaluated and how many of those failed. |
rejection_rate | The share of attempted draws rejected by bounds or the constraint. |
objective_median, objective_dispersion | The centre and the sample standard deviation (ddof 1) of the objective over successful evaluations. |
positive_fraction | The share of successful evaluations with an objective above zero. It always means above zero, whatever direction is. |
passing_fraction | The share that meets evidence_threshold: at least the threshold when direction="maximize", at most when "minimize". None without a threshold. |
The perturbations table has one row per accepted draw: the full parameter set, the objective, status ("completed" or "failed"), and the exception class name for failures. A median near the selected value with small dispersion suggests a plateau. A median far below it, or a passing_fraction well under one, suggests the selected point sat on a peak. A uniformly weak region looks the same way, so read the level of the objective as well as its spread, and remember the neighbours share the winner’s data.
Pass an ExperimentRegistry as registry to record every accepted evaluation as an attempt, including failures, so the perturbation points count toward your total number of trials. Rejected draws are never evaluated and are not recorded. See Experiments.
registry = lc.ExperimentRegistry("perturbation-demo")
lc.robustness.continuous_perturbation(
evaluate,
selected_parameters={"lookback": 20, "threshold": 0.0005},
perturbations={"threshold": PerturbationSpec(distribution="uniform", scale=0.0004, lower=0.0)},
objective="sharpe",
evaluator_name="docs.momentum",
sample_id="series-v1",
code_id="docs-example-1",
draws=10,
seed=1,
registry=registry,
)
print(len(registry.attempts())) 10 Perturbation evidence is local. It describes the declared distributions and constraints and says nothing about parameter values far from them.
Subperiods
subperiod_analysis evaluates your strategy on windows you declare and measures how consistent the result is across them. Declare the windows before you look at the results; windows chosen after seeing which years were good are not evidence of stability.
A Subperiod is a half-open window [start, end) with a name and a sample_id. start and end must be the same type (both dates or both timezone-aware datetimes), and start must be before end. Names and sample ids must be unique across the periods you pass.
bounds = [date(2023, 1, 1), date(2023, 7, 1), date(2024, 1, 1), date(2024, 7, 1), date(2025, 1, 1), date(2025, 7, 1)]
periods = [
Subperiod(name=f"H{i + 1}", start=start, end=end, sample_id=f"series-v1:{start}:{end}")
for i, (start, end) in enumerate(zip(bounds[:-1], bounds[1:]))
]
def evaluate_period(period):
window = series.filter((pl.col("time") >= period.start) & (pl.col("time") < period.end))
return summarize(strategy_pnl(window["ret"], 20, 0.0))
stability = lc.robustness.subperiod_analysis(
evaluate_period,
periods=periods,
objective="sharpe",
sample_count_metric="n_obs",
outcome_metric="total_pnl",
evaluator_name="docs.momentum",
code_id="docs-example-1",
)
rows = pl.DataFrame(stability.table("subperiods")).select("name", "objective", "sample_count", "outcome")
print(rows.with_columns(pl.col("objective", "outcome").round(3)))
keys = ("sign_consistency", "worst_objective", "objective_trend_per_period", "top_absolute_outcome_share")
print({key: round(stability.metrics[key], 3) for key in keys})
print([(f.code, f.state.value) for f in stability.findings]) shape: (5, 4)
┌──────┬───────────┬──────────────┬─────────┐
│ name ┆ objective ┆ sample_count ┆ outcome │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ i64 ┆ f64 │
╞══════╪═══════════╪══════════════╪═════════╡
│ H1 ┆ 0.043 ┆ 130 ┆ 0.003 │
│ H2 ┆ 0.702 ┆ 130 ┆ 0.056 │
│ H3 ┆ 1.591 ┆ 130 ┆ 0.129 │
│ H4 ┆ -0.294 ┆ 132 ┆ -0.023 │
│ H5 ┆ -1.801 ┆ 78 ┆ -0.075 │
└──────┴───────────┴──────────────┴─────────┘
{'sign_consistency': 0.6, 'worst_objective': -1.801, 'objective_trend_per_period': -0.469, 'top_absolute_outcome_share': 0.449}
[('SUBPERIOD_SIGN_INSTABILITY', 'WARN')] The Sharpe is positive for the first three half-years and negative after. Three of the five periods share the positive sign, so sign_consistency is 0.6, below the 0.8 threshold, and the result carries SUBPERIOD_SIGN_INSTABILITY. The trend is about -0.47 Sharpe per period. No single period supplies 60% of the absolute profit (the largest supplies 45%), so there is no concentration finding. The 78-observation last period is shorter than the others; sample_count is there so a reader sees that.
Each period’s evaluator must return the objective and a sample_count_metric, a non-negative whole number such as the number of observations. The count is carried into the table so a Sharpe from 78 observations is not mistaken for one from 130. In this example the count includes each window’s 20 warm-up rows, during which the strategy is flat, so every period’s Sharpe is diluted by those zeros. Report the count your evaluator actually used. Optionally it returns an outcome_metric (profit, for concentration) and a pair of confidence_lower_metric and confidence_upper_metric that you name together; these are passed through to the table.
| Metric | What it tells you |
|---|---|
positive_fraction | The share of successful periods with an objective above zero. |
sign_consistency | The share of successful periods with the most common sign (positive, negative or zero). It is 1.0 when all agree and falls toward 0.5 or lower when signs split. Below 0.8 raises SUBPERIOD_SIGN_INSTABILITY; at or above it, SUBPERIOD_SIGN_CONSISTENCY passes. |
worst_objective, best_objective | The least and most favourable period, where “favourable” follows direction. |
objective_dispersion | The sample standard deviation of the objective across periods. |
objective_trend_per_period | The slope of an ordinary least-squares line of the objective on the period’s position in the list you passed. It is a trend in declared order, not in calendar time, and unequal window lengths do not change it. |
top_absolute_outcome_share | The largest period’s share of the total absolute outcome. At or above concentration_threshold, it raises SUBPERIOD_OUTCOME_CONCENTRATION. Needs outcome_metric. |
Periods may overlap, but then they are not independent, and the result carries SUBPERIOD_OVERLAP so no one counts them as separate observations. Failed periods stay in the table with status="failed" and add SUBPERIOD_EVALUATION_FAILURES.
Universes
universe_perturbation re-runs your evaluation over several declared universes and reports how much the instruments changed alongside how much the result changed. A result that disappears when you remove ten percent of the instruments was a result about those instruments.
A UniverseScenario is a named, timestamped eligibility set: a name, a membership_id identifying the membership list, an as_of time at which it was determined, the instrument_ids themselves, and a definition saying in words how it was built. point_in_time=True, the default, is your claim that the set was determined as of as_of without hindsight.
names = list("ABCDEFGH")
universe_rng = np.random.default_rng(5)
frames = []
for k, name in enumerate(names):
drift_k = np.zeros(n)
for t in range(1, n):
drift_k[t] = 0.95 * drift_k[t - 1] + universe_rng.normal(0, 0.0006 if k < 3 else 0.0)
frames.append(pl.DataFrame({"time": days, "instrument": name, "ret": drift_k + universe_rng.normal(0, 0.01, n)}))
panel = pl.concat(frames)
def evaluate_universe(universe):
pnl = [
strategy_pnl(panel.filter(pl.col("instrument") == name)["ret"], 20, 0.0)
for name in universe.instrument_ids
]
return summarize(np.mean(pnl, axis=0))
universes = [
UniverseScenario("baseline", "u:all", date(2023, 1, 2), tuple(names), "all eight instruments"),
UniverseScenario("ex_first_three", "u:ex3", date(2023, 1, 2), tuple(names[3:]), "baseline without A, B and C"),
UniverseScenario("alternate", "u:alt", date(2023, 1, 2), tuple(names[::2]), "every other instrument"),
UniverseScenario(
"today_list", "u:now", date(2025, 4, 1), tuple(names[:6]),
"constituents on 2025-04-01 applied to the whole history", point_in_time=False,
),
]
robust = lc.robustness.universe_perturbation(
evaluate_universe,
universes=universes,
baseline="baseline",
objective="sharpe",
sample_count_metric="n_obs",
evaluator_name="docs.momentum",
code_id="docs-example-1",
)
rows = pl.DataFrame(robust.table("universes")).select(
"name", "objective", "retained_baseline_fraction", "removed_instruments"
)
print(rows.with_columns(pl.col("objective", "retained_baseline_fraction").round(3)))
print([(f.code, f.state.value) for f in robust.findings]) shape: (4, 4)
┌────────────────┬───────────┬────────────────────────────┬─────────────────────┐
│ name ┆ objective ┆ retained_baseline_fraction ┆ removed_instruments │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ i64 │
╞════════════════╪═══════════╪════════════════════════════╪═════════════════════╡
│ baseline ┆ 1.163 ┆ 1.0 ┆ 0 │
│ ex_first_three ┆ 0.323 ┆ 0.625 ┆ 3 │
│ alternate ┆ 1.372 ┆ 0.5 ┆ 4 │
│ today_list ┆ 1.128 ┆ 0.75 ┆ 2 │
└────────────────┴───────────┴────────────────────────────┴─────────────────────┘
[('UNIVERSE_RETROSPECTIVE_MEMBERSHIP', 'WARN')] Instruments A, B and C carry the drift. Removing them (ex_first_three) drops the Sharpe sharply, which shows the result depends on three names. The baseline must be one of the declared scenarios, by name, and each scenario’s composition is measured against it. retained_baseline_fraction is the share of the baseline’s instruments still present and composition_jaccard is the overlap divided by the union. The result also reports minimum_composition_jaccard and maximum_composition_change, which is one minus it. The objective summaries (worst_objective, best_objective, objective_dispersion) are taken across the scenarios; they are not changes relative to the baseline, so compare each row’s objective with the baseline’s yourself.
A scenario with point_in_time=False, such as a list of today’s constituents applied to old data, adds UNIVERSE_RETROSPECTIVE_MEMBERSHIP, a WARN. That is survivorship bias: the instruments that failed are already gone from the list. If all scenarios declare point-in-time membership, the result carries UNIVERSE_POINT_IN_TIME_DECLARED, a PASS. That finding is a record of what you declared, and the result warns that it does not prove the source is safe. A UniverseScenario is a static set with a single as_of. Lacuna never compares as_of to your data window, so point_in_time=True means the list was fixed as of that date. It does not describe membership that changes through time; for that, evaluate one scenario per date or use membership_at. To build a membership you can defend, see Membership and survivorship.
Regimes
A strategy can work in calm markets and fail in turbulent ones, or the other way round. Regime analysis splits the outcome by a market state and shows how the result differs between them. Lacuna separates the two steps: quantile_regimes labels each date, and regime_analysis summarises outcomes by label.
Classifying by quantiles
quantile_regimes takes a time series of one value, such as implied volatility, and labels each row "low", "middle" or "high" by comparing it with two quantile thresholds. method controls where the thresholds come from, and that is where look-ahead enters.
method | Thresholds | Point-in-time? |
|---|---|---|
"expanding" | The quantiles of all earlier rows. | Yes: each row uses only rows before it. |
"rolling" | The quantiles of the previous window rows. | Yes, for the same reason. |
"fixed" | The lower_threshold and upper_threshold you supply. | Only if you chose them without hindsight. |
"retrospective" | The quantiles of the whole sample. | No. |
For "expanding" and "rolling" the thresholds for row come from rows strictly before it: the current value is never part of its own threshold, and later values never enter. A row has a label only once at least min_history finite earlier values exist, and until then it is "unknown". "rolling" counts a window in rows (observations), not calendar time, and needs window >= min_history. Quantiles use NumPy’s linear interpolation. A value at or below the lower threshold is "low", at or above the upper is "high", anything else "middle"; missing or NaN values are "unknown", and infinite values raise.
The full-sample method labels early dates using quantiles that depend on later data. Prove it to yourself by classifying a prefix of the series and the whole series, then comparing the labels on the overlap:
market_rng = np.random.default_rng(3)
m = 300
market_days = [day for day in (date(2024, 1, 1) + timedelta(days=k) for k in range(500)) if day.weekday() < 5][:m]
vix = 15 + 0.03 * np.arange(m) + market_rng.normal(0, 2, m)
market = pl.DataFrame(
{
"time": market_days,
"vix": vix,
"ret": market_rng.normal(0, 0.005, m) + 0.0004 * (vix - 15) / 5,
}
)
def labels(result):
return [row["regime"] for row in result.table("regimes")]
options = dict(time="time", value="vix", min_history=30)
for method in ("expanding", "retrospective"):
full = labels(lc.regime.quantile_regimes(market, method=method, **options))
prefix = labels(lc.regime.quantile_regimes(market.head(150), method=method, **options))
changed = sum(a != b for a, b in zip(prefix, full[:150]))
print(method, "labels changed when 150 later rows were added:", changed) expanding labels changed when 150 later rows were added: 0
retrospective labels changed when 150 later rows were added: 69 Adding later data changes none of the expanding labels, and changes 69 of the 150 retrospective ones. A label that moves when the future arrives cannot have been known at the time. Retrospective classification adds REGIME_RETROSPECTIVE_THRESHOLDS, a high-severity WARN, and is useful only to describe the past. Any rows left "unknown" add REGIME_UNCLASSIFIED_ROWS, an UNKNOWN finding, so unclassified dates stay visible. Fixed and trailing methods add REGIME_THRESHOLDS_POINT_IN_TIME, a PASS. It covers threshold fitting only: the thresholds were not fitted to the classified or later values. For "fixed" it is not a check on your thresholds, since any fixed thresholds pass, because Lacuna cannot know how you picked them. It does not say the values themselves were published by their dates. That is a separate claim, reported as one of three findings:
available_time | Finding |
|---|---|
| Not supplied | REGIME_SOURCE_AVAILABILITY_UNKNOWN, UNKNOWN. |
Supplied, none later than its row’s time | REGIME_SOURCE_AVAILABLE, PASS. |
Supplied, some later than its row’s time | REGIME_SOURCE_NOT_AVAILABLE, FAIL. The call does not raise. |
These three are skipped for method="retrospective", although future_available_rows is still counted. The available_time column must have the same dtype as time and no nulls, otherwise the call raises a DataContractError. The method version is 2 because earlier results reported REGIME_THRESHOLDS_POINT_IN_TIME alone, which read as if source availability had been established. regime_analysis has its own availability check, as shown below.
The regimes table has one row per date, sorted by time, with history_count, threshold_lower, threshold_upper and regime. Its time column is written as ISO text, so convert it back before joining.
classified = lc.regime.quantile_regimes(market, method="expanding", **options)
print(classified.metrics)
print([(f.code, f.state.value) for f in classified.findings])
print(pl.DataFrame(classified.table("regimes")).tail(2)) {'row_count': 300, 'classified_rows': 270, 'unknown_rows': 30, 'future_available_rows': 0}
[('REGIME_THRESHOLDS_POINT_IN_TIME', 'PASS'), ('REGIME_SOURCE_AVAILABILITY_UNKNOWN', 'UNKNOWN'), ('REGIME_UNCLASSIFIED_ROWS', 'UNKNOWN')]
shape: (2, 6)
┌────────────┬───────────┬───────────────┬─────────────────┬─────────────────┬────────┐
│ time ┆ vix ┆ history_count ┆ threshold_lower ┆ threshold_upper ┆ regime │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ i64 ┆ f64 ┆ f64 ┆ str │
╞════════════╪═══════════╪═══════════════╪═════════════════╪═════════════════╪════════╡
│ 2025-02-20 ┆ 19.457037 ┆ 298 ┆ 17.218758 ┆ 22.027209 ┆ middle │
│ 2025-02-21 ┆ 22.824697 ┆ 299 ┆ 17.234738 ┆ 22.024524 ┆ high │
└────────────┴───────────┴───────────────┴─────────────────┴─────────────────┴────────┘ Conditional outcomes
regime_analysis takes a table with a regime label and an outcome per date, and summarises the outcome inside each regime. It does not classify anything. It also cannot tell how the labels were made, so you declare it with classification_mode, a required keyword.
The label at date uses the value at . It is therefore valid for outcomes after , not for the return that produced the value. Pair each label with the next period’s outcome, as below.
regimes = pl.DataFrame(classified.table("regimes")).select(pl.col("time").str.to_date(), "regime")
evidence = (
market.join(regimes, on="time")
.with_columns(outcome=pl.col("ret").shift(-1), available_time=pl.col("time"))
.select("time", "available_time", "regime", "outcome")
)
analysis = lc.regime.regime_analysis(
evidence,
classification_mode="point_in_time",
available_time="available_time",
min_observations=40,
annualization=252,
)
table = pl.DataFrame(analysis.table("conditional_evidence")).select(
"regime", "sample_count", "mean_outcome", "sharpe", "confidence_lower", "confidence_upper"
)
print(table.with_columns(pl.col("mean_outcome", "sharpe", "confidence_lower", "confidence_upper").round(4)))
print(analysis.metrics["top_regime"], round(analysis.metrics["top_absolute_outcome_share"], 3))
print([(f.code, f.state.value) for f in analysis.findings]) shape: (4, 6)
┌─────────┬──────────────┬──────────────┬─────────┬──────────────────┬──────────────────┐
│ regime ┆ sample_count ┆ mean_outcome ┆ sharpe ┆ confidence_lower ┆ confidence_upper │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═════════╪══════════════╪══════════════╪═════════╪══════════════════╪══════════════════╡
│ high ┆ 173 ┆ 0.0008 ┆ 2.5873 ┆ 0.0001 ┆ 0.0015 │
│ low ┆ 13 ┆ -0.0016 ┆ -3.8443 ┆ -0.0052 ┆ 0.002 │
│ middle ┆ 83 ┆ 0.0017 ┆ 6.0325 ┆ 0.0007 ┆ 0.0027 │
│ unknown ┆ 30 ┆ -0.0008 ┆ -2.4191 ┆ -0.0032 ┆ 0.0016 │
└─────────┴──────────────┴──────────────┴─────────┴──────────────────┴──────────────────┘
high 0.561
[('REGIME_INSUFFICIENT_EVIDENCE', 'UNKNOWN'), ('REGIME_INSUFFICIENT_EVIDENCE', 'UNKNOWN'), ('REGIME_UNKNOWN_CLASSIFICATION', 'UNKNOWN'), ('REGIME_AVAILABILITY_POINT_IN_TIME', 'PASS')] The outcome is the next day’s market return ret (shifted back one row), so the last row has none and is excluded (excluded_outcomes, one row here, which is why "high" has 173 valid outcomes from 174 rows). The first 30 rows are "unknown" because they have too little history, so they form their own group instead of being dropped. Two groups have fewer than min_observations valid outcomes, "low" with 13 and "unknown" with 30, so each gets a REGIME_INSUFFICIENT_EVIDENCE finding, UNKNOWN: their estimates are shown but are not evidence. The mean outcome is positive in the middle and high regimes, and the interval for "high" sits barely above zero. With three regimes compared and no multiplicity control, read this as a description of one sample, not as evidence that the strategy depends on the regime.
The regime shares are lopsided: 58% of the rows are "high". The series trends upward, so an expanding threshold sits below most new values, and most dates classify as high. A trending input makes expanding labels reflect the trend as much as the level; a rolling window or a detrended value would divide the dates more evenly. The high regime holds 56% of the absolute outcome, close to its share of the observations, so there is no concentration finding.
The declared classification_mode sets the availability finding. REGIME_AVAILABILITY_POINT_IN_TIME checks only that each label’s source was available by its time. It cannot check that each outcome happens after the label was available, so a PASS does not rule out a contemporaneous pairing of label and outcome. That alignment is yours to get right.
classification_mode | available_time | Finding |
|---|---|---|
"point_in_time" | not supplied | REGIME_AVAILABILITY_UNKNOWN, UNKNOWN. |
"point_in_time" | supplied, none later than time | REGIME_AVAILABILITY_POINT_IN_TIME, PASS. |
"point_in_time" | supplied, some later than time | REGIME_AVAILABILITY_LEAKAGE, FAIL. |
"retrospective" | any | REGIME_ANALYSIS_RETROSPECTIVE, WARN. The result is descriptive only. |
Lacuna does not check the declaration against how the labels were built. Labels from method="retrospective" that are passed with classification_mode="point_in_time" are not caught. Pass the mode that matches the labels, and the timestamps that go with them. The result records classification_provenance="declared_unverified" in its parameters, and with classification_mode="point_in_time" it carries a warning that the mode is a caller declaration whose label construction and label-to-outcome timing Lacuna does not verify. Both were added in 0.14.2 without changing any value, so regime_analysis is still method version 1.
How the conditional statistics are computed
For each regime, with outcomes in time order, regime_analysis reports the mean, the sample standard deviation (ddof 1), the hit rate (the share above zero), and the Sharpe ratio , with the annualization. There is no risk-free adjustment. The Sharpe is None when or .
Neighbouring outcomes are often correlated, so the interval uses an effective sample size from the lag-one autocorrelation of the regime’s own outcomes:
Only positive autocorrelation shrinks the sample; negative autocorrelation is ignored rather than inflating it. The autocorrelation is taken over the outcomes inside the regime in time order, so consecutive entries can be days apart. It is a rough correction, not a block bootstrap, and it is optimistic when autocorrelation extends beyond lag one: for an AR(1) series the effective size is , which is smaller. The interval is for the mean outcome. The hit rate and Sharpe have no interval. Lacuna does not test whether regimes differ from each other and applies no multiplicity control across them, so a pattern across regimes is a description, not a finding. For inference on a Sharpe ratio, see Inference.
Concentration asks how much of the result lives in one regime. With the absolute outcome share of regime :
absolute_outcome_hhi is 1 when one regime holds all the outcome and when regimes share it equally. If the top regime’s share is at least concentration_threshold (0.6 by default), the result carries REGIME_OUTCOME_CONCENTRATION, a WARN. The conditional table also gives, for each regime, net_outcome_share (its signed total over the grand total, which can be negative or exceed one when other regimes lose), leave_one_regime_out_total (the total outcome without it), and maximum_drawdown (the worst peak-to-trough fall of the running sum of its outcomes, starting from zero, reported as a non-positive number).
Set mutually_exclusive=False if one date can carry several labels. The key then becomes (time, regime), shares count label rows rather than unique dates, and the result warns about overlap with REGIME_LABELS_OVERLAP.
Parameters
continuous_perturbation
| Parameter | Meaning |
|---|---|
evaluate | A callable taking the parameter dictionary and returning an AnalysisResult. |
selected_parameters | The chosen values. Perturbed parameters must be finite numbers; others are held fixed and passed through. |
perturbations | A PerturbationSpec for each parameter to perturb, keyed by name. At least one. |
objective | The name of the metric in each result to analyse. It must be finite. |
evaluator_name, evaluator_version | The identity of the evaluation method, recorded in provenance. |
sample_id | A declared identity for the data sample. |
code_id | A declared identity for the evaluator code version. |
draws | The number of accepted points to evaluate. |
seed | The seed of the draw generator. Non-negative. |
direction | "maximize" or "minimize". It decides which side of evidence_threshold counts as passing, and which period is “worst”. It does not change positive_fraction. |
constraint, constraint_name | An optional feasibility function and its identity. Give both or neither. |
failure_policy | "record" stores failures; "raise" propagates the first. |
max_attempts | The cap on draws tried, at least draws. Default 100 * draws. |
evidence_threshold | Optional objective level for passing_fraction. |
registry | An optional ExperimentRegistry that records every evaluation. |
| Parameter | Meaning |
|---|---|
distribution | "normal", "lognormal" or "uniform". |
scale | Standard deviation (normal), log-scale standard deviation (lognormal) or half-width (uniform). Positive. |
lower, upper | Optional bounds. Draws outside them are rejected, not clipped. |
integer | Round draws to whole numbers before applying bounds. |
subperiod_analysis
| Parameter | Meaning |
|---|---|
evaluate | A callable taking a Subperiod and returning an AnalysisResult. It must restrict its data to the window itself. |
periods | The Subperiod windows. At least one, with unique names and sample ids. |
objective | The metric to analyse. |
sample_count_metric | A metric holding the period’s observation count, as a non-negative whole number. |
evaluator_name, evaluator_version | The identity of the evaluation method. |
code_id | A declared identity for the evaluator code version. |
outcome_metric | Optional metric, such as profit, used for concentration. |
confidence_lower_metric, confidence_upper_metric | Optional metrics carried into the table as an interval. Give both or neither; the lower may not exceed the upper. |
direction | "maximize" or "minimize", which decides the worst and best period. |
failure_policy | "record" or "raise". |
concentration_threshold | The top outcome share, in (0, 1], at which concentration is flagged. Default 0.6. |
registry | An optional ExperimentRegistry. |
| Parameter | Meaning |
|---|---|
name | A unique label for the window. |
start, end | The half-open bounds, both dates or both timezone-aware datetimes. |
sample_id | A unique declared identity for the data in the window. |
universe_perturbation
| Parameter | Meaning |
|---|---|
evaluate | A callable taking a UniverseScenario and returning an AnalysisResult. It must restrict its data to the instruments itself. |
universes | The scenarios. Names and membership ids must be unique. |
baseline | The name of the scenario that composition is measured against. |
objective | The metric to analyse. |
sample_count_metric | A metric holding the observation count, as a non-negative whole number. |
evaluator_name, evaluator_version | The identity of the evaluation method. |
code_id | A declared identity for the evaluator code version. |
direction | "maximize" or "minimize", which decides the worst and best scenario. |
failure_policy | "record" or "raise". |
registry | An optional ExperimentRegistry. |
| Parameter | Meaning |
|---|---|
name | A unique label for the scenario. |
membership_id | A unique identity for the membership list. |
as_of | When the eligibility set was determined. A datetime must be timezone-aware. |
instrument_ids | The members: unique, non-empty, trimmed strings. |
definition | A plain-language description of how the set was built. |
point_in_time | Your claim that the set was determined as of as_of without hindsight. Default True. |
quantile_regimes
| Parameter | Meaning |
|---|---|
data | A table with a time column and a value column, one row per time. |
time | The time column. Rows are sorted by it; duplicates raise. |
value | The numeric series to classify. |
method | "fixed", "expanding", "rolling" or "retrospective". |
lower_quantile, upper_quantile | The quantile cut-offs in (0, 1), lower below upper. |
min_history | The earlier finite values needed before a row can be classified. Used by "expanding" and "rolling" only; ignored for "fixed" and "retrospective". |
window | The rolling window in rows; required for "rolling" and invalid otherwise. |
lower_threshold, upper_threshold | The cut-offs for "fixed"; invalid for other methods. |
low_label, middle_label, high_label, unknown_label | The label strings. They must be distinct. |
available_time | Optional column giving when each value became available, checked against time. |
regime_analysis
| Parameter | Meaning |
|---|---|
data | A table with a time, a regime label and an outcome per row. |
time | The time column. |
regime | The regime label column. Null labels become unknown_label. |
outcome | The numeric outcome (a per-period return or profit). Infinite values raise; null and NaN are excluded and counted. |
classification_mode | Required. Your declaration: "point_in_time" or "retrospective". |
available_time | Optional column for when each label’s source became available. |
mutually_exclusive | True if each time has one label, False if labels can overlap. |
unknown_label | The label that marks unclassified rows. |
min_observations | The fewest valid outcomes a regime needs before its estimate counts as evidence. |
annualization | Periods per year, used in the Sharpe ratio. |
concentration_threshold | The top absolute outcome share, in (0, 1], at which concentration is flagged. |
The full signatures are in the API reference for lacuna.robustness and lacuna.regime.