onsetkit 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+ - Entity-aware onset labels for shuffled panels and global timestamp splits.
5
+ - Event recall, alarm precision, false-alarm rate and first-warning lead.
6
+ - Finite-population variance estimator with census and singleton handling.
7
+ - Panel example and expanded test suite.
8
+
9
+ ## 0.1.0
10
+ - Initial local prototype: onset labels, optimal integer allocation, weighted stratified sampling, forward splits.
onsetkit-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OnsetKit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include CHANGELOG.md RELEASING.md
2
+ recursive-include examples *.py
3
+ recursive-include tests *.py
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: onsetkit
3
+ Version: 0.2.0
4
+ Summary: Event-onset labels, optimal stratified sampling and temporal validation
5
+ Author: Jaskaran Singh
6
+ Maintainer: Jaskaran Singh
7
+ License-Expression: MIT
8
+ Project-URL: Repository, https://github.com/jaskaran04/onsetkit
9
+ Project-URL: Issues, https://github.com/jaskaran04/onsetkit/issues
10
+ Keywords: rare-events,time-series,regime-shifts,stratified-sampling,quantitative-finance
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.24
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7; extra == "dev"
21
+ Requires-Dist: build; extra == "dev"
22
+ Requires-Dist: twine; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # OnsetKit
26
+
27
+ **Construct, sample and validate rare-event forecasting datasets.**
28
+
29
+ OnsetKit is a NumPy-only toolkit for forward-looking event labels, finite-population stratified sampling and chronological validation. Applications include market volatility-regime transitions, liquidity shocks, equipment failures and operational incidents. It is experimental alpha software; it does not itself detect regimes or fit a forecasting model.
30
+
31
+ ## Install locally
32
+
33
+ Python 3.10+ is required. From the repository root:
34
+
35
+ ```sh
36
+ python -m pip install -e ".[dev]"
37
+ python -m pytest -q
38
+ python examples/regime_demo.py
39
+ python examples/panel_demo.py
40
+ ```
41
+
42
+ Public PyPI publication is pending.
43
+
44
+ ## Quick start
45
+
46
+ ```python
47
+ import numpy as np
48
+ from onsetkit import label_onsets, purged_forward_split, stratified_sample
49
+
50
+ active = np.zeros(1000, dtype=int)
51
+ active[100:120] = 1
52
+ active[400:420] = 1
53
+ active[800:820] = 1
54
+ result = label_onsets(active, horizon=5)
55
+ train, test = purged_forward_split(result.label_end, 700, 1000, gap=5)
56
+ y_train = result.labels[train]
57
+ sample = stratified_sample(y_train, budget=20, allocation="equal", seed=42)
58
+ selected_rows = train[sample.indices]
59
+ print(sample.estimate_mean(result.labels[selected_rows]))
60
+ # X must contain causal features aligned with the original rows.
61
+ # model.fit(X[selected_rows], result.labels[selected_rows], sample_weight=sample.weights)
62
+ ```
63
+
64
+ ### Label semantics
65
+
66
+ `label_onsets(active, horizon)` accepts an ordered binary state sequence. A 0-to-1 transition at row j is an onset. For inactive row t, the target is 1 if an onset occurs in t+1 through t+h inclusive. Active rows and rows without a complete future horizon are excluded (label -1). The initial active state is not treated as an observed onset. `label_end` is the inclusive end row of each complete horizon, or -1 for excluded rows. Labels are retrospective training targets, not deployable features. The caller supplies the regime definition; ex-post regime labels may require additional dating/availability buffers beyond the nominal horizon.
67
+
68
+ ### Sampling
69
+
70
+ `stratified_sample` selects uniformly without replacement within each stratum, with at least one observation per stratum by default. Indices are sorted and relative to the array supplied to the function, not the original dataset. Returned inclusion probabilities and inverse-probability weights are aligned to selected rows. The budget must be feasible. Allocation choices:
71
+
72
+ | Method | Objective |
73
+ | --- | --- |
74
+ | proportional | Equal scale across strata |
75
+ | equal | Minimize sum of reciprocal stratum sample counts |
76
+ | neyman | Minimize finite-population variance using supplied stratum scales |
77
+
78
+ For population stratum sizes N_h, scales S_h and sample counts n_h, the variable part of the variance of a stratified mean is proportional to sum(N_h^2 S_h^2 / n_h). `optimal_allocation` minimizes this separable objective under integer sample budgets and bounds by assigning each remaining unit to the largest marginal reduction. This is exact in real arithmetic; extreme floating-point scale ratios can introduce ties or underflow. The algorithm costs O((budget - sum(lower))*log(H)) for H strata. Zero-scale strata receive no extra units while positive marginal gains remain; ties are resolved by stratum index. Scales must be fixed before sampling and supplied in sorted unique stratum order; use an independent or training-only pilot. No claim is made that these scales are optimal for an arbitrary model's predictive loss.
79
+
80
+ Within a stratum, inclusion probability is n_h/N_h. `estimate_mean` implements the Horvitz–Thompson mean for fixed population values observed at selected rows. It is design-unbiased conditional on a fixed allocation and population; temporal independence is not required for that finite-population statement. This does not guarantee unbiased learned parameters, calibrated probabilities or out-of-sample performance. Inverse-probability weighting corrects the sampling design, not distribution shifts or leakage.
81
+
82
+ ### Temporal validation
83
+
84
+ `purged_forward_split(label_end, test_start, test_stop, gap=0)` uses half-open test row bounds. Training label ends must be strictly earlier than test_start-gap. Test labels must resolve strictly before test_stop. Empty splits are rejected. Apply sampling only after splitting; fit feature transforms and pilot scales on permitted training data. The splitter cannot infer future-dependent features, revision delays, or cross-entity information leakage. A gap does not establish statistical independence.
85
+
86
+ ## Demonstration
87
+
88
+ `examples/regime_demo.py` creates synthetic volatility regimes and compares original, sampled and weighted event prevalence. It is not a benchmark or a model forecast.
89
+
90
+ ## Multi-entity panels (v0.2.0)
91
+
92
+ ```python
93
+ from onsetkit import label_panel_onsets, panel_forward_split
94
+
95
+ # Arrays of equal length in any input row order; time can be numeric or np.datetime64.
96
+ r = label_panel_onsets(active, entities, time, horizon=5)
97
+ train, test = panel_forward_split(r.label_end, time, test_start=350,
98
+ test_stop=500, train_cutoff=340)
99
+ ```
100
+
101
+ Labels are computed separately in each entity's timestamp order and returned in the original row order. Duplicate timestamps within one entity are rejected; simultaneous timestamps across entities are allowed. The horizon counts observations within an entity, not elapsed time. `label_end` contains original row indices, so use `panel_forward_split`, not the single-series row-index splitter, for panel labels. The panel splitter applies one global time cutoff across all entities. It does not check external feature or regime-label availability, and assumes label-end indices come from the corresponding panel labels. Explicitly sort selected rows by time if the downstream model requires it.
102
+
103
+ ## Design-based variance
104
+
105
+ ```python
106
+ sample = stratified_sample(strata, budget=100, allocation="equal", minimum=2)
107
+ mean = sample.estimate_mean(values[sample.indices])
108
+ variance = sample.estimate_variance(values[sample.indices])
109
+ ```
110
+
111
+ For fixed finite-population attributes under independent stratified simple random sampling without replacement, the estimator is sum((N_h/N)^2 * (1 - n_h/N_h) * s_h^2/n_h). Census strata contribute zero. Noncensus strata with fewer than two sampled rows raise an error. This estimates the design variance of the population mean, not uncertainty from fitting a forecasting model, future market uncertainty or time-series process variance. The sample allocation must be fixed independently of the sampling draw.
112
+
113
+ ## Event-level evaluation
114
+
115
+ ```python
116
+ from onsetkit import event_metrics
117
+ m = event_metrics(active, alarms, horizon=5, evaluation_mask=held_out_mask)
118
+ print(m.event_recall, m.alarm_precision, m.mean_first_warning_lead)
119
+ ```
120
+
121
+ This single-sequence API scores binary alarms on eligible inactive rows with complete horizons, optionally restricted to a boolean evaluation mask. Each positive alarm is attributed to the next onset, not to every onset within the horizon. An event is evaluable only if at least one scored row could predict it as the next onset. Repeated alarms count once toward event recall and separately toward alarm precision. False alarm rate is false alarms divided by eligible negative rows. Mean first-warning lead is computed over detected events in observation rows. Undefined rates are NaN. Use a mask restricted to labels that resolve within the held-out block; for panels call separately on time-sorted entity sequences. These are operational metrics, not pointwise classifier metrics or a statistical significance test.
122
+
123
+ Run `python examples/panel_demo.py` for a shuffled multi-asset synthetic example, weighted sampling and random-alarm baseline.
124
+
125
+ ## Current limits
126
+
127
+ - Panel timestamps are used for ordering and splitting, but horizons count observations rather than elapsed time.
128
+ - Regime/event detection and forecasting models are supplied externally.
129
+ - No uncertainty intervals, streaming execution or probability calibration yet; event scoring is per sequence.
130
+ - No real-market or industrial performance benchmarks yet.
131
+ - NumPy arrays are mutable even inside frozen result dataclasses; treat them as read-only.
132
+
133
+ ## Roadmap
134
+
135
+ Explicit information availability timestamps, elapsed-time horizons, aggregate panel event metrics, calibration utilities, uncertainty intervals, and reproducible real-world financial and industrial benchmarks.
136
+
137
+ ## Contributing
138
+
139
+ Bug reports, reproducible examples and regression tests are welcome. MIT licence; review copyright attribution and research provenance before publication.
@@ -0,0 +1,115 @@
1
+ # OnsetKit
2
+
3
+ **Construct, sample and validate rare-event forecasting datasets.**
4
+
5
+ OnsetKit is a NumPy-only toolkit for forward-looking event labels, finite-population stratified sampling and chronological validation. Applications include market volatility-regime transitions, liquidity shocks, equipment failures and operational incidents. It is experimental alpha software; it does not itself detect regimes or fit a forecasting model.
6
+
7
+ ## Install locally
8
+
9
+ Python 3.10+ is required. From the repository root:
10
+
11
+ ```sh
12
+ python -m pip install -e ".[dev]"
13
+ python -m pytest -q
14
+ python examples/regime_demo.py
15
+ python examples/panel_demo.py
16
+ ```
17
+
18
+ Public PyPI publication is pending.
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ import numpy as np
24
+ from onsetkit import label_onsets, purged_forward_split, stratified_sample
25
+
26
+ active = np.zeros(1000, dtype=int)
27
+ active[100:120] = 1
28
+ active[400:420] = 1
29
+ active[800:820] = 1
30
+ result = label_onsets(active, horizon=5)
31
+ train, test = purged_forward_split(result.label_end, 700, 1000, gap=5)
32
+ y_train = result.labels[train]
33
+ sample = stratified_sample(y_train, budget=20, allocation="equal", seed=42)
34
+ selected_rows = train[sample.indices]
35
+ print(sample.estimate_mean(result.labels[selected_rows]))
36
+ # X must contain causal features aligned with the original rows.
37
+ # model.fit(X[selected_rows], result.labels[selected_rows], sample_weight=sample.weights)
38
+ ```
39
+
40
+ ### Label semantics
41
+
42
+ `label_onsets(active, horizon)` accepts an ordered binary state sequence. A 0-to-1 transition at row j is an onset. For inactive row t, the target is 1 if an onset occurs in t+1 through t+h inclusive. Active rows and rows without a complete future horizon are excluded (label -1). The initial active state is not treated as an observed onset. `label_end` is the inclusive end row of each complete horizon, or -1 for excluded rows. Labels are retrospective training targets, not deployable features. The caller supplies the regime definition; ex-post regime labels may require additional dating/availability buffers beyond the nominal horizon.
43
+
44
+ ### Sampling
45
+
46
+ `stratified_sample` selects uniformly without replacement within each stratum, with at least one observation per stratum by default. Indices are sorted and relative to the array supplied to the function, not the original dataset. Returned inclusion probabilities and inverse-probability weights are aligned to selected rows. The budget must be feasible. Allocation choices:
47
+
48
+ | Method | Objective |
49
+ | --- | --- |
50
+ | proportional | Equal scale across strata |
51
+ | equal | Minimize sum of reciprocal stratum sample counts |
52
+ | neyman | Minimize finite-population variance using supplied stratum scales |
53
+
54
+ For population stratum sizes N_h, scales S_h and sample counts n_h, the variable part of the variance of a stratified mean is proportional to sum(N_h^2 S_h^2 / n_h). `optimal_allocation` minimizes this separable objective under integer sample budgets and bounds by assigning each remaining unit to the largest marginal reduction. This is exact in real arithmetic; extreme floating-point scale ratios can introduce ties or underflow. The algorithm costs O((budget - sum(lower))*log(H)) for H strata. Zero-scale strata receive no extra units while positive marginal gains remain; ties are resolved by stratum index. Scales must be fixed before sampling and supplied in sorted unique stratum order; use an independent or training-only pilot. No claim is made that these scales are optimal for an arbitrary model's predictive loss.
55
+
56
+ Within a stratum, inclusion probability is n_h/N_h. `estimate_mean` implements the Horvitz–Thompson mean for fixed population values observed at selected rows. It is design-unbiased conditional on a fixed allocation and population; temporal independence is not required for that finite-population statement. This does not guarantee unbiased learned parameters, calibrated probabilities or out-of-sample performance. Inverse-probability weighting corrects the sampling design, not distribution shifts or leakage.
57
+
58
+ ### Temporal validation
59
+
60
+ `purged_forward_split(label_end, test_start, test_stop, gap=0)` uses half-open test row bounds. Training label ends must be strictly earlier than test_start-gap. Test labels must resolve strictly before test_stop. Empty splits are rejected. Apply sampling only after splitting; fit feature transforms and pilot scales on permitted training data. The splitter cannot infer future-dependent features, revision delays, or cross-entity information leakage. A gap does not establish statistical independence.
61
+
62
+ ## Demonstration
63
+
64
+ `examples/regime_demo.py` creates synthetic volatility regimes and compares original, sampled and weighted event prevalence. It is not a benchmark or a model forecast.
65
+
66
+ ## Multi-entity panels (v0.2.0)
67
+
68
+ ```python
69
+ from onsetkit import label_panel_onsets, panel_forward_split
70
+
71
+ # Arrays of equal length in any input row order; time can be numeric or np.datetime64.
72
+ r = label_panel_onsets(active, entities, time, horizon=5)
73
+ train, test = panel_forward_split(r.label_end, time, test_start=350,
74
+ test_stop=500, train_cutoff=340)
75
+ ```
76
+
77
+ Labels are computed separately in each entity's timestamp order and returned in the original row order. Duplicate timestamps within one entity are rejected; simultaneous timestamps across entities are allowed. The horizon counts observations within an entity, not elapsed time. `label_end` contains original row indices, so use `panel_forward_split`, not the single-series row-index splitter, for panel labels. The panel splitter applies one global time cutoff across all entities. It does not check external feature or regime-label availability, and assumes label-end indices come from the corresponding panel labels. Explicitly sort selected rows by time if the downstream model requires it.
78
+
79
+ ## Design-based variance
80
+
81
+ ```python
82
+ sample = stratified_sample(strata, budget=100, allocation="equal", minimum=2)
83
+ mean = sample.estimate_mean(values[sample.indices])
84
+ variance = sample.estimate_variance(values[sample.indices])
85
+ ```
86
+
87
+ For fixed finite-population attributes under independent stratified simple random sampling without replacement, the estimator is sum((N_h/N)^2 * (1 - n_h/N_h) * s_h^2/n_h). Census strata contribute zero. Noncensus strata with fewer than two sampled rows raise an error. This estimates the design variance of the population mean, not uncertainty from fitting a forecasting model, future market uncertainty or time-series process variance. The sample allocation must be fixed independently of the sampling draw.
88
+
89
+ ## Event-level evaluation
90
+
91
+ ```python
92
+ from onsetkit import event_metrics
93
+ m = event_metrics(active, alarms, horizon=5, evaluation_mask=held_out_mask)
94
+ print(m.event_recall, m.alarm_precision, m.mean_first_warning_lead)
95
+ ```
96
+
97
+ This single-sequence API scores binary alarms on eligible inactive rows with complete horizons, optionally restricted to a boolean evaluation mask. Each positive alarm is attributed to the next onset, not to every onset within the horizon. An event is evaluable only if at least one scored row could predict it as the next onset. Repeated alarms count once toward event recall and separately toward alarm precision. False alarm rate is false alarms divided by eligible negative rows. Mean first-warning lead is computed over detected events in observation rows. Undefined rates are NaN. Use a mask restricted to labels that resolve within the held-out block; for panels call separately on time-sorted entity sequences. These are operational metrics, not pointwise classifier metrics or a statistical significance test.
98
+
99
+ Run `python examples/panel_demo.py` for a shuffled multi-asset synthetic example, weighted sampling and random-alarm baseline.
100
+
101
+ ## Current limits
102
+
103
+ - Panel timestamps are used for ordering and splitting, but horizons count observations rather than elapsed time.
104
+ - Regime/event detection and forecasting models are supplied externally.
105
+ - No uncertainty intervals, streaming execution or probability calibration yet; event scoring is per sequence.
106
+ - No real-market or industrial performance benchmarks yet.
107
+ - NumPy arrays are mutable even inside frozen result dataclasses; treat them as read-only.
108
+
109
+ ## Roadmap
110
+
111
+ Explicit information availability timestamps, elapsed-time horizons, aggregate panel event metrics, calibration utilities, uncertainty intervals, and reproducible real-world financial and industrial benchmarks.
112
+
113
+ ## Contributing
114
+
115
+ Bug reports, reproducible examples and regression tests are welcome. MIT licence; review copyright attribution and research provenance before publication.
@@ -0,0 +1,9 @@
1
+ # Release checklist
2
+
3
+ 1. Confirm project ownership, author metadata, MIT attribution and intended repository URL. Add project URLs to pyproject.toml after the GitHub repository exists.
4
+ 2. Run `python -m pytest -v` and `python examples/regime_demo.py`.
5
+ 3. Run `python -m build` and `python -m twine check --strict dist/*` in a clean working tree.
6
+ 4. Push to a separate GitHub repository and verify CI on Windows and Linux.
7
+ 5. Configure a project-specific pending Trusted Publisher on TestPyPI and a matching GitHub environment, with deployment limited to main. Use workflow_dispatch and separate build and publishing jobs, with id-token: write only on the publishing job. Verify the package in a clean environment, installing NumPy from official PyPI first and OnsetKit from TestPyPI with --no-deps.
8
+ 6. Configure a separate official PyPI publisher and environment. Publish only after tests and metadata review. Verify normal pip installation in another clean environment.
9
+ 7. Tag the published commit and document the release. Do not upload the same version twice. Do not commit credentials.
@@ -0,0 +1,32 @@
1
+ """Synthetic multi-asset labels, held-out event scores and weighted statistics."""
2
+ import numpy as np
3
+ from onsetkit import label_panel_onsets, panel_forward_split, stratified_sample, event_metrics
4
+
5
+ rng = np.random.default_rng(42)
6
+ n, assets = 500, 3
7
+ time = np.tile(np.arange(n), assets)
8
+ entity = np.repeat(['A','B','C'], n)
9
+ active = np.zeros(n * assets, dtype=int)
10
+ for i in range(assets):
11
+ for t in range(40 + 3*i, n-10, 70):
12
+ active[i*n+t:i*n+t+7] = 1
13
+ # Random order intentionally exercises entity/time sorting.
14
+ order = rng.permutation(len(time))
15
+ time, entity, active = time[order], entity[order], active[order]
16
+ r = label_panel_onsets(active, entity, time, horizon=5)
17
+ train, test = panel_forward_split(r.label_end, time, 350, 500, train_cutoff=340)
18
+ s = stratified_sample(r.labels[train], budget=100, allocation='equal', minimum=2, seed=42)
19
+ print(f'Training rows: {len(train)}; test rows: {len(test)}; sample: {len(s.indices)}')
20
+ print(f'Population prevalence: {r.labels[train].mean():.4%}')
21
+ print(f'Weighted prevalence: {s.estimate_mean(r.labels[train[s.indices]]):.4%}')
22
+ # A fixed synthetic attribute, not a learned model's in-sample error.
23
+ values = rng.normal(size=len(time))
24
+ print(f'Weighted attribute mean: {s.estimate_mean(values[train[s.indices]]):.4f}')
25
+ print(f'Estimated design standard error: {np.sqrt(s.estimate_variance(values[train[s.indices]])):.4f}')
26
+ # Random alarm baseline; no claim of predictive ability.
27
+ alarms = rng.random(len(time)) < 0.15
28
+ for asset in np.unique(entity):
29
+ rows = np.flatnonzero(entity == asset)
30
+ rows = rows[np.argsort(time[rows])]
31
+ m = event_metrics(active[rows], alarms[rows], 5, evaluation_mask=np.isin(rows, test))
32
+ print(f'{asset}: events {m.detected_events}/{m.eligible_events}; alarms {m.alarms}; false alarms {m.false_alarms}')
@@ -0,0 +1,22 @@
1
+ """Synthetic volatility-regime labels; no fitted forecasting model."""
2
+ import numpy as np
3
+ from onsetkit import label_onsets, purged_forward_split, stratified_sample
4
+
5
+ rng = np.random.default_rng(42)
6
+ n = 10000
7
+ active = np.zeros(n, dtype=int)
8
+ for start in range(200, n-30, 400):
9
+ active[start:start+20] = 1
10
+ returns = rng.normal(0, np.where(active, .035, .008))
11
+ labels = label_onsets(active, horizon=5)
12
+ train, test = purged_forward_split(labels.label_end, 8000, n, gap=20)
13
+ y = labels.labels[train]
14
+ sample = stratified_sample(y, 200, allocation='equal', seed=42)
15
+ selected = train[sample.indices]
16
+ print(f'Eligible training rows: {len(train)}; test rows: {len(test)}')
17
+ print(f'Original onset prevalence: {y.mean():.4%}')
18
+ print(f'Sampled onset prevalence: {labels.labels[selected].mean():.4%}')
19
+ print(f'Weighted onset prevalence: {sample.estimate_mean(labels.labels[selected]):.4%}')
20
+ print(f'Stratum counts: {sample.counts}; allocation: {sample.allocation}')
21
+ assert np.isclose(sample.estimate_mean(labels.labels[selected]), y.mean())
22
+ assert max(labels.label_end[train]) < min(test)-20
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "onsetkit"
7
+ version = "0.2.0"
8
+ description = "Event-onset labels, optimal stratified sampling and temporal validation"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["numpy>=1.24"]
14
+ authors = [{name = "Jaskaran Singh"}]
15
+ maintainers = [{name = "Jaskaran Singh"}]
16
+ keywords = ["rare-events", "time-series", "regime-shifts", "stratified-sampling", "quantitative-finance"]
17
+ classifiers = ["Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering"]
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/jaskaran04/onsetkit"
21
+ Issues = "https://github.com/jaskaran04/onsetkit/issues"
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["pytest>=7", "build", "twine"]
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
28
+
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """Tools for forward-onset forecasting datasets and finite-population sampling."""
2
+ from .core import (OnsetLabels, StratifiedSample, label_onsets, optimal_allocation,
3
+ stratified_sample, purged_forward_split)
4
+ from .panel import label_panel_onsets, panel_forward_split
5
+ from .metrics import EventMetrics, event_metrics
6
+ __version__ = '0.2.0'
7
+ __all__ = ['OnsetLabels', 'StratifiedSample', 'label_onsets', 'optimal_allocation',
8
+ 'stratified_sample', 'purged_forward_split', 'label_panel_onsets',
9
+ 'panel_forward_split', 'EventMetrics', 'event_metrics']
@@ -0,0 +1,189 @@
1
+ """Finite-population sampling and forward-onset labels on ordered rows."""
2
+ from dataclasses import dataclass
3
+ import heapq
4
+ from numbers import Integral
5
+ import numpy as np
6
+
7
+
8
+ def _integer(value, name, minimum=1):
9
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < minimum:
10
+ raise ValueError(f'{name} must be an integer >= {minimum}')
11
+ return int(value)
12
+
13
+
14
+ def _vector(x, name):
15
+ a = np.asarray(x)
16
+ if a.ndim != 1 or not a.size:
17
+ raise ValueError(f'{name} must be a nonempty one-dimensional array')
18
+ return a
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class OnsetLabels:
23
+ labels: np.ndarray # -1 means excluded / censored
24
+ eligible: np.ndarray
25
+ onset: np.ndarray
26
+ label_end: np.ndarray # inclusive row; -1 for excluded
27
+
28
+
29
+ def label_onsets(active, horizon):
30
+ """Predict a 0->1 transition in rows t+1,...,t+h, excluding active rows.
31
+
32
+ The first row is never an onset (prior state unknown). All incomplete
33
+ future windows are excluded, even if a positive is already observable.
34
+ """
35
+ a = _vector(active, 'active')
36
+ h = _integer(horizon, 'horizon')
37
+ if a.dtype.kind not in 'biuf' or not np.all(np.isin(a, [0, 1])):
38
+ raise ValueError('active must contain only binary states')
39
+ a = a.astype(bool)
40
+ n = len(a)
41
+ onset = np.zeros(n, dtype=bool)
42
+ onset[1:] = a[1:] & ~a[:-1]
43
+ idx = np.arange(n)
44
+ eligible = ~a & (idx < n - h)
45
+ labels = np.full(n, -1, dtype=np.int8)
46
+ end = np.full(n, -1, dtype=np.int64)
47
+ t = idx[eligible]
48
+ cumulative = np.r_[0, np.cumsum(onset, dtype=np.int64)]
49
+ labels[t] = cumulative[t+h+1] > cumulative[t+1]
50
+ end[t] = t+h
51
+ return OnsetLabels(labels, eligible, onset, end)
52
+
53
+
54
+ def optimal_allocation(counts, scales, budget, *, minimum=1):
55
+ """Exact integer minimizer of sum N_h**2 * S_h**2 / n_h.
56
+
57
+ Bounds: min(minimum,N_h) <= n_h <= N_h. Uses diminishing marginal
58
+ gains; O((budget-sum(lower))*log(H)). Zero gains break ties by
59
+ stratum index. Scales are supplied or pilot estimates, not fitted models.
60
+ """
61
+ N = _vector(counts, 'counts')
62
+ if N.dtype.kind not in 'iu' or np.any(N <= 0) or np.any(N > np.iinfo(np.int64).max):
63
+ raise ValueError('counts must be positive integers within int64')
64
+ N = N.astype(np.int64)
65
+ S = _vector(scales, 'scales').astype(float)
66
+ if len(N) != len(S) or np.any(~np.isfinite(S)) or np.any(S < 0):
67
+ raise ValueError('scales must be finite, nonnegative and match counts')
68
+ k = _integer(budget, 'budget')
69
+ m = _integer(minimum, 'minimum')
70
+ lower = np.minimum(N, m) if m <= int(N.max()) else N.copy()
71
+ if not sum(map(int, lower)) <= k <= sum(map(int, N)):
72
+ raise ValueError('budget infeasible under stratum bounds')
73
+ if k == sum(map(int, N)):
74
+ return N.copy()
75
+ # Normalize both factors before multiplying to avoid overflow.
76
+ if np.max(S) == 0:
77
+ A = np.zeros(len(N))
78
+ else:
79
+ A = ((N / N.max()) * (S / S.max())) ** 2
80
+ out = lower.copy()
81
+ def gain(i):
82
+ q = int(out[i])
83
+ return float(A[i]) / q / (q+1)
84
+ heap = [(-gain(i), i) for i in range(len(N)) if out[i] < N[i]]
85
+ heapq.heapify(heap)
86
+ for _ in range(k - sum(map(int, out))):
87
+ _, i = heapq.heappop(heap)
88
+ out[i] += 1
89
+ if out[i] < N[i]:
90
+ heapq.heappush(heap, (-gain(i), i))
91
+ return out
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class StratifiedSample:
96
+ indices: np.ndarray
97
+ inclusion_probabilities: np.ndarray
98
+ weights: np.ndarray
99
+ strata: np.ndarray
100
+ counts: np.ndarray
101
+ allocation: np.ndarray
102
+ population_size: int
103
+ sampled_strata: np.ndarray | None = None # integer stratum codes
104
+
105
+ def estimate_mean(self, values):
106
+ """Horvitz-Thompson population mean of fixed values at sampled rows."""
107
+ v = _vector(values, 'values').astype(float)
108
+ if len(v) != len(self.indices) or not np.all(np.isfinite(v)):
109
+ raise ValueError('values must be finite and aligned to sampled indices')
110
+ return float(np.dot(v, self.weights) / self.population_size)
111
+
112
+
113
+ def estimate_variance(self, values):
114
+ """Design-unbiased estimated variance of the HT mean under stratified SRS.
115
+
116
+ Noncensus strata require at least two sampled rows. Values must be fixed
117
+ population attributes, not predictions fitted using this same sample.
118
+ """
119
+ v = _vector(values, 'values').astype(float)
120
+ if len(v) != len(self.indices) or not np.all(np.isfinite(v)):
121
+ raise ValueError('values must be finite and aligned to sampled indices')
122
+ if self.sampled_strata is None:
123
+ raise ValueError('sampled stratum codes are unavailable')
124
+ if np.any((self.allocation < self.counts) & (self.allocation < 2)):
125
+ raise ValueError('noncensus strata require at least two observations')
126
+ total = 0.0
127
+ for i, (N, n) in enumerate(zip(self.counts, self.allocation)):
128
+ if n < N:
129
+ s2 = np.var(v[self.sampled_strata == i], ddof=1)
130
+ total += (int(N) / self.population_size)**2 * (1 - n/N) * s2/n
131
+ return float(total)
132
+
133
+
134
+ def stratified_sample(strata, budget, *, allocation='proportional', scales=None,
135
+ minimum=1, seed=0):
136
+ """SRS without replacement independently within each observed stratum.
137
+
138
+ allocation: proportional (equal scales), equal (scales 1/N), or neyman
139
+ (user-supplied scales aligned to sorted unique stratum labels).
140
+ """
141
+ s = _vector(strata, 'strata')
142
+ if s.dtype.kind not in 'biufUS' or (s.dtype.kind == 'f' and not np.all(np.isfinite(s))):
143
+ raise ValueError('strata must be finite numeric or string labels')
144
+ names, inverse, N = np.unique(s, return_inverse=True, return_counts=True)
145
+ if allocation == 'proportional' and scales is None:
146
+ S = np.ones(len(N))
147
+ elif allocation == 'equal' and scales is None:
148
+ S = 1 / N
149
+ elif allocation == 'neyman' and scales is not None:
150
+ S = scales
151
+ else:
152
+ raise ValueError('choose proportional/equal without scales, or neyman with scales')
153
+ n = optimal_allocation(N, S, budget, minimum=minimum)
154
+ rng = np.random.default_rng(_integer(seed, 'seed', 0))
155
+ # Group once, rather than scanning the population for each stratum.
156
+ order = np.argsort(inverse, kind='stable')
157
+ offsets = np.r_[0, np.cumsum(N)]
158
+ selected = [rng.choice(order[offsets[i]:offsets[i+1]], size=int(k), replace=False)
159
+ for i, k in enumerate(n)]
160
+ idx = np.sort(np.concatenate(selected))
161
+ p = (n / N)[inverse[idx]]
162
+ return StratifiedSample(idx, p, 1/p, names, N, n, len(s), inverse[idx])
163
+
164
+
165
+ def purged_forward_split(label_end, test_start, test_stop, *, gap=0):
166
+ """Return eligible train/test row indices for one forward block.
167
+
168
+ Train labels must end strictly before test_start-gap; test rows lie
169
+ in [test_start,test_stop), with label ends strictly before test_stop.
170
+ Excluded rows use -1. gap is additional pre-test buffer in rows.
171
+ """
172
+ end = _vector(label_end, 'label_end')
173
+ if end.dtype.kind != 'i':
174
+ raise ValueError('label_end must be signed integer row indices')
175
+ n = len(end)
176
+ start = _integer(test_start, 'test_start')
177
+ stop = _integer(test_stop, 'test_stop')
178
+ g = _integer(gap, 'gap', 0)
179
+ t = np.arange(n)
180
+ valid = end >= 0
181
+ if np.any(end < -1) or np.any(valid & ((end < t) | (end >= n))):
182
+ raise ValueError('label_end must be -1 or a valid inclusive end row >= start row')
183
+ if not start < stop <= n or g >= start:
184
+ raise ValueError('invalid test block or gap')
185
+ train = t[valid & (t < start) & (end < start-g)]
186
+ test = t[valid & (t >= start) & (t < stop) & (end < stop)]
187
+ if not len(train) or not len(test):
188
+ raise ValueError('split has no eligible training or test rows')
189
+ return train, test
@@ -0,0 +1,56 @@
1
+ """Event-centric evaluation for a single ordered binary regime sequence."""
2
+ from dataclasses import dataclass
3
+ import numpy as np
4
+ from .core import _vector, label_onsets
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class EventMetrics:
9
+ eligible_rows: int
10
+ eligible_events: int
11
+ detected_events: int
12
+ alarms: int
13
+ true_alarms: int
14
+ false_alarms: int
15
+ event_recall: float
16
+ alarm_precision: float
17
+ false_alarm_rate: float
18
+ mean_first_warning_lead: float
19
+
20
+
21
+ def event_metrics(active, alarms, horizon, *, evaluation_mask=None):
22
+ """Score binary alarms, attributing each to the next onset within horizon.
23
+
24
+ Only eligible inactive rows with complete horizons and a true evaluation
25
+ mask are scored. Events count only if at least one scored row could have
26
+ predicted them as the next onset. Multiple alarms for one onset count once
27
+ toward event recall, but separately toward alarm precision. Undefined rates
28
+ are NaN. Lead is measured in observation rows, not clock time.
29
+ """
30
+ r = label_onsets(active, horizon)
31
+ a = _vector(alarms, 'alarms')
32
+ if len(a) != len(r.labels) or a.dtype.kind not in 'biuf' or not np.all(np.isin(a, [0, 1])):
33
+ raise ValueError('alarms must be aligned binary values')
34
+ mask = r.eligible.copy()
35
+ if evaluation_mask is not None:
36
+ m = _vector(evaluation_mask, 'evaluation_mask')
37
+ if len(m) != len(a) or m.dtype.kind != 'b':
38
+ raise ValueError('evaluation_mask must be aligned boolean values')
39
+ mask &= m
40
+ rows = np.flatnonzero(mask)
41
+ positive = rows[r.labels[rows] == 1]
42
+ onsets = np.flatnonzero(r.onset)
43
+ targets = onsets[np.searchsorted(onsets, positive, side='right')]
44
+ alerted = a[positive].astype(bool)
45
+ detected, first = np.unique(targets[alerted], return_index=True)
46
+ leads = detected - positive[alerted][first]
47
+ events = len(np.unique(targets))
48
+ n_alarm = int(np.count_nonzero(a[rows]))
49
+ tp = int(np.count_nonzero(alerted))
50
+ fp = n_alarm - tp
51
+ negatives = len(rows) - len(positive)
52
+ def ratio(x, y):
53
+ return x/y if y else float('nan')
54
+ return EventMetrics(len(rows), events, len(detected), n_alarm, tp, fp,
55
+ ratio(len(detected), events), ratio(tp, n_alarm),
56
+ ratio(fp, negatives), float(np.mean(leads)) if len(leads) else float('nan'))
@@ -0,0 +1,74 @@
1
+ """Entity-aware labels and chronological splits for interleaved panel rows."""
2
+ import numpy as np
3
+ from .core import OnsetLabels, _vector, _integer, label_onsets
4
+
5
+
6
+ def _time_vector(time):
7
+ t = _vector(time, 'time')
8
+ if t.dtype.kind not in 'iufM' or (t.dtype.kind == 'M' and np.any(np.isnat(t))) or (t.dtype.kind == 'f' and not np.all(np.isfinite(t))):
9
+ raise ValueError('time must contain finite numeric or datetime64 values')
10
+ return t
11
+
12
+
13
+ def label_panel_onsets(active, entities, time, horizon):
14
+ """Label each entity in timestamp order; return arrays in input row order.
15
+
16
+ Horizon counts observations within an entity, not elapsed clock time.
17
+ label_end contains original input row indices, not positions after sorting.
18
+ Duplicate timestamps within an entity are rejected.
19
+ """
20
+ a = _vector(active, 'active')
21
+ e = _vector(entities, 'entities')
22
+ t = _time_vector(time)
23
+ h = _integer(horizon, 'horizon')
24
+ if len(a) != len(e) or len(a) != len(t):
25
+ raise ValueError('active, entities and time must have matching lengths')
26
+ if e.dtype.kind not in 'biufUS' or (e.dtype.kind == 'f' and not np.all(np.isfinite(e))):
27
+ raise ValueError('entities must be finite numeric or string labels')
28
+ _, groups = np.unique(e, return_inverse=True)
29
+ order = np.lexsort((t, groups))
30
+ boundaries = np.r_[0, np.flatnonzero(np.diff(groups[order])) + 1, len(a)]
31
+ labels = np.full(len(a), -1, dtype=np.int8)
32
+ eligible = np.zeros(len(a), dtype=bool)
33
+ onset = eligible.copy()
34
+ end = np.full(len(a), -1, dtype=np.int64)
35
+ for lo, hi in zip(boundaries[:-1], boundaries[1:]):
36
+ idx = order[lo:hi]
37
+ if np.any(t[idx][1:] == t[idx][:-1]):
38
+ raise ValueError('duplicate timestamps within an entity')
39
+ r = label_onsets(a[idx], h)
40
+ labels[idx], eligible[idx], onset[idx] = r.labels, r.eligible, r.onset
41
+ end[idx[r.eligible]] = idx[r.label_end[r.eligible]]
42
+ return OnsetLabels(labels, eligible, onset, end)
43
+
44
+
45
+ def panel_forward_split(label_end, time, test_start, test_stop, *, train_cutoff=None):
46
+ """Global timestamp split with inclusive label ends and exclusive cutoffs.
47
+
48
+ train_cutoff defaults to test_start; set earlier for an additional buffer.
49
+ Pass numeric bounds for numeric timestamps and datetime64 bounds for dates.
50
+ Returns original row indices in input order; no entity crosses the cutoff
51
+ through a label horizon. Does not check external feature availability.
52
+ """
53
+ t = _time_vector(time)
54
+ end = _vector(label_end, 'label_end')
55
+ if len(t) != len(end) or end.dtype.kind != 'i' or np.any(end < -1) or np.any(end >= len(t)):
56
+ raise ValueError('label_end must be aligned signed indices or -1')
57
+ def bound(x):
58
+ b = np.asarray(x)
59
+ if b.ndim != 0 or (t.dtype.kind == 'M' and (b.dtype.kind != 'M' or np.isnat(b))) or (t.dtype.kind != 'M' and (b.dtype.kind not in 'iuf' or not np.isfinite(b))):
60
+ raise ValueError('invalid timestamp bound')
61
+ return b
62
+ start, stop = bound(test_start), bound(test_stop)
63
+ cutoff = start if train_cutoff is None else bound(train_cutoff)
64
+ if not cutoff <= start < stop:
65
+ raise ValueError('require train_cutoff <= test_start < test_stop')
66
+ rows = np.flatnonzero(end >= 0)
67
+ ends = t[end[rows]]
68
+ if np.any(ends < t[rows]):
69
+ raise ValueError('label ends cannot precede their rows in time')
70
+ train = rows[(t[rows] < cutoff) & (ends < cutoff)]
71
+ test = rows[(t[rows] >= start) & (t[rows] < stop) & (ends < stop)]
72
+ if not len(train) or not len(test):
73
+ raise ValueError('split has no eligible training or test rows')
74
+ return train, test
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: onsetkit
3
+ Version: 0.2.0
4
+ Summary: Event-onset labels, optimal stratified sampling and temporal validation
5
+ Author: Jaskaran Singh
6
+ Maintainer: Jaskaran Singh
7
+ License-Expression: MIT
8
+ Project-URL: Repository, https://github.com/jaskaran04/onsetkit
9
+ Project-URL: Issues, https://github.com/jaskaran04/onsetkit/issues
10
+ Keywords: rare-events,time-series,regime-shifts,stratified-sampling,quantitative-finance
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.24
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7; extra == "dev"
21
+ Requires-Dist: build; extra == "dev"
22
+ Requires-Dist: twine; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # OnsetKit
26
+
27
+ **Construct, sample and validate rare-event forecasting datasets.**
28
+
29
+ OnsetKit is a NumPy-only toolkit for forward-looking event labels, finite-population stratified sampling and chronological validation. Applications include market volatility-regime transitions, liquidity shocks, equipment failures and operational incidents. It is experimental alpha software; it does not itself detect regimes or fit a forecasting model.
30
+
31
+ ## Install locally
32
+
33
+ Python 3.10+ is required. From the repository root:
34
+
35
+ ```sh
36
+ python -m pip install -e ".[dev]"
37
+ python -m pytest -q
38
+ python examples/regime_demo.py
39
+ python examples/panel_demo.py
40
+ ```
41
+
42
+ Public PyPI publication is pending.
43
+
44
+ ## Quick start
45
+
46
+ ```python
47
+ import numpy as np
48
+ from onsetkit import label_onsets, purged_forward_split, stratified_sample
49
+
50
+ active = np.zeros(1000, dtype=int)
51
+ active[100:120] = 1
52
+ active[400:420] = 1
53
+ active[800:820] = 1
54
+ result = label_onsets(active, horizon=5)
55
+ train, test = purged_forward_split(result.label_end, 700, 1000, gap=5)
56
+ y_train = result.labels[train]
57
+ sample = stratified_sample(y_train, budget=20, allocation="equal", seed=42)
58
+ selected_rows = train[sample.indices]
59
+ print(sample.estimate_mean(result.labels[selected_rows]))
60
+ # X must contain causal features aligned with the original rows.
61
+ # model.fit(X[selected_rows], result.labels[selected_rows], sample_weight=sample.weights)
62
+ ```
63
+
64
+ ### Label semantics
65
+
66
+ `label_onsets(active, horizon)` accepts an ordered binary state sequence. A 0-to-1 transition at row j is an onset. For inactive row t, the target is 1 if an onset occurs in t+1 through t+h inclusive. Active rows and rows without a complete future horizon are excluded (label -1). The initial active state is not treated as an observed onset. `label_end` is the inclusive end row of each complete horizon, or -1 for excluded rows. Labels are retrospective training targets, not deployable features. The caller supplies the regime definition; ex-post regime labels may require additional dating/availability buffers beyond the nominal horizon.
67
+
68
+ ### Sampling
69
+
70
+ `stratified_sample` selects uniformly without replacement within each stratum, with at least one observation per stratum by default. Indices are sorted and relative to the array supplied to the function, not the original dataset. Returned inclusion probabilities and inverse-probability weights are aligned to selected rows. The budget must be feasible. Allocation choices:
71
+
72
+ | Method | Objective |
73
+ | --- | --- |
74
+ | proportional | Equal scale across strata |
75
+ | equal | Minimize sum of reciprocal stratum sample counts |
76
+ | neyman | Minimize finite-population variance using supplied stratum scales |
77
+
78
+ For population stratum sizes N_h, scales S_h and sample counts n_h, the variable part of the variance of a stratified mean is proportional to sum(N_h^2 S_h^2 / n_h). `optimal_allocation` minimizes this separable objective under integer sample budgets and bounds by assigning each remaining unit to the largest marginal reduction. This is exact in real arithmetic; extreme floating-point scale ratios can introduce ties or underflow. The algorithm costs O((budget - sum(lower))*log(H)) for H strata. Zero-scale strata receive no extra units while positive marginal gains remain; ties are resolved by stratum index. Scales must be fixed before sampling and supplied in sorted unique stratum order; use an independent or training-only pilot. No claim is made that these scales are optimal for an arbitrary model's predictive loss.
79
+
80
+ Within a stratum, inclusion probability is n_h/N_h. `estimate_mean` implements the Horvitz–Thompson mean for fixed population values observed at selected rows. It is design-unbiased conditional on a fixed allocation and population; temporal independence is not required for that finite-population statement. This does not guarantee unbiased learned parameters, calibrated probabilities or out-of-sample performance. Inverse-probability weighting corrects the sampling design, not distribution shifts or leakage.
81
+
82
+ ### Temporal validation
83
+
84
+ `purged_forward_split(label_end, test_start, test_stop, gap=0)` uses half-open test row bounds. Training label ends must be strictly earlier than test_start-gap. Test labels must resolve strictly before test_stop. Empty splits are rejected. Apply sampling only after splitting; fit feature transforms and pilot scales on permitted training data. The splitter cannot infer future-dependent features, revision delays, or cross-entity information leakage. A gap does not establish statistical independence.
85
+
86
+ ## Demonstration
87
+
88
+ `examples/regime_demo.py` creates synthetic volatility regimes and compares original, sampled and weighted event prevalence. It is not a benchmark or a model forecast.
89
+
90
+ ## Multi-entity panels (v0.2.0)
91
+
92
+ ```python
93
+ from onsetkit import label_panel_onsets, panel_forward_split
94
+
95
+ # Arrays of equal length in any input row order; time can be numeric or np.datetime64.
96
+ r = label_panel_onsets(active, entities, time, horizon=5)
97
+ train, test = panel_forward_split(r.label_end, time, test_start=350,
98
+ test_stop=500, train_cutoff=340)
99
+ ```
100
+
101
+ Labels are computed separately in each entity's timestamp order and returned in the original row order. Duplicate timestamps within one entity are rejected; simultaneous timestamps across entities are allowed. The horizon counts observations within an entity, not elapsed time. `label_end` contains original row indices, so use `panel_forward_split`, not the single-series row-index splitter, for panel labels. The panel splitter applies one global time cutoff across all entities. It does not check external feature or regime-label availability, and assumes label-end indices come from the corresponding panel labels. Explicitly sort selected rows by time if the downstream model requires it.
102
+
103
+ ## Design-based variance
104
+
105
+ ```python
106
+ sample = stratified_sample(strata, budget=100, allocation="equal", minimum=2)
107
+ mean = sample.estimate_mean(values[sample.indices])
108
+ variance = sample.estimate_variance(values[sample.indices])
109
+ ```
110
+
111
+ For fixed finite-population attributes under independent stratified simple random sampling without replacement, the estimator is sum((N_h/N)^2 * (1 - n_h/N_h) * s_h^2/n_h). Census strata contribute zero. Noncensus strata with fewer than two sampled rows raise an error. This estimates the design variance of the population mean, not uncertainty from fitting a forecasting model, future market uncertainty or time-series process variance. The sample allocation must be fixed independently of the sampling draw.
112
+
113
+ ## Event-level evaluation
114
+
115
+ ```python
116
+ from onsetkit import event_metrics
117
+ m = event_metrics(active, alarms, horizon=5, evaluation_mask=held_out_mask)
118
+ print(m.event_recall, m.alarm_precision, m.mean_first_warning_lead)
119
+ ```
120
+
121
+ This single-sequence API scores binary alarms on eligible inactive rows with complete horizons, optionally restricted to a boolean evaluation mask. Each positive alarm is attributed to the next onset, not to every onset within the horizon. An event is evaluable only if at least one scored row could predict it as the next onset. Repeated alarms count once toward event recall and separately toward alarm precision. False alarm rate is false alarms divided by eligible negative rows. Mean first-warning lead is computed over detected events in observation rows. Undefined rates are NaN. Use a mask restricted to labels that resolve within the held-out block; for panels call separately on time-sorted entity sequences. These are operational metrics, not pointwise classifier metrics or a statistical significance test.
122
+
123
+ Run `python examples/panel_demo.py` for a shuffled multi-asset synthetic example, weighted sampling and random-alarm baseline.
124
+
125
+ ## Current limits
126
+
127
+ - Panel timestamps are used for ordering and splitting, but horizons count observations rather than elapsed time.
128
+ - Regime/event detection and forecasting models are supplied externally.
129
+ - No uncertainty intervals, streaming execution or probability calibration yet; event scoring is per sequence.
130
+ - No real-market or industrial performance benchmarks yet.
131
+ - NumPy arrays are mutable even inside frozen result dataclasses; treat them as read-only.
132
+
133
+ ## Roadmap
134
+
135
+ Explicit information availability timestamps, elapsed-time horizons, aggregate panel event metrics, calibration utilities, uncertainty intervals, and reproducible real-world financial and industrial benchmarks.
136
+
137
+ ## Contributing
138
+
139
+ Bug reports, reproducible examples and regression tests are welcome. MIT licence; review copyright attribution and research provenance before publication.
@@ -0,0 +1,19 @@
1
+ CHANGELOG.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ RELEASING.md
6
+ pyproject.toml
7
+ examples/panel_demo.py
8
+ examples/regime_demo.py
9
+ src/onsetkit/__init__.py
10
+ src/onsetkit/core.py
11
+ src/onsetkit/metrics.py
12
+ src/onsetkit/panel.py
13
+ src/onsetkit.egg-info/PKG-INFO
14
+ src/onsetkit.egg-info/SOURCES.txt
15
+ src/onsetkit.egg-info/dependency_links.txt
16
+ src/onsetkit.egg-info/requires.txt
17
+ src/onsetkit.egg-info/top_level.txt
18
+ tests/test_core.py
19
+ tests/test_panel_metrics.py
@@ -0,0 +1,6 @@
1
+ numpy>=1.24
2
+
3
+ [dev]
4
+ pytest>=7
5
+ build
6
+ twine
@@ -0,0 +1 @@
1
+ onsetkit
@@ -0,0 +1,94 @@
1
+ import itertools
2
+ import numpy as np
3
+ import pytest
4
+ from onsetkit import label_onsets, optimal_allocation, stratified_sample, purged_forward_split
5
+
6
+
7
+ def test_onsets():
8
+ r = label_onsets([0,0,1,1,0,0,1,0,0], 2)
9
+ np.testing.assert_array_equal(r.labels, [1,1,-1,-1,1,1,-1,-1,-1])
10
+ np.testing.assert_array_equal(np.flatnonzero(r.onset), [2,6])
11
+ np.testing.assert_array_equal(r.label_end, [2,3,-1,-1,6,7,-1,-1,-1])
12
+
13
+
14
+ def test_future_not_current():
15
+ r = label_onsets([1,1,0,0,0,1,0], 1)
16
+ np.testing.assert_array_equal(r.labels, [-1,-1,0,0,1,-1,-1])
17
+ assert not r.onset[0]
18
+
19
+ @pytest.mark.parametrize('a,h', [([],1),([0,2],1),([0,np.nan],1),([0,1],0),([0,1],1.5),([[0,1]],1)])
20
+ def test_bad_labels(a,h):
21
+ with pytest.raises(ValueError): label_onsets(a,h)
22
+
23
+
24
+ def test_long_horizon():
25
+ assert not label_onsets([0,1], 10).eligible.any()
26
+
27
+
28
+ def test_random_labels_match_naive():
29
+ rng=np.random.default_rng(42)
30
+ for _ in range(100):
31
+ a=rng.integers(0,2,30); h=int(rng.integers(1,35))
32
+ y=label_onsets(a,h).labels
33
+ expected=[-1 if a[t] or t+h>=len(a) else int(any(a[j] and not a[j-1] for j in range(t+1,t+h+1))) for t in range(len(a))]
34
+ np.testing.assert_array_equal(y,expected)
35
+
36
+
37
+ def test_allocation_exact_exhaustive():
38
+ rng=np.random.default_rng(10)
39
+ for _ in range(100):
40
+ N=rng.integers(1,7,3); S=rng.integers(0,5,3); k=int(rng.integers(3,N.sum()+1))
41
+ n=optimal_allocation(N,S,k)
42
+ obj=lambda x: np.sum((N*S)**2/np.asarray(x))
43
+ best=min(obj(x) for x in itertools.product(*(range(1,int(z)+1) for z in N)) if sum(x)==k)
44
+ assert obj(n)==pytest.approx(best)
45
+ assert n.sum()==k
46
+
47
+
48
+ def test_allocation_minimum_and_caps():
49
+ np.testing.assert_array_equal(optimal_allocation([1,4,9],[1,3,0],7,minimum=2),[1,4,2])
50
+
51
+ @pytest.mark.parametrize('N,S,k', [([1,2],[1,1],1),([1,2],[1,1],4),([0,2],[1,1],2),([1.2,2],[1,1],2),([1,2],[1,-1],2),([1,2],[1],2),([1,2],[1,np.inf],2)])
52
+ def test_bad_allocation(N,S,k):
53
+ with pytest.raises(ValueError): optimal_allocation(N,S,k)
54
+
55
+
56
+ def test_sample_weights():
57
+ s=np.repeat([0,1],[90,10]); r=stratified_sample(s,20,allocation='equal',seed=42)
58
+ np.testing.assert_array_equal(r.allocation,[10,10])
59
+ assert len(np.unique(r.indices))==20
60
+ assert np.all(np.diff(r.indices)>0)
61
+ assert r.weights.sum()==pytest.approx(100)
62
+ assert r.estimate_mean(s[r.indices])==pytest.approx(.1)
63
+ np.testing.assert_array_equal(r.indices,stratified_sample(s,20,allocation='equal',seed=42).indices)
64
+
65
+
66
+ def test_neyman():
67
+ r=stratified_sample(np.repeat(['a','b'],[20,20]),10,allocation='neyman',scales=[1,3])
68
+ np.testing.assert_array_equal(r.allocation,[3,7])
69
+
70
+
71
+ def test_census():
72
+ r=stratified_sample([0,1,1],3)
73
+ np.testing.assert_array_equal(r.indices,[0,1,2]); np.testing.assert_array_equal(r.weights,[1,1,1])
74
+
75
+ @pytest.mark.parametrize('kwargs',[{'allocation':'bad'}, {'allocation':'neyman'}, {'scales':[1,2]}, {'seed':-1}])
76
+ def test_bad_sample(kwargs):
77
+ with pytest.raises(ValueError): stratified_sample([0,0,1,1],2,**kwargs)
78
+
79
+
80
+ def test_purge():
81
+ r=label_onsets(np.zeros(20),3)
82
+ train,test=purged_forward_split(r.label_end,10,20,gap=2)
83
+ np.testing.assert_array_equal(train,np.arange(5)); np.testing.assert_array_equal(test,np.arange(10,17))
84
+ assert max(r.label_end[train])<8
85
+
86
+
87
+ def test_excluded_rows():
88
+ r=label_onsets([0,0,1,0,0,0,0,1,0,0,0,0],1)
89
+ train,test=purged_forward_split(r.label_end,6,12)
90
+ assert 2 not in train and 7 not in test and 5 not in train
91
+
92
+ @pytest.mark.parametrize('end,start,stop,gap',[([0,1,2],0,3,0),([0,1,2],2,4,0),([0,1,2],1,3,1),([0,0,2],1,3,0),([0,1,9],1,3,0),([-1,-1,2],1,3,0)])
93
+ def test_bad_split(end,start,stop,gap):
94
+ with pytest.raises(ValueError): purged_forward_split(end,start,stop,gap=gap)
@@ -0,0 +1,95 @@
1
+ import itertools
2
+ import numpy as np
3
+ import pytest
4
+ from onsetkit import (label_panel_onsets, panel_forward_split, label_onsets,
5
+ event_metrics, stratified_sample)
6
+
7
+
8
+ def test_panel_shuffled():
9
+ a = np.array([0,0,1,0,0,0,0,1,1,0,0,0])
10
+ e = np.repeat(['A','B'], 6)
11
+ t = np.tile(np.arange(6), 2)
12
+ perm = np.random.default_rng(3).permutation(len(a))
13
+ r = label_panel_onsets(a[perm], e[perm], t[perm], 2)
14
+ for entity in ['A','B']:
15
+ idx = np.flatnonzero(e[perm] == entity)
16
+ idx = idx[np.argsort(t[perm][idx])]
17
+ expected = label_onsets(a[perm][idx], 2)
18
+ np.testing.assert_array_equal(r.labels[idx], expected.labels)
19
+ np.testing.assert_array_equal(r.onset[idx], expected.onset)
20
+ np.testing.assert_array_equal(r.label_end[idx[expected.eligible]], idx[expected.label_end[expected.eligible]])
21
+
22
+
23
+ def test_panel_global_split():
24
+ t = np.tile(np.arange(10), 2)
25
+ r = label_panel_onsets(np.zeros(20), np.repeat(['A','B'],10), t, 2)
26
+ train, test = panel_forward_split(r.label_end, t, 5, 10, train_cutoff=4)
27
+ assert set(t[train]) == {0,1}
28
+ assert set(t[test]) == {5,6,7}
29
+ assert np.all(t[r.label_end[train]] < 4)
30
+
31
+
32
+ def test_datetime():
33
+ t = np.datetime64('2020-01-01') + np.arange(10)
34
+ r = label_panel_onsets(np.zeros(10), ['a']*10, t, 1)
35
+ train,test = panel_forward_split(r.label_end,t,t[5],t[-1]+np.timedelta64(1,'D'))
36
+ assert list(train)==[0,1,2,3]
37
+ assert list(test)==[5,6,7,8]
38
+
39
+
40
+ @pytest.mark.parametrize('entities,time', [(['a','a'],[0,0]), (['a'],[0,1]), (['a','b'],[0,np.nan])])
41
+ def test_invalid_panel(entities,time):
42
+ with pytest.raises(ValueError): label_panel_onsets([0,1],entities,time,1)
43
+
44
+
45
+ def test_no_cross_entity():
46
+ r = label_panel_onsets([0,0,1,1], ['a','a','b','b'], [0,1,0,1],1)
47
+ assert list(r.labels)==[0,-1,-1,-1]
48
+ assert not r.onset.any()
49
+
50
+
51
+ def test_event_metrics():
52
+ a = [0,0,0,1,0,0,0,1,0,0,0]
53
+ alarms = [1,1,1,0,1,0,0,0,0,0,0]
54
+ m = event_metrics(a,alarms,2)
55
+ assert (m.eligible_events,m.detected_events,m.alarms,m.true_alarms,m.false_alarms)==(2,1,4,2,2)
56
+ assert m.event_recall == .5 and m.alarm_precision == .5
57
+ assert m.mean_first_warning_lead == 2
58
+ assert m.false_alarm_rate == 2/3
59
+
60
+
61
+ def test_event_mask():
62
+ m = event_metrics([0,0,1,0,0],[0,1,0,0,0],1,evaluation_mask=[False,True,False,False,False])
63
+ assert m.event_recall == 1 and m.alarm_precision == 1
64
+ assert np.isnan(m.false_alarm_rate)
65
+
66
+
67
+ def test_empty_events():
68
+ m = event_metrics([0,0,0],[0,0,0],1)
69
+ assert m.eligible_events == 0 and np.isnan(m.event_recall) and np.isnan(m.alarm_precision)
70
+
71
+
72
+ def test_next_event_attribution():
73
+ m = event_metrics([0,1,0,1,0,0,0],[1,0,0,0,0,0,0],3)
74
+ assert m.eligible_events == 2 and m.detected_events == 1
75
+
76
+
77
+ def test_variance_census():
78
+ s = stratified_sample([0,1],2)
79
+ assert s.estimate_variance([1,100]) == 0
80
+
81
+
82
+ def test_variance_singleton():
83
+ s = stratified_sample([0,0,1,1],2)
84
+ with pytest.raises(ValueError): s.estimate_variance([1,2])
85
+
86
+
87
+ def test_variance_exhaustive():
88
+ # Enumerate all possible two-of-four samples; expectation of estimated
89
+ # variance equals actual design variance of the HT mean.
90
+ from dataclasses import replace
91
+ v=np.array([1.,2.,4.,8.]); s=stratified_sample([0]*4,2)
92
+ estimates=[]; means=[]
93
+ for pair in itertools.combinations(range(4),2):
94
+ x=replace(s,indices=np.array(pair)); estimates.append(x.estimate_variance(v[list(pair)])); means.append(x.estimate_mean(v[list(pair)]))
95
+ assert np.mean(estimates)==pytest.approx(np.var(means))