Statistical inference
Put uncertainty and selection bias on a backtest result with block bootstraps, Sharpe inference, permutation tests, multiple-testing corrections, PBO, the Reality Check, SPA and parameter surfaces.
A backtest produces one number: a mean return, a Sharpe ratio, an information coefficient. That number is one draw from a process you only saw once, and two things make it less trustworthy than it looks. Returns are serially dependent, so the textbook standard error is too small. And the number you are looking at was usually picked from many alternatives, so it is the best of a crowd rather than a typical draw.
lacuna.validation has a method for each of these problems. Block bootstraps and Sharpe inference say how uncertain one statistic is. Permutation tests say how surprising it is under a stated null. Multiple-testing corrections, the Probability of Backtest Overfitting, White’s Reality Check and Hansen’s SPA say what the selection from many trials does to the evidence. Parameter surfaces say whether the chosen setting sits on a plateau or on a spike. Every function returns an AnalysisResult with metrics, tables, findings and warnings, and records the seed and every setting that affects the number.
Which function answers which question
| Question | Function | Input |
|---|---|---|
| How uncertain is this mean, median or Sharpe ratio, given serial dependence? | bootstrap | One series |
| How uncertain are several strategies’ means, and how do they move together? | joint_stationary_bootstrap | A table of strategy returns |
| Is this Sharpe ratio distinguishable from a benchmark, after skew and fat tails, and after searching many trials? | sharpe_inference | One series, optionally the trial Sharpe ratios |
| Is this mean, or this association, larger than chance under an explicit exchangeability assumption? | permutation_test | One series, or a signal and a return |
| Which of these p-values survive having run all of them? | multiple_testing | A list or table of p-values |
| How often does the best in-sample strategy rank below the median out of sample? | probability_of_backtest_overfitting | A table of strategy returns |
| Does the best of a family beat a benchmark by more than data snooping explains? | reality_check, superior_predictive_ability | A table of return differentials |
| Is the chosen parameter setting supported by its neighbours? | parameter_surface | An evaluator function and a grid |
A first example
The shared data for this page: a daily strategy return series with a little positive autocorrelation, and a family of twelve strategies. Everything uses fixed seeds.
import lacuna as lc
import numpy as np
import polars as pl
V = lc.validation
rng = np.random.default_rng(42)
n, mu, phi = 500, 0.0006, 0.3
eps = rng.normal(0, 0.01, n)
returns = np.empty(n)
returns[0] = mu + eps[0]
for t in range(1, n):
returns[t] = mu + phi * (returns[t - 1] - mu) + eps[t]
result = V.bootstrap(returns, method="stationary", resamples=2000, seed=1)
print(result.metrics["observed"], result.metrics["confidence_lower"], result.metrics["confidence_upper"]) 0.0004310391041698273 -0.0006012815346137366 0.001558565176789749 The observed mean daily return and a 95% interval for it. The interval comfortably includes zero, which is the first thing worth knowing about 500 days of a strategy earning 4 basis points a day.
Bootstrap
bootstrap resamples a series many times, recomputes a statistic on each resample, and reads an interval off the distribution of those replicates. It answers: how much would this statistic move if the same process had produced a different sample?
The plain (IID) bootstrap draws observations one at a time with replacement, which destroys the order of the data. That is only right when observations are independent. Returns, and especially IC series built from overlapping labels, are not. The block methods resample runs of consecutive observations so that the dependence within a block survives.
method | How a resample is built |
|---|---|
"iid" | n indices drawn uniformly with replacement. Takes no block length. |
"moving" (default) | Fixed-length blocks starting at any position from 0 to n - block_length, concatenated and cut to n. Blocks never wrap around the end. |
"circular" | Fixed-length blocks starting anywhere, wrapping past the end of the series back to its start. |
"stationary" | Blocks of random length, geometric with mean expected_block_length, each starting at a uniformly random position and wrapping. Because lengths are random, the resampled series is stationary. |
For the three block methods the default block length is max(2, round(n ** (1/3))), which is 8 for 500 observations. It is a rule of thumb, not an estimate of your series’ dependence. Pass block_length for moving and circular, and either block_length or expected_block_length for stationary; passing both is an error, and expected_block_length is rejected for the other methods. A block length must be a positive integer no larger than the sample size. Every function on this page raises a MethodContractError for 0 or a negative value.
rows = []
for method in ("iid", "moving", "circular", "stationary"):
b = V.bootstrap(returns, method=method, resamples=2000, seed=1)
rows.append(
{
"method": method,
"block_length": b.metadata.parameters["block_length"],
"standard_error": round(b.metrics["standard_error"], 6),
"lower": round(b.metrics["confidence_lower"], 5),
"upper": round(b.metrics["confidence_upper"], 5),
}
)
print(pl.DataFrame(rows)) shape: (4, 5)
┌────────────┬──────────────┬────────────────┬──────────┬─────────┐
│ method ┆ block_length ┆ standard_error ┆ lower ┆ upper │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪══════════════╪════════════════╪══════════╪═════════╡
│ iid ┆ 1 ┆ 0.00047 ┆ -0.0005 ┆ 0.00135 │
│ moving ┆ 8 ┆ 0.000592 ┆ -0.00062 ┆ 0.00165 │
│ circular ┆ 8 ┆ 0.000586 ┆ -0.00069 ┆ 0.00161 │
│ stationary ┆ 8 ┆ 0.000562 ┆ -0.0006 ┆ 0.00156 │
└────────────┴──────────────┴────────────────┴──────────┴─────────┘ The IID interval is the narrowest, and it is the one that is wrong for this series: the returns were generated with positive autocorrelation, so the mean is estimated less precisely than independent draws would suggest. The block methods widen the interval to reflect that. The IID method also adds a BOOTSTRAP_IID_ASSUMPTION warning finding to its result, so that an audit can see that the dependence was ignored.
Block-length sensitivity
One block length does not prove the interval is right: too short and it understates dependence, too long and it leaves few independent blocks. Every block-method result carries a warning to that effect. Vary the length and see how much the answer moves:
for length in (2, 4, 8, 16, 32):
b = V.bootstrap(returns, method="stationary", expected_block_length=length, resamples=2000, seed=1)
print(length, round(b.metrics["standard_error"], 6)) 2 0.000535
4 0.00059
8 0.000562
16 0.000511
32 0.000454 If the standard error changes materially across plausible lengths, report the range rather than one interval.
Statistics and interval methods
statistic is "mean", "median", "sharpe" or a function from a one-dimensional float array to a float. The built-in "sharpe" is the per-period mean divided by the sample standard deviation (ddof=1); it is not annualized, so multiply by the square root of your periods per year. A zero-variance sample raises an error. A custom statistic runs in Python, once per resample.
interval="percentile" (default) takes the (1 - confidence_level) / 2 and 1 - (1 - confidence_level) / 2 quantiles of the replicates. interval="basic" reflects them around the observed value, which corrects some bias in the replicates:
where is the observed statistic, the -quantile of the replicates and .
sharpe_ci = V.bootstrap(
returns, statistic="sharpe", method="stationary", expected_block_length=8,
interval="basic", resamples=2000, seed=1,
)
scale = np.sqrt(252)
print(
round(sharpe_ci.metrics["observed"] * scale, 3),
round(sharpe_ci.metrics["confidence_lower"] * scale, 3),
round(sharpe_ci.metrics["confidence_upper"] * scale, 3),
) 0.662 -1.096 2.239 That is an annualized Sharpe ratio with a dependence-aware interval, obtained by resampling blocks of returns.
Reading the result
metrics holds observed (the statistic on your data), bootstrap_estimate (the mean of the replicates), standard_error (their standard deviation), confidence_lower and confidence_upper, and monte_carlo_resolution (1 / (resamples + 1), the spacing of the quantile levels the replicates can resolve, not a precision for the statistic itself). n_effective is None: the bootstrap does not estimate an effective sample size, and the result says so in its warnings. The distribution_summary table has eleven quantiles of the replicates. Pass store_distribution=True to keep every replicate in a resample_distribution table.
An interval that contains zero means the data do not rule out a zero effect at that confidence level. It does not mean the effect is zero.
Non-finite values are removed by default (null_policy="drop") and counted in excluded_rows; pass "raise" to fail instead. At least two finite observations are needed, and resamples must be at least 100.
Seeds
Each replicate draws from its own random stream, derived from (seed, method version, replicate number). The result does not depend on how the work is batched. If you pass no seed, Lacuna uses the configured seed if there is one and otherwise draws one, and it always records the seed it used in result.metadata.seed. Pass a seed in anything you want to reproduce. See Results for how seeds are recorded.
| Parameter | Meaning |
|---|---|
data | A one-dimensional NumPy array, a sequence of numbers, or a table with the series in the value column. |
value | The column to resample when data is a table. Default "value". |
statistic | "mean" (default), "median", "sharpe" or a callable. |
method | "iid", "moving" (default), "circular" or "stationary". |
block_length | Block length for the block methods. Must be omitted for "iid". |
expected_block_length | Mean block length. Only valid with "stationary", and not together with block_length. |
resamples | The number of bootstrap replicates, at least 100. Default 1000. More replicates give a smoother interval, not a more accurate one. |
confidence_level | The interval’s coverage, strictly between 0 and 1. Default 0.95. |
interval | "percentile" (default) or "basic". |
seed | A non-negative integer for reproducibility. |
null_policy | "drop" (default) removes non-finite values and counts them; "raise" fails. |
store_distribution | Keep every replicate in the result. |
use_native | Use the compiled reduction for the built-in mean when available. The backend used is recorded. |
batch_memory_bytes | A cap on the memory used per batch of resamples. It changes how the work is batched, not which resamples are drawn. |
Joint bootstrap of several strategies
When you compare strategies, resampling each one separately throws away the fact that they were observed on the same days. joint_stationary_bootstrap draws one stationary-bootstrap index path per replicate and applies it to every column, so both the time dependence within each strategy and the dependence between strategies are preserved. It returns the sampling distribution of each strategy’s mean and the long-run covariance between them.
The twelve-strategy family below is mostly noise plus one column with a real daily edge of 10 basis points. The strategies share a common factor, which is what makes the cross-strategy dependence real.
rng = np.random.default_rng(6)
T, N = 480, 12
common = rng.normal(0, 0.01, T)
noise = 0.5 * common[:, None] + rng.normal(0, 0.01, (T, N))
names = [f"s{i:02d}" for i in range(N)]
noise_family = pl.DataFrame(noise, schema=names)
edge = noise.copy()
edge[:, 7] += 0.0010
edge_family = pl.DataFrame(edge, schema=names)
joint = V.joint_stationary_bootstrap(
edge_family.select("s03", "s07"), expected_block_length=5, resamples=1000, seed=2
)
print(pl.DataFrame(joint.table("strategy_statistics")))
print(pl.DataFrame(joint.table("long_run_covariance"))) shape: (2, 4)
┌──────────┬──────────┬────────────────┬──────────────────────────┐
│ strategy ┆ mean ┆ bootstrap_mean ┆ bootstrap_standard_error │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪══════════╪════════════════╪══════════════════════════╡
│ s03 ┆ 0.000266 ┆ 0.000294 ┆ 0.000492 │
│ s07 ┆ 0.001881 ┆ 0.0019 ┆ 0.000454 │
└──────────┴──────────┴────────────────┴──────────────────────────┘
shape: (4, 3)
┌──────────┬────────────────┬─────────────────────┐
│ strategy ┆ other_strategy ┆ long_run_covariance │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞══════════╪════════════════╪═════════════════════╡
│ s03 ┆ s03 ┆ 0.000116 │
│ s03 ┆ s07 ┆ 0.000024 │
│ s07 ┆ s03 ┆ 0.000024 │
│ s07 ┆ s07 ┆ 0.000099 │
└──────────┴────────────────┴─────────────────────┘ strategy_statistics has each strategy’s observed mean, the mean of its bootstrap replicates and the bootstrap standard error. long_run_covariance is the covariance, across replicates, of for each pair of strategies, an estimate of the long-run covariance of the means. A positive off-diagonal entry means that the two strategies’ means tend to be over- or under-estimated together.
The expected block length defaults to the same max(2, round(T ** (1/3))) rule and must be a positive integer no larger than T; 0 raises. The index path uses the same stationary scheme as bootstrap(method="stationary") but a different random-stream layout, so the two do not give identical replicates for the same seed.
Several functions on this page take a table of strategies. They share these rules:
- Pass a table or a two-dimensional NumPy array, one row per period and one column per strategy, all rows synchronous. A NumPy array names its columns
strategy_0,strategy_1and so on. - With a table and no
strategy_columns, every numeric column is used. That includes an integer index or period column, so passstrategy_columnswhen the table has one. - There must be at least four rows and two columns, and every value must be finite. Missing values raise a
DataContractError; these functions never drop rows.
Sharpe inference
sharpe_inference answers three questions about a return series: how uncertain is its Sharpe ratio, how likely is it that the true Sharpe ratio exceeds a benchmark, and how long a track record would be needed to say so. With trial_sharpes it also answers a fourth: would this Sharpe ratio still look good if you account for having picked it from many trials?
What it estimates
With periodic returns, mean and sample standard deviation (ddof=1), the periodic Sharpe ratio is and the reported Sharpe ratio is , where is annualization, the number of periods per year (252 for daily data). The default of 1 reports the periodic ratio.
The standard error uses the sample skewness and Pearson kurtosis (3 for a normal distribution), so that skewed and fat-tailed returns widen the interval. These moments are the plain standardized central moments with divisor , while the Sharpe ratio itself uses the standard deviation with ddof=1:
For normal returns this reduces to the familiar . The reported standard error and the confidence interval are on the annualized scale: , with the two-sided normal quantile for confidence_level.
The Probabilistic Sharpe Ratio is the asymptotic normal distribution function evaluated at the standardized distance between the observed Sharpe ratio and a benchmark . It is one minus the one-sided asymptotic p-value for the null that the true Sharpe ratio equals the benchmark. It is not a posterior probability that the true Sharpe ratio exceeds the benchmark:
benchmark is given on the annualized scale and divided by internally. PSR does not depend on annualization. The minimum track record length is the number of observations at which the Sharpe ratio would first be significant at confidence_level against the benchmark, holding the observed moments fixed:
with the one-sided normal quantile. It is in observations of the input frequency, and it is None when the observed Sharpe ratio does not exceed the benchmark.
sharpe = V.sharpe_inference(returns, annualization=252)
for key in ("observed_sharpe", "standard_error", "confidence_lower", "confidence_upper",
"probabilistic_sharpe_ratio", "minimum_track_record_observations",
"skewness", "kurtosis"):
print(f"{key:36s}", round(sharpe.metrics[key], 4))
print([(f.code, f.state.value) for f in sharpe.findings]) observed_sharpe 0.6618
standard_error 0.7092
confidence_lower -0.7283
confidence_upper 2.0519
probabilistic_sharpe_ratio 0.8246
minimum_track_record_observations 1551.5596
skewness 0.1165
kurtosis 3.104
[('SHARPE_UNCERTAIN', 'WARN')] The annualized Sharpe ratio is 0.66 with an interval running from clearly negative to above 2. The PSR against zero is 0.82, which is a one-sided asymptotic p-value of about 0.18 for the null of a zero Sharpe ratio. It is below the 0.95 default confidence_level, so the finding is SHARPE_UNCERTAIN. minimum_track_record_observations is the total number of observations, with this Sharpe ratio, skewness and kurtosis, at which the ratio would first beat zero at 95% confidence. It is about 1,550 days, three times the length of the sample. A strategy with an annualized Sharpe ratio of 0.66 needs a long record before the data distinguish it from zero.
What it does not handle
The standard error corrects for skewness and kurtosis, not for autocorrelation. It assumes the returns are serially independent, and Lacuna does not adjust for dependence. The series above has positive autocorrelation, so the interval here is too narrow; compare the block-bootstrap interval from bootstrap(statistic="sharpe") above. The method is also asymptotic. The result’s warnings say that short samples and unstable fourth moments call for caution.
The SHARPE_EXCEEDS_BENCHMARK or SHARPE_UNCERTAIN finding is decided by PSR against confidence_level, whether or not trial_sharpes is supplied. It is not adjusted for selection. Its evidence always records selection_adjusted: False. When you supply trial_sharpes, it also names, in deflated_finding, the finding to read with it (otherwise None), and the result carries that finding too, as Deflating for selection shows.
Deflating for selection
A Sharpe ratio picked as the best of trials is biased upward: the best of twelve will look good even if none of them has any edge. The Deflated Sharpe Ratio replaces the benchmark with a selection threshold built from the trials you supply: their mean Sharpe ratio plus the expected excess of the maximum of normal draws with their dispersion. With and the mean and standard deviation (ddof=1) of the trial Sharpe ratios on the periodic scale, and the Euler-Mascheroni constant:
Because is the mean of your trials, not zero, this differs from the published DSR, whose threshold assumes the trials have zero mean Sharpe ratio under the null. For a family that is profitable across the board, so that is well above zero, Lacuna’s threshold is more demanding. With independent_trials=1 the threshold is exactly . The benchmark argument does not enter the DSR; it affects only the PSR, the minimum track record and the finding.
Pass the Sharpe ratios of every trial you ran as trial_sharpes, on the same annualization scale as the result. The list must have at least two values and must include the observed Sharpe ratio of the series you are testing, or Lacuna raises an error. This protects against passing a list that leaves out the winner. By default is the number of trials, which treats them as independent; pass independent_trials with an effective count between 1 and the number of trials if they are strongly correlated. Lacuna does not estimate that count, and says so in a warning.
Here is the best strategy of the noise-only family. Taken alone, it looks significant:
annual = {c: noise_family[c].mean() / noise_family[c].std() * np.sqrt(252) for c in names}
best = max(annual, key=annual.get)
alone = V.sharpe_inference(noise_family[best].to_numpy(), annualization=252)
deflated = V.sharpe_inference(
noise_family[best].to_numpy(), annualization=252, trial_sharpes=list(annual.values())
)
print(best, round(annual[best], 3))
print("PSR vs 0:", round(alone.metrics["probabilistic_sharpe_ratio"], 3))
print("DSR: ", round(deflated.metrics["deflated_sharpe_ratio"], 3))
print("mean Sharpe of the trials:", round(deflated.metrics["trial_sharpe_mean"], 3))
print("selection threshold:", round(deflated.metrics["deflated_sharpe_threshold"], 3))
print([(f.code, f.state.value) for f in alone.findings])
print([(f.code, f.state.value) for f in deflated.findings])
psr_finding = deflated.findings[0]
print(psr_finding.evidence["selection_adjusted"], psr_finding.evidence["deflated_finding"]) s07 1.273
PSR vs 0: 0.96
DSR: 0.349
mean Sharpe of the trials: 0.314
selection threshold: 1.555
[('SHARPE_EXCEEDS_BENCHMARK', 'PASS')]
[('SHARPE_EXCEEDS_BENCHMARK', 'PASS'), ('DEFLATED_SHARPE_UNCERTAIN', 'WARN')]
False DEFLATED_SHARPE_UNCERTAIN Against a benchmark of zero the best strategy has a PSR above 95%. Against the selection threshold, which is the trials’ mean Sharpe ratio of 0.31 plus the expected excess of the best of twelve, giving 1.55, it has a DSR of about 0.35. The strategies were pure noise, so the second number is the honest one. With trial_sharpes the result adds a second finding, DEFLATED_SHARPE_SUPPORTED (PASS) when the DSR reaches confidence_level and DEFLATED_SHARPE_UNCERTAIN (WARN) when it does not. The PSR finding above still passes, because it ignores selection; its evidence says so with selection_adjusted of False and names the deflated finding to read with it. The DSR is only as good as the list you give it: omit the failed variants and it flatters the winner.
| Parameter | Meaning |
|---|---|
data | A one-dimensional NumPy array, a sequence, or a table with the returns in value. At least three finite observations, and not all equal. |
value | The column to use when data is a table. |
benchmark | The Sharpe ratio to test against, on the annualized scale. Default 0. |
confidence_level | Between 0.5 and 1. Used for the interval, the minimum track record and the finding. Default 0.95. |
annualization | Periods per year. Scales the Sharpe ratio, standard error, interval, benchmark and DSR threshold. Default 1. |
trial_sharpes | The Sharpe ratios of all trials, including the one tested, on the annualized scale. Enables the deflated Sharpe ratio. |
independent_trials | The effective number of independent trials, between 1 and the trial count. Requires trial_sharpes. |
null_policy | "raise" (default) fails on non-finite values; "drop" removes and counts them. |
Permutation tests
A permutation test builds the null distribution of a statistic by re-arranging the data in a way that would not change anything if the null were true, and asks how often the rearranged statistic is as extreme as the observed one. It makes no distributional assumption, but it makes an exchangeability assumption, and the p-value is only as valid as that assumption. The result carries a warning to that effect.
The scheme says what is exchangeable:
scheme | What it permutes | Null it tests |
|---|---|---|
"sign_flip" (default) | Multiplies each value by a random sign. | A one-sample null that the values are symmetric around zero, so the mean is zero. |
"unrestricted" | Shuffles value against paired_with across all rows. | No association between the two columns. |
"within_date" | Shuffles value within each value of the time column. | No cross-sectional association on any date. |
"within_group" | Shuffles value within each value of the group column. | No association within a group, such as a sector. |
"block" | Reorders non-overlapping consecutive blocks of value of length block_length (the last block may be shorter) against paired_with. | No association, with local ordering of value preserved. |
All schemes except sign_flip need paired_with, and they need an order-sensitive statistic: the built-in "mean" of a reshuffled column never changes, so it is rejected. Use statistic="pearson" or a function of (values, paired).
The p-value counts the replicates at least as extreme as the observed statistic, with a finite-sample correction so it is never exactly zero:
alternative="two_sided" compares absolute values, "greater" and "less" count one tail. The smallest p-value a run can report is 1 / (permutations + 1). For the block scheme, a series cut into blocks has only distinct orderings, so there are few distinct rearrangements to draw from when is small, and that floor may be unreachable. For the within_date and within_group schemes, a stratum with a single row cannot be shuffled and contributes nothing, and at least one stratum must have two rows or the call raises.
A sign-flip test of the strategy’s mean return:
flip = V.permutation_test(returns, permutations=2000, seed=5)
print(flip.metadata.method, round(flip.metrics["observed"], 6), round(flip.metrics["p_value"], 3)) validation.permutation.sign_flip 0.000431 0.349 The p-value is far from small, in line with the bootstrap interval that contained zero. The null is that the values are symmetric about zero and independent, because each sign is flipped on its own. With positive autocorrelation the test is too optimistic (p-values too small); with negative autocorrelation it is conservative. For a dependent series, use a block bootstrap instead.
A within-date test of a signal and next-period return. The panel has 40 dates and 25 instruments, and the signal has a small real effect on the return:
g = np.random.default_rng(3)
dates, names_ = 40, 25
signal = g.normal(size=(dates, names_))
forward = 0.0015 * signal + g.normal(0, 0.02, (dates, names_))
panel = pl.DataFrame(
{
"time": np.repeat(np.arange(dates), names_),
"signal": signal.ravel(),
"forward_return": forward.ravel(),
}
)
within = V.permutation_test(
panel, value="signal", paired_with="forward_return",
statistic="pearson", scheme="within_date", time="time",
permutations=1000, seed=5,
)
print({k: round(v, 4) if isinstance(v, float) else v for k, v in within.metrics.items() if k in ("observed", "p_value", "exceedances", "n_effective")}) {'observed': 0.1033, 'p_value': 0.002, 'exceedances': 1, 'n_effective': 1000} The statistic is the pooled Pearson correlation between the signal and the return, and the null shuffles the signal across instruments within each date, so the test cannot be fooled by differences between dates. The observed correlation is about 0.10, and only one of the 1000 shuffles reached it in absolute value, so the p-value is (1 + 1) / (1000 + 1), about 0.002. Neither this test nor a pooled correlation adjusts for dependence across dates, which is why the signal diagnostics work with the IC for each date instead.
At least three finite observations are needed, and permutations must be at least 100. value, paired_with and time/group columns are read from a table; a NumPy array may hold one column, or two when paired_with is given.
| Parameter | Meaning |
|---|---|
data | A series, or a table with the named columns. |
value | The column being tested or permuted. |
paired_with | The column that value is permuted against. Required for every scheme except "sign_flip". |
statistic | "mean", "pearson" or a callable taking the values and the paired values (or None) and returning a float. |
scheme | One of the five schemes above. Default "sign_flip". |
time | The date column, for "within_date". Default "time". |
group | The group column, for "within_group". Default "group". |
block_length | The block length for "block", between 1 and the sample size minus 1. Invalid for other schemes. |
permutations | The number of random rearrangements, at least 100. Default 1000. |
alternative | "two_sided" (default), "greater" or "less". |
seed | A non-negative integer for reproducibility. |
null_policy | "raise" (default) or "drop" for non-finite values. |
store_distribution | Keep every replicate of the statistic in a permutation_distribution table. |
Multiple testing
If you test twenty independent hypotheses at the 5% level and none is real, you expect one to come out significant. multiple_testing takes the p-values of a declared family and adjusts them for the number of tests. It needs the p-values of every test you ran, including the ones that did not work out.
method | Controls | Adjusted p-value for the -th smallest of |
|---|---|---|
"bonferroni" | Family-wise error rate | |
"holm" (default) | Family-wise error rate | |
"benjamini_hochberg" | False discovery rate, under independence or positive dependence | |
"benjamini_yekutieli" | False discovery rate, under arbitrary dependence | Benjamini-Hochberg multiplied by |
A hypothesis is rejected when its adjusted p-value is at most alpha. Holm is never less powerful than Bonferroni and has the same guarantee, so it is the default. The family-wise error rate is the probability of at least one false rejection; the false discovery rate is the expected fraction of rejections that are false. The first is the stricter promise.
pvalues = [0.001, 0.008, 0.012, 0.03, 0.04, 0.2, 0.5, 0.9]
table = pl.DataFrame({"trial_id": range(len(pvalues)), "p_value": pvalues})
for method in ("bonferroni", "holm", "benjamini_hochberg", "benjamini_yekutieli"):
adjusted = V.multiple_testing(pvalues, method=method)
table = table.with_columns(
pl.Series(method, [row["adjusted_p_value"] for row in adjusted.table("adjusted_p_values")]).round(4)
)
print(f"{method:22s} rejects {adjusted.metrics['rejected_count']} of {adjusted.metrics['trial_count']}")
print(table) bonferroni rejects 1 of 8
holm rejects 1 of 8
benjamini_hochberg rejects 3 of 8
benjamini_yekutieli rejects 1 of 8
shape: (8, 6)
┌──────────┬─────────┬────────────┬───────┬────────────────────┬─────────────────────┐
│ trial_id ┆ p_value ┆ bonferroni ┆ holm ┆ benjamini_hochberg ┆ benjamini_yekutieli │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪═════════╪════════════╪═══════╪════════════════════╪═════════════════════╡
│ 0 ┆ 0.001 ┆ 0.008 ┆ 0.008 ┆ 0.008 ┆ 0.0217 │
│ 1 ┆ 0.008 ┆ 0.064 ┆ 0.056 ┆ 0.032 ┆ 0.087 │
│ 2 ┆ 0.012 ┆ 0.096 ┆ 0.072 ┆ 0.032 ┆ 0.087 │
│ 3 ┆ 0.03 ┆ 0.24 ┆ 0.15 ┆ 0.06 ┆ 0.1631 │
│ 4 ┆ 0.04 ┆ 0.32 ┆ 0.16 ┆ 0.064 ┆ 0.1739 │
│ 5 ┆ 0.2 ┆ 1.0 ┆ 0.6 ┆ 0.2667 ┆ 0.7248 │
│ 6 ┆ 0.5 ┆ 1.0 ┆ 1.0 ┆ 0.5714 ┆ 1.0 │
│ 7 ┆ 0.9 ┆ 1.0 ┆ 1.0 ┆ 0.9 ┆ 1.0 │
└──────────┴─────────┴────────────┴───────┴────────────────────┴─────────────────────┘ The smallest raw p-value, 0.001, survives every method. The next four, 0.008, 0.012, 0.03 and 0.04, are each below 5% on their own, but none of them survives Bonferroni, Holm or Benjamini-Yekutieli. Benjamini-Hochberg keeps two of them, 0.008 and 0.012, for three rejections in all. Which you should use depends on what a false positive costs: for a handful of final candidates that will receive capital, control the family-wise error rate; for a screen whose survivors get a second look, a false discovery rate is often the right promise.
The input can be a list or NumPy array of p-values, or a table with a trial identifier column (unique, no nulls) and a p_value column. It can also be an ExperimentRegistry: p_value then names the metric recorded on each trial, and every trial’s latest attempt must be completed with that metric, otherwise the call raises. This is how to make sure the family is the one you actually ran. Registry trials are returned sorted by trial identifier. The range check on p-values and null_policy below apply to a registry as they do to lists, arrays and tables, so a recorded metric outside [0, 1] raises.
The result has the adjusted_p_values table with the rank, the raw and the adjusted p-value and a rejected flag for each trial, in the input order. P-values outside [0, 1] raise an error, and missing values raise unless null_policy="drop". A registry cannot record a non-finite metric, so null_policy has nothing to drop there. Dropping missing p-values shrinks the family size , which weakens the adjustment for the tests that remain. Leave the default "raise", or replace a missing p-value with 1 yourself, so that every test you ran still counts. The finding is MULTIPLE_TESTING_DISCOVERIES when at least one trial survives and MULTIPLE_TESTING_NO_DISCOVERY otherwise.
effective_trials is for Bonferroni only. If your tests are strongly correlated, the number of independent tests is smaller than the number you ran, and you can supply that smaller number to avoid over-correcting. It must be between 1 and the trial count. Lacuna takes your word for it and records that the value was user-supplied.
| Parameter | Meaning |
|---|---|
data | A list or array of p-values, a table, or an ExperimentRegistry. |
p_value | The p-value column of a table, or the metric name for a registry. Default "p_value". |
trial | The trial identifier column of a table. Default "trial_id". |
method | One of the four methods. Default "holm". |
alpha | The significance level, strictly between 0 and 1. Default 0.05. |
effective_trials | The effective number of independent tests, for "bonferroni" only. |
null_policy | "raise" (default) or "drop" for missing p-values. |
Probability of Backtest Overfitting
probability_of_backtest_overfitting asks a question about a research process rather than about one strategy: if you pick the best-performing strategy in one part of the history, how often does it rank below the median in the rest? The method is combinatorially symmetric cross-validation (CSCV). It takes a matrix of strategy returns you have already computed. It does not fit models, which is what distinguishes it from the purged splits.
With a matrix and an even number of partitions , Lacuna splits the rows into equal contiguous groups. For each of the ways to choose half of the groups as in-sample, the other half is out-of-sample, and:
- The in-sample winner is the strategy with the best in-sample performance: the Sharpe ratio (mean over standard deviation,
ddof=1) or the plain mean, as chosen bystatistic. - Its out-of-sample relative rank is , where the rank is among the out-of-sample performances, ascending, so 1 is the worst, with ties given their average rank.
- The logit is .
A logit at or below zero means the winner landed at or below the out-of-sample median, and that counts as a failure. A PBO near 0 means the in-sample winners usually land above the out-of-sample median. A strategy picked at random would give a PBO of 0.5 when is even and when is odd, since a rank at or below the middle counts as a failure; a value above that level means the in-sample winner does worse than a random pick.
The result carries one finding, decided by the PBO at the main partitions value only, not by the sensitivity rows. BACKTEST_OVERFITTING_ELEVATED (WARN, high severity) is raised when PBO is above 0.5, and BACKTEST_OVERFITTING_LOW (PASS) otherwise. The PASS means the selection was not worse than a coin flip. It is not evidence that the strategy has skill.
rows = []
for label, family in (("noise only", noise_family), ("one real edge", edge_family)):
pbo = V.probability_of_backtest_overfitting(family, partition_sensitivity=(4, 6, 10))
for row in pbo.table("partition_sensitivity"):
rows.append(
{"family": label, "partitions": row["partitions"], "combinations": row["combinations"], "pbo": round(row["pbo"], 3)}
)
print(pl.DataFrame(rows)) shape: (8, 4)
┌───────────────┬────────────┬──────────────┬───────┐
│ family ┆ partitions ┆ combinations ┆ pbo │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ f64 │
╞═══════════════╪════════════╪══════════════╪═══════╡
│ noise only ┆ 8 ┆ 70 ┆ 0.714 │
│ noise only ┆ 4 ┆ 6 ┆ 0.667 │
│ noise only ┆ 6 ┆ 20 ┆ 0.65 │
│ noise only ┆ 10 ┆ 252 ┆ 0.504 │
│ one real edge ┆ 8 ┆ 70 ┆ 0.1 │
│ one real edge ┆ 4 ┆ 6 ┆ 0.167 │
│ one real edge ┆ 6 ┆ 20 ┆ 0.15 │
│ one real edge ┆ 10 ┆ 252 ┆ 0.107 │
└───────────────┴────────────┴──────────────┴───────┘ For the noise-only family PBO is well above zero at every partition count, and it moves a lot between them: 0.71 with eight partitions, 0.50 with ten. The family with a real edge has a PBO of 0.1 to 0.17 across the partition counts: the edge strategy is the in-sample winner in 63 of the 70 combinations and keeps a high out-of-sample rank. The noise-only number is not a stable estimate of the random-pick level or of anything else. It depends on the partition count and on this particular sample: with the seeds 42, 5 and 6 the same noise-only construction gave 0.34, 0.64 and 0.71 at eight partitions. Read it against the sensitivity table, never alone.
The combinations table lists the splits for the main partitions value, with the strategy selected in each and where it ranked out of sample:
pbo = V.probability_of_backtest_overfitting(edge_family)
print(
pl.DataFrame(pbo.table("combinations"))
.select("combination", "selected_strategy", "out_of_sample_rank", "relative_rank", "logit")
.head(3)
)
print(pbo.metrics["pbo"], pbo.metrics["n_combinations"]) shape: (3, 5)
┌─────────────┬───────────────────┬────────────────────┬───────────────┬──────────┐
│ combination ┆ selected_strategy ┆ out_of_sample_rank ┆ relative_rank ┆ logit │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪═══════════════════╪════════════════════╪═══════════════╪══════════╡
│ 0 ┆ s07 ┆ 12.0 ┆ 0.923077 ┆ 2.484907 │
│ 1 ┆ s07 ┆ 12.0 ┆ 0.923077 ┆ 2.484907 │
│ 2 ┆ s07 ┆ 11.0 ┆ 0.846154 ┆ 1.704748 │
└─────────────┴───────────────────┴────────────────────┴───────────────┴──────────┘
0.1 70 Some details that matter for interpretation:
- The row count must divide evenly by
partitions, or aDataContractErroris raised. The groups are contiguous in the order given, so sort the rows by time first. Nothing is purged between in-sample and out-of-sample groups, so autocorrelation across a group boundary is not removed. - If two strategies tie for best in-sample, the default
tie_break="raise"raises an error.tie_break="first"takes the lower column index, counts the ties inselection_tiesand adds a warning. Use it only if your column order is a rule you could defend. partitionsmust be even and at least 2. The number of combinations is capped bymax_combinations(20 000 by default); sixteen partitions give 12 870.- With
statistic="sharpe", a strategy with constant returns makes the Sharpe ratio undefined and raises aDataContractError. Usestatistic="mean"or remove the column. - PBO describes the family you supplied. Leave out failed variants and it will look better than your research process was. It is also not a false-discovery probability, as the result warns.
| Parameter | Meaning |
|---|---|
data | A table or two-dimensional array of strategy returns, rows synchronous and sorted by time. |
strategy_columns | The columns to use. By default every numeric column. |
partitions | The number of equal contiguous groups, an even integer. Default 8, which gives 70 combinations. |
statistic | "sharpe" (default) or "mean". |
partition_sensitivity | Other partition counts to evaluate, so you can see how much the answer depends on the choice. |
tie_break | "raise" (default) or "first". |
max_combinations | The safety limit on the number of combinations. |
Reality Check and SPA
Pick the best of strategies and test it against a benchmark with an ordinary test, and the p-value is wrong: you tested the maximum of noisy numbers. White’s Reality Check and Hansen’s Superior Predictive Ability test (SPA) are built for that. They test whether the best strategy in a declared family beats a benchmark by more than data snooping alone would produce.
Both take a table of performance differentials: each cell is a strategy’s performance minus the benchmark’s for that period, positive when the strategy is better. Lacuna does not compute the differentials, so the benchmark is whatever you subtracted. The null hypothesis is that no strategy has a positive expected differential. Both resample all columns jointly with the stationary bootstrap, so cross-strategy dependence is preserved.
For a differential matrix with column means over periods:
and over replicates. The Reality Check uses the unscaled means. SPA studentizes each mean by an estimate of its long-run standard deviation, which stops a few high-variance strategies from dominating the maximum, and recentres the bootstrap at one of three locations :
recentering | Use | |
|---|---|---|
lower | The least conservative p-value. | |
consistent | if , else 0 | Hansen’s recommended p-value, and the one the finding uses. |
upper | The most conservative; this is the Reality Check’s centring, studentized. |
Poor strategies, ones that are clearly worse than the benchmark, dilute the Reality Check, because its null is centred at zero for all of them. The consistent SPA recentring removes clearly poor strategies from consideration, so it has more power when the family contains many of them. The Reality Check’s result warns about this.
differentials = {"noise only": noise_family, "one real edge": edge_family}
rows = []
for label, family in differentials.items():
rc = V.reality_check(family, expected_block_length=5, resamples=1000, seed=3)
spa = V.superior_predictive_ability(family, expected_block_length=5, resamples=1000, seed=3)
rows.append(
{
"family": label,
"best": rc.metrics["best_strategy"],
"rc_p": round(rc.metrics["p_value"], 3),
"spa_lower": round(spa.metrics["p_value_lower"], 3),
"spa_consistent": round(spa.metrics["p_value_consistent"], 3),
"spa_upper": round(spa.metrics["p_value_upper"], 3),
}
)
print(pl.DataFrame(rows)) shape: (2, 6)
┌───────────────┬──────┬───────┬───────────┬────────────────┬───────────┐
│ family ┆ best ┆ rc_p ┆ spa_lower ┆ spa_consistent ┆ spa_upper │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═══════════════╪══════╪═══════╪═══════════╪════════════════╪═══════════╡
│ noise only ┆ s07 ┆ 0.327 ┆ 0.196 ┆ 0.248 ┆ 0.248 │
│ one real edge ┆ s07 ┆ 0.005 ┆ 0.001 ┆ 0.001 ┆ 0.001 │
└───────────────┴──────┴───────┴───────────┴────────────────┴───────────┘ Here the columns of each family are treated as differentials over a benchmark. In the noise-only family the best strategy is not distinguishable from luck: the p-values are between 0.2 and 0.33. In the family with one real edge the Reality Check gives 0.005 and SPA gives 0.001. SPA is smaller here because it studentizes the means and so is not dominated by the high-variance columns. The floor for a p-value is 1 / (resamples + 1), so 0.001 is as small as 1000 resamples can report.
Reading a result: a p-value at or below your chosen level means the best strategy’s advantage is too large to be explained by the best of this family under the null. The finding is REALITY_CHECK_SUPERIOR_CANDIDATE or SPA_SUPERIOR_CANDIDATE (state PASS) when the p-value is at most 0.05 (for SPA, the consistent p-value) and the observed statistic is positive. Otherwise it is REALITY_CHECK_NO_SUPERIOR_CANDIDATE or SPA_NO_SUPERIOR_CANDIDATE (state WARN). The 5% level is fixed. It does not say that the winner is the only good strategy, only that the family contains one. The tests are only as good as the family: strategies you tried and dropped must be in the matrix.
The strategy_statistics table lists each strategy’s mean differential. For SPA it also lists the long-run variance, the standardized mean, the recentering threshold and the three recentered locations, and the p_values table lists the three p-values with their exceedance counts. SPA requires a positive, finite long-run variance for every strategy, and the series should be stationary and weakly dependent.
expected_block_length is the mean block length of the stationary bootstrap, a positive integer no larger than the number of rows (0 raises here), defaulting to max(2, round(n ** (1/3))). Block-length sensitivity is part of the design: repeat with several values and report the range. joint_stationary_bootstrap and superior_predictive_ability take the same parameters as reality_check.
| Parameter | Meaning |
|---|---|
data | A table or two-dimensional array of performance differentials, rows synchronous. |
strategy_columns | The columns to use. By default every numeric column. |
expected_block_length | Mean block length for the stationary bootstrap. |
resamples | The number of bootstrap replicates, at least 100. Default 1000. |
seed | A non-negative integer for reproducibility. |
store_distribution | Keep the bootstrap statistics in a bootstrap_distribution table. |
Parameter surface
A strategy with a free parameter has a performance surface over the parameter’s values. If the setting you chose sits on a plateau, small changes keep the result. If it is a spike that its neighbours do not share, the result is probably a fit to noise. parameter_surface evaluates every point of a grid you declare and measures how well the selected point is supported by its neighbours.
You provide a function that takes a dictionary of parameters and returns an AnalysisResult with a numeric metric, which is the objective. The metrics of sharpe_inference work well. Lacuna calls it for every point of the grid.
rng = np.random.default_rng(21)
steps = rng.normal(0.0002, 0.01, 1500)
price = 100 * np.exp(np.cumsum(steps))
def moving_average(x, window):
c = np.cumsum(np.insert(x, 0, 0.0))
out = np.full(x.size, np.nan)
out[window - 1:] = (c[window:] - c[:-window]) / window
return out
def evaluate(params):
fast = moving_average(price, params["fast"])
slow = moving_average(price, params["slow"])
position = np.where(fast > slow, 1.0, -1.0)
strategy = (position[:-1] * steps[1:])[params["slow"]:]
return V.sharpe_inference(strategy, annualization=252)
surface = V.parameter_surface(
evaluate,
grid={"fast": [5, 10, 20, 40], "slow": [50, 100, 150, 200, 250]},
objective="observed_sharpe",
evaluator_name="sma_crossover",
sample_id="synthetic-seed-21",
code_id="docs-example",
)
metrics = surface.metrics
print({k: metrics[k] for k in ("attempted_points", "selected_objective", "local_median", "isolation_score", "plateau_width", "neighbor_count")})
print([(f.code, f.state.value) for f in surface.findings]) {'attempted_points': 20, 'selected_objective': 1.1893621587812722, 'local_median': 0.9897927317608253, 'isolation_score': 8.91873043620836, 'plateau_width': 1, 'neighbor_count': 3}
[('PARAMETER_ISOLATED_OPTIMUM', 'WARN'), ('PARAMETER_BOUNDARY_OPTIMUM', 'WARN'), ('PARAMETER_SELECTION_REUSE', 'WARN')] grid_table = pl.DataFrame(surface.table("parameter_surface"))
print(grid_table.pivot(on="slow", index="fast", values="objective").sort("fast").with_columns(pl.col(pl.Float64).round(2))) shape: (4, 6)
┌──────┬──────┬──────┬──────┬──────┬──────┐
│ fast ┆ 50 ┆ 100 ┆ 150 ┆ 200 ┆ 250 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════╪══════╪══════╪══════╪══════╪══════╡
│ 5 ┆ 0.05 ┆ 0.83 ┆ 0.71 ┆ 0.81 ┆ 0.95 │
│ 10 ┆ 0.18 ┆ 0.87 ┆ 0.92 ┆ 0.99 ┆ 1.05 │
│ 20 ┆ 0.32 ┆ 1.1 ┆ 0.97 ┆ 0.99 ┆ 0.81 │
│ 40 ┆ 0.99 ┆ 0.83 ┆ 1.01 ┆ 1.19 ┆ 0.79 │
└──────┴──────┴──────┴──────┴──────┴──────┘ The best point, fast=40 and slow=200 with a Sharpe ratio of 1.19, is the highest cell in the table. Its neighbours at distance one on the grid are 0.99, 1.01 and 0.79, and the surface findings say what that means.
The neighbourhood is the set of points at Manhattan distance up to neighborhood_radius in the position of each parameter’s value within the grid you declared, so the order you give the values in is the order of adjacency. Parameter names are sorted, the values within one parameter must be distinct (a duplicate raises an error), and the whole grid is evaluated, up to max_evaluations points.
The measures are:
| Metric | Meaning |
|---|---|
local_median, local_mad | The median and median absolute deviation of the successful neighbours’ objectives. |
isolation_score | for direction="maximize", with the gap reversed for "minimize". The scale is the larger of the raw MAD, 1e-12 times the absolute local median and machine epsilon, with no 1.4826 consistency factor, so a threshold of 3 means three raw MADs, not three standard deviations. With few neighbours, or a MAD of 0, the score is unreliable. |
plateau_width | The number of grid points connected to the selected point, by steps of one along one parameter, whose objective is within plateau_tolerance times the selected objective’s magnitude of it. A width of 1 means no neighbour is nearly as good. |
objective_to_local_median_ratio | The selected objective over the local median, when both have the same sign. |
neighbor_positive_fraction, neighbor_passing_fraction | The fraction of neighbours with a positive objective, and with an objective that meets evidence_threshold if you gave one. |
boundary_parameters | The parameters for which the selected value is the first or last value of the grid. |
The findings follow from them:
| Finding | State | When |
|---|---|---|
PARAMETER_ISOLATED_OPTIMUM | WARN | isolation_score >= isolation_threshold and plateau_width == 1. |
PARAMETER_LOCAL_STABILITY | PASS | There are at least two successful neighbours and the isolated-optimum condition is not met. |
PARAMETER_ISOLATION_UNKNOWN | UNKNOWN | Fewer than two neighbours succeeded, so isolation cannot be established. |
PARAMETER_BOUNDARY_OPTIMUM | WARN | The selected point is on the edge of the grid in some parameter, so the grid does not bracket it. Extend the grid. |
PARAMETER_SURFACE_NO_VALID_POINT | FAIL | Every point failed or had an undefined objective. |
PARAMETER_SELECTED_POINT_FAILED | FAIL | The point you passed in selected_parameters failed. |
PARAMETER_SURFACE_FAILURES | WARN | Some points failed. |
PARAMETER_SELECTION_REUSE | WARN | The surface was selected and evaluated on the same sample. |
PARAMETER_SELECTION_SEPARATION | PASS | You gave selected_parameters and a selection_sample_id different from sample_id. |
PARAMETER_SELECTION_SAMPLE_UNKNOWN | UNKNOWN | You gave selected_parameters without a selection_sample_id. |
In the example the selected point is isolated (its score is about 9, against a threshold of 3, and no neighbour is within 10% of it), it is on the boundary of the fast axis, and the selection reuses the evaluation sample, which is the case whenever the best point is picked from the same surface. The surface is descriptive, not independent evidence.
To judge a setting you chose in advance, or on other data, pass selected_parameters together with a selection_sample_id that differs from sample_id. Without selected_parameters the best point is selected on the evaluation sample and the reuse warning is reported, so a selection_sample_id that differs from sample_id is a contradiction and raises a MethodContractError. Pass it only together with selected_parameters, or leave it out. Lacuna records the two identities, but it cannot verify that the samples really are disjoint, so this is your statement:
chosen = V.parameter_surface(
evaluate,
grid={"fast": [5, 10, 20, 40], "slow": [50, 100, 150, 200, 250]},
objective="observed_sharpe",
evaluator_name="sma_crossover",
sample_id="validation-sample",
selection_sample_id="training-sample",
selected_parameters={"fast": 20, "slow": 100},
code_id="docs-example",
)
print([(f.code, f.state.value) for f in chosen.findings])
print(round(chosen.metrics["selected_objective"], 3), round(chosen.metrics["isolation_score"], 3)) [('PARAMETER_ISOLATED_OPTIMUM', 'WARN'), ('PARAMETER_SELECTION_SEPARATION', 'PASS')]
1.103 3.704 Here the chosen setting is declared to come from another sample, so PARAMETER_SELECTION_SEPARATION passes, but its neighbours are still much worse, so it is still flagged as isolated.
A point whose evaluator raises, or whose objective is missing or not finite, is recorded as failed with the exception’s type name, and the surface carries on (failure_policy="record"). With failure_policy="raise" the first failure propagates. Pass an ExperimentRegistry as registry to record every evaluation, successful or not, as an attempt; see Experiments.
| Parameter | Meaning |
|---|---|
evaluate | A function from a parameter dictionary to an AnalysisResult whose metrics contain objective. |
grid | A mapping from parameter name to an ordered list of values. The order defines adjacency. |
objective | The metric name to read from each evaluation, which must be a finite number. |
evaluator_name | A name for the evaluator, recorded in the result and in the registry. |
sample_id | An identifier for the data the surface is evaluated on. |
code_id | An identifier for the code version, recorded for provenance. |
evaluator_version | A version number for the evaluator. Default 1. |
direction | "maximize" (default) or "minimize". |
selected_parameters | A point on the grid to assess instead of the best one. |
selection_sample_id | An identifier for the data on which the selected point was chosen. Use it only together with selected_parameters: a value that differs from sample_id, given without them, raises MethodContractError. |
failure_policy | "record" (default) or "raise". |
neighborhood_radius | The Manhattan radius of the neighbourhood, in grid steps. Default 1. |
isolation_threshold | The isolation score at which an optimum is flagged. Default 3. |
plateau_tolerance | The relative tolerance for plateau membership. Default 0.1. |
evidence_threshold | An objective level that neighbours should meet; reported as neighbor_passing_fraction. |
max_evaluations | The largest grid the call will evaluate. Default 10 000. |
registry | An ExperimentRegistry that records every attempt. |
Reporting what you ran
None of these methods can protect you from a family you did not report. State how many strategies, parameter settings and variants you tried, give the multiple-testing or deflation method you applied, and give the block length and seed. The experiment registry is the place to keep the full set of attempts, so that the family you give to multiple_testing, reality_check or sharpe_inference is the one that was run and not the one that survived.
The full signatures are in the API reference.