uracle-oracle 0.1.2__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.
- uracle_oracle-0.1.2/FEATURES_v0.1.2.md +146 -0
- uracle_oracle-0.1.2/FEATURE_CONTRACTS.md +271 -0
- uracle_oracle-0.1.2/FEATURE_IMPLEMENTATION.md +142 -0
- uracle_oracle-0.1.2/MANIFEST.in +8 -0
- uracle_oracle-0.1.2/MODULE_CONTRACTS.md +51 -0
- uracle_oracle-0.1.2/PKG-INFO +194 -0
- uracle_oracle-0.1.2/README.md +186 -0
- uracle_oracle-0.1.2/RESEARCH_PIPELINE.md +76 -0
- uracle_oracle-0.1.2/TODO.md +55 -0
- uracle_oracle-0.1.2/VALIDATION_v0.1.2.md +33 -0
- uracle_oracle-0.1.2/examples/feature_demo.json +25 -0
- uracle_oracle-0.1.2/feature_notes/arbitrage.md +100 -0
- uracle_oracle-0.1.2/feature_notes/copy_trading.md +131 -0
- uracle_oracle-0.1.2/feature_notes/hedging.md +118 -0
- uracle_oracle-0.1.2/feature_notes/line_movement.md +146 -0
- uracle_oracle-0.1.2/feature_notes/portfolio.md +114 -0
- uracle_oracle-0.1.2/feature_notes/props.md +93 -0
- uracle_oracle-0.1.2/feature_notes/sentiment.md +137 -0
- uracle_oracle-0.1.2/feature_notes/settlement.md +131 -0
- uracle_oracle-0.1.2/feature_notes/triggers.md +124 -0
- uracle_oracle-0.1.2/feature_notes/whale.md +138 -0
- uracle_oracle-0.1.2/historical_backtest.py +392 -0
- uracle_oracle-0.1.2/module_notes/bootstrap.md +50 -0
- uracle_oracle-0.1.2/module_notes/conformal.md +57 -0
- uracle_oracle-0.1.2/module_notes/drawdown.md +51 -0
- uracle_oracle-0.1.2/module_notes/drift.md +60 -0
- uracle_oracle-0.1.2/module_notes/ensemble.md +46 -0
- uracle_oracle-0.1.2/module_notes/liquidity.md +71 -0
- uracle_oracle-0.1.2/module_notes/regime.md +65 -0
- uracle_oracle-0.1.2/module_notes/replay.md +64 -0
- uracle_oracle-0.1.2/module_notes/shadow.md +81 -0
- uracle_oracle-0.1.2/module_notes/tail_risk.md +67 -0
- uracle_oracle-0.1.2/plan.md +59 -0
- uracle_oracle-0.1.2/pyproject.toml +19 -0
- uracle_oracle-0.1.2/research_config.example.json +10 -0
- uracle_oracle-0.1.2/scripts/validate_research_pipeline.py +88 -0
- uracle_oracle-0.1.2/scripts/verify_installed_pipeline.py +55 -0
- uracle_oracle-0.1.2/self_evolving_oracle.py +646 -0
- uracle_oracle-0.1.2/setup.cfg +4 -0
- uracle_oracle-0.1.2/test_feature_arbitrage.py +472 -0
- uracle_oracle-0.1.2/test_feature_cli.py +374 -0
- uracle_oracle-0.1.2/test_feature_copy_trading.py +471 -0
- uracle_oracle-0.1.2/test_feature_hedging.py +643 -0
- uracle_oracle-0.1.2/test_feature_integration.py +440 -0
- uracle_oracle-0.1.2/test_feature_line_movement.py +466 -0
- uracle_oracle-0.1.2/test_feature_portfolio.py +548 -0
- uracle_oracle-0.1.2/test_feature_props.py +497 -0
- uracle_oracle-0.1.2/test_feature_sentiment.py +521 -0
- uracle_oracle-0.1.2/test_feature_settlement.py +478 -0
- uracle_oracle-0.1.2/test_feature_triggers.py +530 -0
- uracle_oracle-0.1.2/test_feature_whale.py +641 -0
- uracle_oracle-0.1.2/tests/test_expected_project.py +65 -0
- uracle_oracle-0.1.2/tests/test_local_integration.py +172 -0
- uracle_oracle-0.1.2/tests/test_pypi_workflow.py +211 -0
- uracle_oracle-0.1.2/tests/test_release_publisher.py +560 -0
- uracle_oracle-0.1.2/tests/test_semver_validation.py +150 -0
- uracle_oracle-0.1.2/tests/test_semver_workflow.py +75 -0
- uracle_oracle-0.1.2/tests/test_tag_guard.py +78 -0
- uracle_oracle-0.1.2/uracle_features/__init__.py +21 -0
- uracle_oracle-0.1.2/uracle_features/arbitrage.py +319 -0
- uracle_oracle-0.1.2/uracle_features/cli.py +155 -0
- uracle_oracle-0.1.2/uracle_features/common.py +704 -0
- uracle_oracle-0.1.2/uracle_features/copy_trading.py +241 -0
- uracle_oracle-0.1.2/uracle_features/hedging.py +326 -0
- uracle_oracle-0.1.2/uracle_features/line_movement.py +265 -0
- uracle_oracle-0.1.2/uracle_features/portfolio.py +395 -0
- uracle_oracle-0.1.2/uracle_features/props.py +360 -0
- uracle_oracle-0.1.2/uracle_features/sentiment.py +367 -0
- uracle_oracle-0.1.2/uracle_features/settlement.py +315 -0
- uracle_oracle-0.1.2/uracle_features/triggers.py +245 -0
- uracle_oracle-0.1.2/uracle_features/whale.py +479 -0
- uracle_oracle-0.1.2/uracle_features/workflow.py +427 -0
- uracle_oracle-0.1.2/uracle_modules/__init__.py +20 -0
- uracle_oracle-0.1.2/uracle_modules/bootstrap.py +99 -0
- uracle_oracle-0.1.2/uracle_modules/conformal.py +123 -0
- uracle_oracle-0.1.2/uracle_modules/drawdown.py +143 -0
- uracle_oracle-0.1.2/uracle_modules/drift.py +141 -0
- uracle_oracle-0.1.2/uracle_modules/ensemble.py +148 -0
- uracle_oracle-0.1.2/uracle_modules/liquidity.py +99 -0
- uracle_oracle-0.1.2/uracle_modules/pipeline.py +258 -0
- uracle_oracle-0.1.2/uracle_modules/regime.py +107 -0
- uracle_oracle-0.1.2/uracle_modules/replay.py +167 -0
- uracle_oracle-0.1.2/uracle_modules/shadow.py +126 -0
- uracle_oracle-0.1.2/uracle_modules/tail_risk.py +115 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/PKG-INFO +194 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/SOURCES.txt +88 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/dependency_links.txt +1 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/entry_points.txt +3 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/requires.txt +1 -0
- uracle_oracle-0.1.2/uracle_oracle.egg-info/top_level.txt +4 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Ten integrated modules for Uracle 0.1.2
|
|
2
|
+
|
|
3
|
+
Uracle 0.1.2 now connects ten complementary modules to the oracle, historical backtester, installed CLI, diagnostics and checkpoint lifecycle. They were selected for distinct roles: improve scenario diversity, expose uncertainty and model changes, constrain exposure, make costs explicit, compare alternatives without hindsight selection, and reproduce state. They combine established methods; neither global uniqueness nor profitable forecasts has been established.
|
|
4
|
+
|
|
5
|
+
## 1. RegimeDetector — distinguish trend from volatility expansion
|
|
6
|
+
|
|
7
|
+
A past-only, two-window diagnostic classifies the current history as `unknown`, `calm`, `trending` or `stressed`. It compares standardized means and the ratio of recent to reference volatility. In the integrated pipeline, a volatility multiplier above one reduces the allocation ceiling; it does not silently change baseline calibration or treat a negative trend as bullish.
|
|
8
|
+
|
|
9
|
+
The confidence output is an uncalibrated heuristic, not a posterior regime probability. NIST supports the standardization mechanism, Cont documents heavy tails and temporal dependence, and time-series momentum research supports past-return/volatility-based diagnostics without validating this module's thresholds. [1] [2] [3]
|
|
10
|
+
|
|
11
|
+
**API:** `RegimeDetector.analyze(history)`. The standalone module passes 30 tests, including formula checks, prefix causality and finite diagnostics.
|
|
12
|
+
|
|
13
|
+
## 2. BlockBootstrap — add empirical historical scenarios
|
|
14
|
+
|
|
15
|
+
The module samples contiguous, non-wrapping historical blocks with replacement. Its multi-step path API preserves adjacency within blocks, allowing historical clustering to survive within sampled paths. The oracle's current one-horizon decision uses the one-step marginal alongside GBM scenarios once `len(history) >= max(block_size, min_history)`.
|
|
16
|
+
|
|
17
|
+
During warm-up, the pipeline duplicates GBM into the unavailable bootstrap slot, explicitly records that fallback, and continues expert scoring against the identical fallback forecast. For one-step paths, fixed full-block starts exclude the last `block_size-1` observations from sampling support. This boundary bias is explicit; historical resampling cannot produce unseen crashes or guarantee future realism. The implementation follows moving-block research and documented R/Arch conventions. [4] [5] [6]
|
|
18
|
+
|
|
19
|
+
**API:** `BlockBootstrap.sample_paths(...)` and `.sample(...)`. The standalone module passes 26 tests, including adjacency, boundary behavior and RNG continuation.
|
|
20
|
+
|
|
21
|
+
## 3. OnlineConformal — expose forecast uncertainty before outcomes
|
|
22
|
+
|
|
23
|
+
The module stores only errors from previously frozen forecasts. With `n` residuals and target coverage `c`, the radius is the `ceil((n+1)*c)`-th absolute residual, producing `center ± radius`. Warm-up and ranks beyond the available sample count are marked `ready=False`, not represented as valid zero-width intervals.
|
|
24
|
+
|
|
25
|
+
The pipeline freezes its sampled-mixture mean before the outcome and updates the residual history afterward. When ready, interval width reduces the position ceiling using the explicit heuristic `min(1, 0.02/width)`. The fixed 0.02 budget is a one-horizon return fraction. Conformal theory motivates corrected ranks, but dependent/drifting markets and adaptive predictors prevent an unconditional coverage claim here. [7] [8] [9]
|
|
26
|
+
|
|
27
|
+
**API:** `OnlineConformal.interval(center)` and `.update(predicted, realized)`. The standalone module passes 23 tests, including rank enumeration and idealized independent-score checks.
|
|
28
|
+
|
|
29
|
+
## 4. AdaptiveEnsemble — let expert weights respond to observed errors
|
|
30
|
+
|
|
31
|
+
Three experts generate scenarios: GBM, historical bootstrap and conservative half-GBM. The module samples one expert at each corresponding scenario index using pre-outcome weights. After observation, scale-normalized squared errors update weights exponentially, followed by uniform sharing that keeps each weight positive.
|
|
32
|
+
|
|
33
|
+
The updated weights affect the next decision, never the past one. Mean-error weighting ignores tails and costs, and the conservative expert is a stress proxy rather than a validated safe distribution. This combines expert-advice and weight-sharing mechanisms with categorical sampling; the original papers' regret guarantees are not asserted for this modified financial application. [10] [11] [12]
|
|
34
|
+
|
|
35
|
+
**API:** `AdaptiveEnsemble.weights()`, `.sample(...)` and `.update(...)`. The standalone module passes 22 tests, including mixture frequencies and state continuation.
|
|
36
|
+
|
|
37
|
+
## 5. CVaRGovernor — cap allocation using scenario tail loss
|
|
38
|
+
|
|
39
|
+
The governor selects the worst `ceil(n*p)` net-return scenarios. Unit expected shortfall is the nonnegative mean loss of that selected tail. Allocation cannot exceed `max_expected_shortfall / unit_expected_shortfall`, when unit tail loss is positive; the existing position ceiling remains in force.
|
|
40
|
+
|
|
41
|
+
The pipeline applies this cap to scenarios incorporating the decision's frozen entry/exit fees and reports VaR/expected shortfall at the final allocation. These are empirical scenario risks, not maximum-loss bounds; unseen crashes or wrong scenario/cost assumptions can defeat the budget. Scenario CVaR research, discrete expected-shortfall analysis and the Basel overview support the mechanism, not a regulatory or capital-preservation claim. [13] [14] [15]
|
|
42
|
+
|
|
43
|
+
**API:** `CVaRGovernor.limit(...)` and `.assess(...)`. The standalone module passes 22 tests, including analytical tail comparisons and allocation feasibility.
|
|
44
|
+
|
|
45
|
+
## 6. DrawdownGuard — pause and resume without permanent cash lock
|
|
46
|
+
|
|
47
|
+
A peak-equity drawdown breach starts a bounded cooldown measured in observed opportunities. During the pause, allowed allocation is zero. Afterward, reduced-risk trading is permitted even without immediate equity recovery; the same unchanged breach cannot retrigger indefinitely. A new peak or recovery below half the threshold rearms the guard.
|
|
48
|
+
|
|
49
|
+
Every observation, including a no-trade opportunity, advances the cooldown. The trade that caused the breach is not retroactively removed. Drawdown-overlay research motivates the mechanism, but the cooldown, threshold and recovery fraction are configurable heuristics rather than literature-calibrated constants or loss guarantees. [16] [17] [18]
|
|
50
|
+
|
|
51
|
+
**API:** `DrawdownGuard.limit(...)`, `.update(equity)` and `.status()`. The standalone module passes 26 tests, including flat-path resumption and recovery/rebreach cases.
|
|
52
|
+
|
|
53
|
+
## 7. DriftSentinel — detect sequential mean-shift evidence
|
|
54
|
+
|
|
55
|
+
The sentinel monitors observed log returns with two reflected cumulative mean-deviation scores. It reports an alarm after enough observations and a strict threshold crossing, then resets active detector statistics while retaining the latest alarm diagnostic.
|
|
56
|
+
|
|
57
|
+
The pipeline updates it only after the matching outcome. A previous alarm halves the next decision's risk ceiling; it does not revise past forecasts or automatically reset the other estimators. A total-loss simple return is explicitly floored at `1e-12` only for logarithmic diagnostics/calibration. CUSUM/Page-Hinkley references support sequential monitoring; alarms remain heuristic, sensitive to noise, dependence and parameter choices. [19] [20] [21]
|
|
58
|
+
|
|
59
|
+
**API:** `DriftSentinel.update(log_return)` and `.status()`. The standalone module passes 23 tests, including both shift directions and reset timing.
|
|
60
|
+
|
|
61
|
+
## 8. LiquidityCostModel — make participation stress explicit
|
|
62
|
+
|
|
63
|
+
Additional per-side cost is capped half-spread plus square-root participation impact:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
min(max_extra_rate, spread_bps/20000 + impact_bps/10000 * sqrt(allocation*capital/liquidity_notional))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The pipeline evaluates the proxy at the maximum pre-constraint allocation, adds base fees, caps the total per-side rate at one, then freezes it. The same rate is used for scenario sizing, modeled realized P&L and shadow accounting. This is conservative only relative to the configured proxy and accounting convention, not actual market execution. Daily input has no measured volume, quotes or order-book depth. Spread definitions and impact/cost studies motivate the model without calibrating these defaults or establishing universal square-root behavior. [22] [23] [24]
|
|
70
|
+
|
|
71
|
+
**API:** `LiquidityCostModel.extra_rate(allocation, capital)`. The standalone module passes 25 tests, including monotonicity, extreme values and Decimal formula references.
|
|
72
|
+
|
|
73
|
+
## 9. ShadowLedger — compare alternatives without choosing hindsight winners
|
|
74
|
+
|
|
75
|
+
Before the outcome, the pipeline computes allocations for all five existing oracle actions under common GBM normal shocks, the same frozen fees and the same risk ceiling. After the actual return arrives, the ledger independently compounds each alternative's hypothetical wealth using `f*((1-c)*r-2*c)`.
|
|
76
|
+
|
|
77
|
+
Shadow results never change actual capital, train the policy on hindsight winners, or claim identified causal effects. Alternative sizing uses common-shock GBM, not a separate re-optimized ensemble per action. All alternatives share the observed path and simplify fills/market impact. Pathwise portfolio accounting, common-random-input comparisons and causal-inference references establish these distinctions. [25] [26] [27]
|
|
78
|
+
|
|
79
|
+
**API:** `ShadowLedger.record(...)` and `.summary()`. The standalone module passes 22 tests, including independent compounding and insolvency rejection.
|
|
80
|
+
|
|
81
|
+
## 10. ReplayCapsule — reproduce complete state and detect content changes
|
|
82
|
+
|
|
83
|
+
Full oracle checkpoints capture configuration, capital, Q values, the next decision ID, unresolved trade, frozen costs/forecasts, every module state and both current RNG states. A restored pending decision is resolved without resampling. Completed observations append a chained event containing the previously frozen decision, realized outcome and diagnostics only after the transaction succeeds.
|
|
84
|
+
|
|
85
|
+
Canonical finite JSON and SHA-256 verify content and chain structure. They are not authenticated signatures: a fully rehashed replacement history can be internally valid. The format is sorted-key Python JSON, not RFC 8785/JCS. Exact replay requires compatible code, generator calls and runtime; seeds alone are insufficient. Full-history verification and snapshots also have quadratic cumulative cost over long runs, so this implementation is a correctness-oriented research path, not a high-throughput event service. [28] [29] [30] [31]
|
|
86
|
+
|
|
87
|
+
**API:** `ReplayCapsule.seal/open`, `.append(...)` and `.verify()`; full oracle methods `save_checkpoint` and `load_checkpoint`. The standalone module passes 25 tests; end-to-end tests additionally verify pending-decision replay, core/Q continuation, both RNG streams and rollback.
|
|
88
|
+
|
|
89
|
+
## Use the complete integration
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from self_evolving_oracle import SelfEvolvingOracle
|
|
93
|
+
from uracle_modules import ResearchPipeline
|
|
94
|
+
|
|
95
|
+
pipeline = ResearchPipeline.for_capital(100_000, seed=43)
|
|
96
|
+
oracle = SelfEvolvingOracle(100_000, seed=42, research_pipeline=pipeline)
|
|
97
|
+
decision = oracle.decide([0.002, -0.003, 0.004, -0.001] * 10)
|
|
98
|
+
oracle.save_checkpoint("pending.json")
|
|
99
|
+
restored = SelfEvolvingOracle.load_checkpoint("pending.json")
|
|
100
|
+
outcome = restored.observe(decision.decision_id, asset_return=0.005)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python -m pip install .
|
|
105
|
+
uracle-backtest data/spy_daily_2022_2025.csv --enhanced \
|
|
106
|
+
--module-config research_config.example.json \
|
|
107
|
+
--output-dir results_enhanced --checkpoint-out results_enhanced/model.json
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Default operation remains the legacy oracle. Enhanced failures restore the core and all pipeline state together. The CLI's checkpoint input initializes a new backtest; it is **not** a saved dataset-cursor resume. Model configuration overrides cannot be combined with checkpoint input. The sample CSV and configuration are source-repository files rather than wheel-embedded data.
|
|
111
|
+
|
|
112
|
+
[RESEARCH_PIPELINE.md](RESEARCH_PIPELINE.md) contains the full timing, configuration, diagnostics and checkpoint contract. [VALIDATION_v0.1.2.md](VALIDATION_v0.1.2.md) records final engineering checks and the historical sample result. The historical sample is single-source data and does not establish profitability or comparative superiority. No main-branch merge, package publication or live trading is performed.
|
|
113
|
+
|
|
114
|
+
## References
|
|
115
|
+
|
|
116
|
+
[1]: https://www.itl.nist.gov/div898/handbook/prc/section2/prc.htm "NIST standardized sample mean guidance"
|
|
117
|
+
[2]: http://rama.cont.perso.math.cnrs.fr/pdf/empirical.pdf "Cont empirical properties of asset returns"
|
|
118
|
+
[3]: https://www.sciencedirect.com/science/article/pii/S0304405X11002613 "Moskowitz Ooi and Pedersen time series momentum"
|
|
119
|
+
[4]: https://arxiv.org/html/1711.01070v3 "Moving block bootstrap for functional time series"
|
|
120
|
+
[5]: https://search.r-project.org/CRAN/refmans/boot/html/tsboot.html "R boot time series bootstrap documentation"
|
|
121
|
+
[6]: https://arch.readthedocs.io/en/stable/bootstrap/timeseries-bootstraps.html "Arch time series bootstrap boundary behavior"
|
|
122
|
+
[7]: https://arxiv.org/html/2107.07511v6 "Angelopoulos and Bates conformal prediction introduction"
|
|
123
|
+
[8]: https://arxiv.org/html/2106.00170v3 "Gibbs and Candes adaptive conformal inference under shift"
|
|
124
|
+
[9]: https://arxiv.org/html/2202.07282v1 "Zaffran and colleagues conformal prediction for time series"
|
|
125
|
+
[10]: https://www.schapire.net/papers/CesabianchiFrHeHaSc92.pdf "Cesa Bianchi and colleagues how to use expert advice"
|
|
126
|
+
[11]: https://link.springer.com/content/pdf/10.1023/A:1007424614876.pdf "Herbster and Warmuth tracking the best expert"
|
|
127
|
+
[12]: https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html "NumPy categorical sampling documentation"
|
|
128
|
+
[13]: https://sites.math.washington.edu/~rtr/papers/rtr179-CVaR1.pdf "Rockafellar and Uryasev conditional value at risk optimization"
|
|
129
|
+
[14]: https://faculty.washington.edu/ezivot/econ589/acertasc.pdf "Acerbi and Tasche expected shortfall and discrete tails"
|
|
130
|
+
[15]: https://www.bis.org/pages/basel-iii-international-regulatory-framework-banks/d457-inbrief.pdf "Basel market risk framework overview"
|
|
131
|
+
[16]: https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/risk-management/supported-models "QuantConnect drawdown overlay documentation"
|
|
132
|
+
[17]: https://www.sciencedirect.com/science/article/abs/pii/S138641811300030X "Kaminski and Lo stop loss rule analysis"
|
|
133
|
+
[18]: https://web.stanford.edu/~boyd/papers/multiperiod_portfolio_drawdown.html "Nystrup and colleagues portfolio drawdown control"
|
|
134
|
+
[19]: https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc313.htm "NIST cumulative sum monitoring guidance"
|
|
135
|
+
[20]: https://riverml.xyz/dev/api/drift/PageHinkley/ "River Page Hinkley documentation"
|
|
136
|
+
[21]: https://metricgate.com/docs/page-hinkley-change-detector/ "MetricGate two sided Page Hinkley mechanism"
|
|
137
|
+
[22]: https://www.sec.gov/answers/spread.htm "SEC spread definition"
|
|
138
|
+
[23]: https://arxiv.org/abs/1811.05230 "Crossover from linear to square root market impact"
|
|
139
|
+
[24]: https://www.aqr.com/Insights/Research/Working-Paper/Trading-Costs "AQR institutional trading cost study"
|
|
140
|
+
[25]: https://www.cs.cmu.edu/~avrim/Papers/portfolio.pdf "Blum and Kalai pathwise portfolio wealth and costs"
|
|
141
|
+
[26]: https://blog.simul8.com/fridays-tip-random-numbers/ "SIMUL8 holding random inputs fixed in comparisons"
|
|
142
|
+
[27]: https://static1.squarespace.com/static/675db8b0dd37046447128f5f/t/677676888e31cc50c2c33877/1735816881944/hernanrobins_WhatIf_2jan25.pdf "Hernan and Robins causal inference assumptions"
|
|
143
|
+
[28]: https://www.nist.gov/publications/secure-hash-standard "NIST secure hash standard"
|
|
144
|
+
[29]: https://www.rfc-editor.org/info/rfc8785/ "RFC 8785 invariant JSON representation"
|
|
145
|
+
[30]: https://numpy.org/devdocs/reference/random/bit_generators/generated/numpy.random.BitGenerator.state.html "NumPy current bit generator state"
|
|
146
|
+
[31]: https://numpy.org/doc/stable/reference/random/compatibility.html "NumPy random stream compatibility policy"
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
# Urakle shared feature contracts — schema 1
|
|
2
|
+
|
|
3
|
+
This is the implementation handshake for the ten **new** features, separate from the ten legacy `uracle_modules` research modules. Python >=3.10, standard library + NumPy only. No changes to the legacy oracle, research pipeline, dataset, version 0.1.2, existing CLI defaults, workflows, Git state, remotes, or credentials are authorized to feature agents. These are research diagnostics and **paper** lifecycles, not production trading or verified investment advice.
|
|
4
|
+
|
|
5
|
+
## 1. Ownership and dependency direction
|
|
6
|
+
|
|
7
|
+
Each agent owns exactly `uracle_features/<id>.py`, root `test_feature_<id>.py`, and `feature_notes/<id>.md` for its ID. It may import `uracle_features.common`, standard library and NumPy. It must not import another feature, change these contracts/shared files, or edit package exports, packaging, README, workflow, CLI, integration fixtures, legacy files or Git. Tests are offline `unittest`; each fixture is labeled synthetic/provider-fixture, not a real feed or performance history.
|
|
8
|
+
|
|
9
|
+
The architect owns this file, `plan.md`, `TODO.md`, initial `uracle_features/__init__.py` and `uracle_features/common.py`. Shared foundation validation uses inline tests, not an extra root file. The later integration reducer alone owns final package exports, a new additive `uracle_features/pipeline.py`, `uracle_features/cli.py`, packaging, README, examples and root `test_feature_integration.py`. All feature result data crosses modules as the models or envelopes below, never by importing a peer implementation. Legacy `ResearchPipeline` stays independent; there is no implied compatibility between SPY daily prices and event-market odds.
|
|
10
|
+
|
|
11
|
+
## 2. Shared validation and units
|
|
12
|
+
|
|
13
|
+
All decision methods require keyword `as_of`; no implicit `datetime.now()` in business logic. Timestamp inputs are UTC-aware ISO-8601 strings with `T` and `Z`/`+00:00`, or UTC-aware `datetime`. Nonzero offsets and naive timestamps are rejected, rather than silently assigning a timezone. Output timestamps are `YYYY-MM-DDTHH:MM:SS.ffffffZ`. `require_fresh` accepts ages in **[0, max_age_seconds]**; future observations are rejected except the explicitly past-filtering line-history method. An order expires when `as_of >= expires_at`.
|
|
14
|
+
|
|
15
|
+
Numeric scalars must be real, finite, bounded and not bool (including NumPy bool); numeric strings are rejected except the settlement decimal-string schema. General magnitude <=1e12; decimal odds **(1,10000]**, probabilities **[0,1]**, fee rates **[0,1]**, stakes/liquidity >=0 with orders/positions requiring positive stake. Derived payouts, outlays and results must also remain finite and bounded. Collection sizes <=100000, feature defaults use much smaller windows, seeds integers in [0,2**32-1], and configuration must reject unknown keys. Reject invalid inputs before mutation. Transparent unavailable/warm-up estimates use null/missing diagnostic fields, not NaN or invented values.
|
|
16
|
+
|
|
17
|
+
`stake` is the pre-fee amount risked in `Market.currency`; fees are charged on stake independent of outcome. Gross outlay = `stake*(1+fee_rate)`; winning gross payout = `stake*decimal_odds`; net winning P&L = payout - outlay; losing P&L = -outlay. `available_stake` is the maximum pre-fee stake the source snapshot says is available at that exact price, not an executable guarantee. There is no FX conversion, leverage, signing or live execution. Trade price/quantity use prediction-share units, not arbitrary sports-book stake units.
|
|
18
|
+
|
|
19
|
+
Identifiers match `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}`; adapters must consistently canonicalize external identifiers, using `stable_key` for long/nonportable provider IDs. Currency codes are uppercase 3..12 character codes. Human-readable text is bounded and must not contain control characters. JSON serialization permits finite Python/NumPy real scalars and integral scalars, dict-like mappings with string keys, lists/tuples, strings, bool and null; no arbitrary objects, callable, pickle, eval, NaN or infinity. NumPy arrays must be converted with `.tolist()` explicitly. JSON size <=1 MiB, depth <=16, total nodes <=100000; file ingestion uses `load_json` to reject duplicate keys.
|
|
20
|
+
|
|
21
|
+
### Exact shared model constructors
|
|
22
|
+
|
|
23
|
+
All five models are frozen dataclasses in `common.py`. Their nested `Market` is immutable; `.to_dict() -> dict` returns a finite deep copy; `Class.from_dict(value: Mapping[str, Any]) -> Class` requires **all** serialized fields (including defaults), rejects extras, and revalidates the entire model. Direct constructors allow the defaults shown.
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
Market(event_id: str, market_id: str, outcomes: tuple[str, ...], currency: str, rules_id: str)
|
|
27
|
+
Quote(market: Market, outcome: str, bookmaker: str, decimal_odds: float,
|
|
28
|
+
available_stake: float, observed_at: str, source: str, fee_rate: float = 0.0)
|
|
29
|
+
Trade(market: Market, outcome: str, trade_id: str, source: str,
|
|
30
|
+
price: float, quantity: float, observed_at: str)
|
|
31
|
+
Position(position_id: str, market: Market, outcome: str, stake: float,
|
|
32
|
+
decimal_odds: float, probability: float, opened_at: str, fee_rate: float = 0.0)
|
|
33
|
+
PaperOrder(feature: str, idempotency_key: str, market: Market, outcome: str,
|
|
34
|
+
stake: float, decimal_odds: float, fee_rate: float, observed_at: str,
|
|
35
|
+
expires_at: str, owner_id: str = "application", rationale: str = "")
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
A `Market` declares 2..32 unique, mutually exclusive, exhaustive outcomes. This is a caller assertion of complete outcomes, **not** an independent provider verification. `rules_id` identifies settlement/push/void/overtime conventions; same event ID alone is never compatibility. `market.key: str` hashes event, market, sorted complete outcomes, currency and rules. Agents compare this key, not dataclass equality when outcome ordering differs. Outcomes in all nested models must belong to their market. `Quote.implied_probability` is `1/decimal_odds`, not a calibrated forecast. `Trade.price` is (0,1], quantity is positive, and `Trade.notional` is price*quantity in market currency. Position/order `.outlay` includes fees. Position probability refers to that position's outcome; `opened_at <= as_of` must be enforced by consumers.
|
|
39
|
+
|
|
40
|
+
Common helpers have these public signatures:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
finite_number(value, name="value", *, minimum=-1e12, maximum=1e12, strict_minimum=False) -> float
|
|
44
|
+
bounded_int(value, name="value", *, minimum=0, maximum=100000) -> int
|
|
45
|
+
text(value, name="value", *, max_length=512, allow_empty=False) -> str
|
|
46
|
+
identifier(value, name="identifier") -> str
|
|
47
|
+
currency_code(value) -> str
|
|
48
|
+
feature_id(value) -> str
|
|
49
|
+
parse_utc(value: str | datetime) -> datetime
|
|
50
|
+
utc_timestamp(value: str | datetime) -> str
|
|
51
|
+
require_fresh(observed_at, *, as_of, max_age_seconds: float) -> float # age seconds
|
|
52
|
+
json_copy(value) -> JSON-compatible value
|
|
53
|
+
canonical_json(value) -> str
|
|
54
|
+
load_json(value: str) -> JSON-compatible value
|
|
55
|
+
stable_key(*parts: str) -> str # SHA-256 of canonical JSON components, 1..32 bounded parts
|
|
56
|
+
result(feature: str, status: str, *, as_of, data: Mapping | None = None,
|
|
57
|
+
warnings: Sequence[str] = (), provenance: Sequence[Mapping] = ()) -> dict
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Shared result envelope
|
|
61
|
+
|
|
62
|
+
Every feature diagnostic/paper action returns this envelope, and every `data` field is machine-readable finite JSON:
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{"schema_version":1,"feature":"triggers","status":"ok","as_of":"2026-01-01T12:00:00.000000Z","mode":"research_paper","data":{},"warnings":[],"provenance":[]}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Statuses are exactly `ok`, `no_signal`, `warmup`, `unconfigured`, `unavailable`, `rejected`. `ok` means a diagnostic or paper action completed, not live configured or profitable. Malformed numeric/schema/timestamps raise `ValueError`; well-formed but unsuitable data, disabled adapters and market conditions return appropriate statuses with reasons. Ledger conflicts/limits are caught by feature action methods and exposed as `rejected`, with no write. A batch must be fully validated before changing history/settings; no partial ingestion on malformed input.
|
|
69
|
+
|
|
70
|
+
Each provenance item is `{source: str, observed_at: UTC, kind: "fixture"|"authorized"|"derived", reference?: str}`; no extra keys. It records actual source availability timestamps <=as_of. Provider publication time may also be included in feature `data`, but may not stand in for the time the information became available to the caller. Do not invent retrieval dates, fact verification, source authentication, rankings, neural models or real-time connections. Offline reducer fixtures use `kind="fixture"`.
|
|
71
|
+
|
|
72
|
+
## 3. Durable paper foundation — actual shared SQLite implementation
|
|
73
|
+
|
|
74
|
+
The application creates and injects **one** `PaperLedger` for an account, or opens the same file/policy after restart. There is no module-global ledger, implicit in-memory database, hidden wallet, or restore-from-untrusted snapshot. Ledger imports have no filesystem effects; explicit construction creates SQLite tables in the caller's chosen existing parent directory. Keep databases outside the committed repository. The caller closes the ledger/context manager.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
PaperLedger(path: str | Path, *, currency="USD", max_order_stake=100.0,
|
|
78
|
+
max_total_stake=1000.0, max_age_seconds=300.0, max_records=100000)
|
|
79
|
+
ledger.descriptor() -> dict # schema_version, absolute path, all policy fields
|
|
80
|
+
ledger.submit(order: PaperOrder, *, as_of, daily_cap: float | None = None) -> dict
|
|
81
|
+
ledger.reserve(feature: str, idempotency_key: str, payload: Mapping, *, as_of) -> dict
|
|
82
|
+
ledger.transition(record_id: str, state: str, *, as_of, details: Mapping | None = None) -> dict
|
|
83
|
+
ledger.get(record_id: str) -> dict | None
|
|
84
|
+
ledger.get_by_key(kind: str, feature: str, idempotency_key: str) -> dict | None
|
|
85
|
+
ledger.list_records(*, feature: str | None = None, kind: str | None = None, limit=1000) -> list[dict]
|
|
86
|
+
ledger.outlay_used(*, feature: str | None = None, owner_id: str | None = None,
|
|
87
|
+
since: UTC | None = None, until: UTC | None = None,
|
|
88
|
+
include_terminal=False) -> float # [since, until), no truncation
|
|
89
|
+
ledger.close() -> None
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`max_order_stake` and `max_total_stake` are legacy-friendly names for **gross-outlay** caps, including fees. Policies/path are read-only after opening and persisted in metadata; a restart with different policy/schema is rejected, not silently upgraded. `:memory:` is rejected. SQLite WAL + FULL synchronous + `BEGIN IMMEDIATE` + a unique `(kind,feature,idempotency_key)` constraint make creation and budget reservation atomic across processes/connections. Per-order cap <=total cap. Record capacity is bounded; no automatic eviction of dedup keys. One connection is not thread-shared; separate threads/processes open their own matching connections. SQLite lock/IO errors propagate without claiming completion. No multi-feature all-or-nothing transaction is promised.
|
|
93
|
+
|
|
94
|
+
A record is `{record_id, kind, feature, idempotency_key, payload, state, created_at, updated_at, audit}`. Each audit entry is `{sequence, state, as_of, details}`. Record IDs are `stable_key(kind,feature,key)`. Submission initially writes `submitted` (not an automatic fill); filling is an explicit paper simulation transition. Each transition and its audit write are in the same transaction. Reads validate order payloads, identities, legal audit chain and chronology. This is auditable local storage, **not** signed/tamper-proof evidence or guaranteed durability under hardware/filesystem failure.
|
|
95
|
+
|
|
96
|
+
- Order graph: `submitted -> filled | cancelled | rejected`; `filled -> settled`; cancelled/rejected/settled are terminal. Filled means a modeled full fill at frozen terms, not venue execution. Partial/live fills are unsupported. Filled orders retain budget until `settled`; only an explicit matching observed outcome should justify settlement. Cancellation only applies before a fill.
|
|
97
|
+
- Generic intent graph: `reserved -> paper_completed | cancelled | rejected`; all destinations terminal. SettlementBridge uses this graph, while naming its proposal/paper-settlement stages explicitly in diagnostics. `reserve` validates finite JSON/identity only; **SettlementBridge** must validate chain, asset, address and amount first. Generic intents never debit paper-order budget or move money.
|
|
98
|
+
- Retry of the same key and identical payload returns the existing record (even terminal/now stale), with no new audit entry or budget debit. Reuse with a changed payload raises `LedgerConflict`; it does not quietly resubmit on new quote terms. Keys must not include `as_of`, polling number, random UUID or restart generation.
|
|
99
|
+
- A repeated same-state transition with identical details is a no-op; changed details/illegal terminal transitions raise `LedgerConflict`. New transitions cannot predate the latest state. A fill rechecks quote age and expiration. Freshness/expiration is checked for **new** submissions, not durable identical retries.
|
|
100
|
+
- New submission enforces market currency, freshness, expiration, gross per-order and outstanding total caps. `daily_cap` additionally atomically caps all submitted orders for that feature + owner on the submission UTC date, **including** subsequently cancelled/rejected/settled orders. This avoids cancel/retry and multi-process daily-cap bypasses. `outlay_used` never truncates totals. `LedgerLimit` rejects without leaving a row or audit. Caller-side sizing is advisory; the ledger is final authority if concurrency changes capacity.
|
|
101
|
+
|
|
102
|
+
Feature order methods must constrain liquidity, their local cap and available ledger gross budget, then submit. Set `expires_at = observed_at + feature max_age_seconds` and apply the stricter of feature/ledger freshness windows. Check ownership (`record.feature`, and owner where relevant) before filling/cancelling; never transition another feature's record. Output `data.order`/`data.intent` is the full record or null. Legacy oracle capital is not debited; this is a separate paper account.
|
|
103
|
+
|
|
104
|
+
### State interfaces required of feature classes
|
|
105
|
+
|
|
106
|
+
All main feature classes expose `state_dict() -> dict` and `load_state_dict(state: Mapping) -> None`. State is schema 1 with exact top-level `{schema_version: 1, feature: <id>, config: {...}, state: {...}}`; enumerate the exact feature-owned keys in its note file. Stateless analytics preserve config and use empty state. Stateful ingestion preserves bounded validated history/dedup sets and timestamps; deterministic algorithms need no hidden RNG. Restore into a temporary validated instance/object and swap only on full success. Config, history, duplicate IDs, unknown keys and bounded counters are validated; failure leaves the original unchanged. Stateful classes cannot silently truncate a malformed restore. Snapshot copies are not writable aliases.
|
|
107
|
+
|
|
108
|
+
Order-backed feature state includes `state.ledger = ledger.descriptor()`; restore requires an injected ledger with the same descriptor. Ledger rows are **not** copied, rewound or reconstructed from feature state; restart duplicate protection comes from SQLite. Follow settings are persisted by `state_dict`/`load_state_dict` in the reducer's application checkpoint; without restoring opt-in settings the new copy instance follows nobody. Do not pretend changing an in-memory setting alone survives a process crash. Adapter objects/tokens are never checkpointed. Config rejects unknown arguments and constructor numeric bool/NaN/infinity. All main methods listed below are mandatory; extra private helpers are allowed, extra public feature APIs must not replace these.
|
|
109
|
+
|
|
110
|
+
## 4. Exact per-feature APIs and acceptance ownership
|
|
111
|
+
|
|
112
|
+
Annotations below use `Sequence` and `Mapping` from typing; `UTC` means `str | datetime` accepted by the common parser. Every API returns an envelope unless explicitly noted. Each agent writes its own offline root unittest suite and notes with equations, actual limitations, validated provider references where applicable, invocation examples and test commands.
|
|
113
|
+
|
|
114
|
+
### whale — Whale Tracker
|
|
115
|
+
|
|
116
|
+
Owned class and methods:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
WhaleTracker(threshold_notional=10000.0, min_history=3, max_age_seconds=300.0, window=1000)
|
|
120
|
+
tracker.ingest(trades: Sequence[Trade], *, as_of: UTC) -> dict
|
|
121
|
+
PolymarketTradeAdapter(*, enabled=False, timeout_seconds=10.0)
|
|
122
|
+
adapter.fetch(market: Market, *, as_of: UTC, limit=100) -> dict
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`ingest` deduplicates `(source,trade_id)`, validates chronological source availability/freshness and retains <=window observations. Large means observed `notional >= threshold_notional`. Report `data.large_trades` (Trade dicts), `accepted_count`, `duplicate_count`, `sample_count`, and `value_signal` (null while warm-up; otherwise bounded transparent observed imbalance score in [-1,1] with explicit outcome and sample denominator). If pooling several markets/outcomes, produce per-market/outcome diagnostics rather than silently mixing currencies/directions. Absence of large prints is `no_signal`, insufficient samples `warmup`. This is observed volume, not wallet intent, order-book depth, insider evidence or guaranteed value.
|
|
126
|
+
|
|
127
|
+
`fetch` returns `{data: {trades: [Trade.to_dict(), ...]}}` in the common envelope. Disabled is `unconfigured` without network access. Enabled uses only independently verified documented **read-only public Polymarket trade** endpoints, explicit timeout, bounded limit/response, and no embedded secrets. The feature agent owns provider documentation verification and fixture mapping; no URL has been verified by the architect. Provider condition/outcome IDs must map to the supplied complete Market; ambiguous/out-of-market rows are rejected. Observed timestamps must be <=as_of. If API schema, permissions, availability or mapping cannot be established, report unavailable honestly and retain the functional offline tracker. Tests own threshold equality, finite/bool validation, dedup/window, fixture parsing, opt-in/no-network default, staleness/future rejection, and atomic state restore.
|
|
128
|
+
|
|
129
|
+
### sentiment — Sentinel Sentiment
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
SentinelSentiment(max_adjustment=0.05, max_age_seconds=3600.0, dedup_limit=10000)
|
|
133
|
+
sentinel.ingest(events: Sequence[Mapping], *, as_of: UTC) -> dict
|
|
134
|
+
sentinel.adjust(event_id: str, prior_probability: float, *, as_of: UTC) -> dict
|
|
135
|
+
sentinel.poll(adapter: AuthorizedSourceAdapter, *, as_of: UTC) -> dict
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Define the local `AuthorizedSourceAdapter` protocol with `name: str`, `authorized: bool` and `fetch(*, as_of: UTC) -> Sequence[Mapping]`. The injected caller implements an authenticated, permitted source; adapters are disabled/unauthorized until explicitly configured. It is an interface, not a claim of shipped X/Discord/news integrations. `poll` refuses unauthorized adapters before calling fetch and never scrapes private channels. The local event mapping has exactly `{event_key, event_id, source, observed_at, published_at, impact, confidence, kind, reference, text}`. IDs portable; text <=2048, reference <=1024; observed and published timestamps UTC with `published_at <= observed_at <= as_of`; impact [-1,1], confidence [0,1]; kind is `information`, `opinion` or `rumor`. Source/reference provenance is required; a supplied kind is not independent fact verification.
|
|
139
|
+
|
|
140
|
+
Dedup by `(source,event_key)` before adjustment, bounded retained events <=dedup_limit; reject overflow rather than evicting a key and claiming permanent dedup. Rumor events have **zero effective impact**; there is no automatic rumor verification or fake neural network. Only retained fresh events matching event_id contribute. Explicit baseline: `delta = clip(max_adjustment * sum(impact*confidence for non-rumor eligible events), -max_adjustment, max_adjustment)` and `adjusted = clip(prior_probability + delta,0,1)`. Report `prior_probability`, `adjusted_probability`, `delta`, `event_count`, `ignored_rumors`, contributions/provenance; no events is warm-up with unchanged prior, not a calibrated forecast. Ingestion reports accepted/duplicate counts. Tests own formula/caps/boundaries, matching event IDs, rumor neutrality, source/published chronology, unauthorized no-fetch, dedup/replay and atomic restore.
|
|
141
|
+
|
|
142
|
+
### arbitrage — Multi-Book Arbitrage Sniper
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
ArbitrageSniper(min_books=10, max_age_seconds=120.0,
|
|
146
|
+
max_time_skew_seconds=30.0, min_profit_fraction=0.0)
|
|
147
|
+
sniper.aggregate(adapters: Sequence[BookmakerAdapter], *, as_of: UTC) -> dict
|
|
148
|
+
sniper.scan(quotes: Sequence[Quote], *, as_of: UTC, total_stake: float) -> dict
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Local `BookmakerAdapter` protocol has `name: str`, `authorized: bool` and `fetch(*, as_of: UTC) -> Sequence[Quote]`. `aggregate` invokes only explicitly authorized adapters and returns `data.quotes` as Quote dicts, `configured_books`, and limitations; default absence is unconfigured. Network permissions/credentials belong to the application; ten synthetic books are not ten configured live providers.
|
|
152
|
+
|
|
153
|
+
`min_books` integer >=10. Group quotes by complete `market.key`; count a book only when it supplies every outcome for the same compatible market/rules/currency and fresh timestamps. Reject incompatible/incomplete/stale/future quotes and explain counts/reasons. Resolve repeated book/outcome quotes deterministically using latest <=as_of (ties with contradictory values rejected). Selected legs must satisfy time skew. Choose best effective decimal odds `d/(1+fee_rate)` for each outcome, without using a negative or absent liquidity assumption.
|
|
154
|
+
|
|
155
|
+
For selected legs set `q = sum((1+f_i)/d_i)`. A candidate requires `q < 1`, expected net profit fraction `1/q-1 > min_profit_fraction`, complete outcomes and positive liquidity. Requested total_stake is **gross** budget. Target equal payout `R = total_stake/q`; cap `R <= min(available_stake_i*d_i)` and recompute `stake_i=R/d_i`, gross outlay, unused budget and net payout-minus-outlay. Report `data.opportunities` with market, >=10 book count, selected Quote dicts, stakes, gross_outlay, equal_payout, net_profit, profit_fraction, timestamps and executable assumptions; zero candidates is no_signal. Do not submit live or paper orders automatically. Tests own >=10 complete books (9 insufficient), exact arithmetic including fees/liquidity, incomplete/incompatible markets, skew/stale/future, deterministic aggregation, no-network default and no risk-free/guaranteed-return wording.
|
|
156
|
+
|
|
157
|
+
### triggers — Trigger Execution
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
TriggerExecutor(ledger: PaperLedger, *, max_stake=100.0, max_age_seconds=120.0)
|
|
161
|
+
executor.evaluate(quote: Quote, model_probability: float, requested_stake: float,
|
|
162
|
+
*, trigger_id: str, as_of: UTC) -> dict
|
|
163
|
+
executor.fill(order_id: str, *, as_of: UTC) -> dict
|
|
164
|
+
executor.cancel(order_id: str, *, as_of: UTC) -> dict
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Condition is exactly `quote.decimal_odds >= 1.80 AND (model_probability - 1/quote.decimal_odds) > 0.05`. Equality at odds qualifies; equality at edge does **not**. Do not round before the comparison or add tolerance. Include fee-aware net expected return `p*d-(1+fee)` and reject nonpositive net EV. Requested stake is >=0; zero yields no_signal. Cap pre-fee stake by requested, local max_stake, quote liquidity and remaining ledger gross capacity divided by `(1+fee)`; ledger enforces final cap, including per-order gross cap. Report `condition_met`, `edge`, `net_expected_return`, `bounded_stake`, `order`/reason. Positive eligible bounded stake submits exactly one paper order. Idempotency key is `stable_key("triggers", trigger_id, market.key, outcome)`, owner `application`; a new intent needs a new caller-supplied trigger_id, not a new polling timestamp. Identical retries return the durable existing record; changed payload same key is rejected. Explicit fill/cancel own only triggers records. Tests own >=1.80/>0.05 boundary semantics, fees/zero/liquidity/budgets, terminal cancellation, repeated/changed-key behavior, database reopen and no real adapter execution.
|
|
168
|
+
|
|
169
|
+
### line_movement — Line-Movement Prediction
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
LineMovementPredictor(window=30, min_history=5, horizon_seconds=300.0,
|
|
173
|
+
confidence_level=0.90, max_age_seconds=3600.0)
|
|
174
|
+
predictor.forecast(quotes: Sequence[Quote], *, as_of: UTC) -> dict
|
|
175
|
+
predictor.closing_line_value(entry: Quote, closing: Quote, *, as_of: UTC) -> dict
|
|
176
|
+
simulate_odds_history(market: Market, outcome: str, *, as_of: UTC,
|
|
177
|
+
bookmaker="simulation", seed=0, n_steps=60, step_seconds=60,
|
|
178
|
+
start_probability=0.5, drift_per_step=0.0, noise_std=0.01) -> list[Quote]
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Forecast filters future observations **before** selecting the fitting window, uses only one compatible market/book/outcome series, and rejects unsorted/duplicate **past** timestamps. Fit a transparent OLS trend of `1/decimal_odds` against elapsed seconds, not a future-close label or unordered index. Require min_history <=window and latest available quote fresh; warm-up reports null forecast/uncertainty and samples. Clip probability predictions to [1/10000,1-1e-6] so reciprocal decimal odds satisfy the common bounds; simulation uses the same bounds. Report `market`, `outcome`, `samples`, `training_end`, `forecast_at`, `predicted_probability`, `predicted_decimal_odds`, `slope_per_second`, and bounded `uncertainty` using residual spread with an explicitly uncalibrated diagnostic interval/assumptions. confidence_level in (0,1) is not a coverage guarantee. `forecast_at > as_of` is a **target**, never provenance or an input.
|
|
182
|
+
|
|
183
|
+
CLV requires matching market/book/outcome, entry.observed_at < closing.observed_at <=as_of; reports `clv_fraction=entry.decimal_odds/closing.decimal_odds-1` and implied-probability change, with both timestamps and fee limitations. Closing odds may be evaluated only after they were available and never enter an earlier forecast. Simulation is seeded NumPy, bounded n_steps and probabilities/odds, timestamps ending at as_of, and source `synthetic simulation`; it is not history. Tests own a known chronological slope, warm-up, append-future invariance, no-look-ahead at each simulation step, unsorted/duplicate past rejection, interval/seed reproducibility, analytical CLV signs and invalid chronology.
|
|
184
|
+
|
|
185
|
+
### copy_trading — Alpha-Copy Syndicate
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
AlphaCopySyndicate(ledger: PaperLedger, *, max_age_seconds=120.0)
|
|
189
|
+
syndicate.set_follow(follower_id: str, leader_id: str, *, enabled=False,
|
|
190
|
+
scale=1.0, max_stake=25.0, daily_cap=100.0) -> None
|
|
191
|
+
syndicate.replicate(follower_id: str, signal: Mapping, quote: Quote, *, as_of: UTC) -> dict
|
|
192
|
+
syndicate.fill(order_id: str, *, as_of: UTC) -> dict
|
|
193
|
+
syndicate.cancel(order_id: str, *, as_of: UTC) -> dict
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Follow is off by default; enabled must be actual bool. Settings are caller opt-in, scale [0,10], local max_stake/daily cap finite nonnegative. Signal exact keys `{signal_id, leader_id, event_id, market_id, outcome, currency, stake, observed_at}`; stake nonnegative. Validate fresh signal/quote, all market/outcome/currency identities, and signal timestamp <=as_of. No fabricated leaders, rankings, returns or authenticated identity guarantees. Unfollowed/disabled leader returns no_signal. Size by leader signal stake*scale, max_stake, liquidity, ledger gross remaining/per-order caps and daily gross remaining, accounting for fees. Use owner_id=follower_id and **atomic** `ledger.submit(..., daily_cap=setting.daily_cap)`; daily use is UTC-day accepted gross outlay including terminal orders.
|
|
197
|
+
|
|
198
|
+
Key is `stable_key("copy_trading", follower_id, leader_id, signal_id)` independent of quote refresh/restart. Duplicate retries return existing order before recreating or resizing it; a modified signal/order at the same identity cannot produce a second order. Return `follower_id`, `leader_id`, `signal_id`, `bounded_stake`, `copied`, `order`/reason. Follow settings survive only a valid application checkpoint restore, while SQLite independently protects order identity on restart. Tests own default off/explicit opt-in, capped/scaled and fee-aware sizing, wrong leader/market, duplicate signal and database reopen, daily cap after cancellation/restart, state rollback, and no invented ranking/performance.
|
|
199
|
+
|
|
200
|
+
### portfolio — Portfolio Variance Guard
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
PortfolioVarianceGuard(concentration_limit=0.25, max_positions=1000, confidence_level=0.95)
|
|
204
|
+
guard.assess(positions: Sequence[Position], covariance: Sequence[Sequence[float]],
|
|
205
|
+
*, as_of: UTC, capital: float) -> dict
|
|
206
|
+
guard.monte_carlo(positions: Sequence[Position], covariance: Sequence[Sequence[float]],
|
|
207
|
+
*, as_of: UTC, capital: float, seed=0, n_samples=10000) -> dict
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Require unique position_id, opened_at<=as_of, common currency (no FX), bounded exposure, positive capital, and a finite square matrix in **the supplied position order**. Covariance is covariance of one-horizon **net return per pre-fee stake**, not dollar P&L, correlation or raw prices. Validate dimensions, symmetry (explicit small tolerance), PSD (allow only numerical tolerance, reject meaningful negative eigenvalues), diagonal >=0 and correlation consistency, including zero-variance rows. No silently coercing bool/string matrices. Probability inputs supply modeled means `mu_i=p_i*d_i-1-fee_i`; covariance is caller-supplied dependence, not inferred proof of correlation. Same-market opposing positions should use compatible modeled covariance, not assume independence.
|
|
211
|
+
|
|
212
|
+
Analytical dollar mean = sum(stake_i*mu_i); dollar variance = s.T@C@s; standard deviation = sqrt(variance). Expose input position ordering, stake/exposure fractions, total_outlay, event/market concentration, covariance assumptions, modeled risk and warnings when concentration/exposure exceeds configured limits/capital. Distinguish modeled loss quantile from long-only worst-case outlay: total_outlay is a conservative stake-loss upper bound under these simple contracts (may not be jointly attainable for exhaustive opposing outcomes), **not** a Gaussian quantile or live guarantee. No new orders.
|
|
213
|
+
|
|
214
|
+
Monte Carlo uses bounded seeded NumPy correlated normal net returns with validated covariance; report sample mean/variance, modeled loss quantile/expected shortfall, seed/n_samples and theoretical values. Gaussian losses can exceed stake outlay; do not clip them and claim maximum-loss protection. Tests own two-position correlated analytical variance, diagonal/ordering/PSD/symmetry/zero-variance cases, deterministic Monte Carlo convergence, concentration and currency mismatch, finite/bool handling and explicit modeled-versus-maximum warnings.
|
|
215
|
+
|
|
216
|
+
### props — Prop Sniper Heatmaps
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
PropSniperHeatmaps(min_samples=5, window=20, max_age_seconds=86400.0)
|
|
220
|
+
sniper.analyze(samples: Sequence[Mapping], lines: Sequence[Mapping], *, as_of: UTC) -> dict
|
|
221
|
+
sniper.export_svg(heatmap: Mapping, path: str | Path) -> str # absolute written path
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Sample exact fields `{sample_id, player_id, stat, unit, value, observed_at, source}` with unique sample identity `(source,sample_id)`, value finite nonnegative, IDs portable, unit bounded explicit text and source text <=256. Line exact fields `{player_id, stat, unit, line, over_quote, under_quote}`; over_quote/under_quote are validated `Quote` instances at the API boundary (reducer rehydrates JSON). Require their same `market.key`, currency/book, outcomes `over`/`under`, exhaustive market outcomes exactly those two, fresh line quote timestamps and line finite nonnegative. Match player/stat/**unit**; never mix incompatible statistics. Rules must explicitly identify push handling; report equality count/push assumptions instead of counting a tie as a win.
|
|
225
|
+
|
|
226
|
+
Use only samples observed<=as_of, chronologically selected <=window, with timestamps/source provenance; stale samples can be a historical sample but last matching sample must meet configured age or report unavailable. Insufficient matching samples is warmup for that cell. Report `data.cells` containing player/stat/unit, line, samples, sufficient flag, sample_start/end, mean, discrepancy (mean-line), observed-over/under/tie fractions, quote implied probabilities, uncalibrated diagnostic score and reason; keep insufficient estimates null. Fraction estimates/trend discrepancy are not a neural prediction or actionable certainty. Mixed-cell envelope can be ok with per-cell statuses; all insufficient is warmup.
|
|
227
|
+
|
|
228
|
+
`export_svg` takes the **whole props envelope** from analyze, revalidates it, emits bounded deterministic standalone SVG with title/description, textual row/column labels, numeric data and sample/insufficiency legend; color is not the only information channel. Escape untrusted labels, do not execute scripts or embed remote assets; refuse oversized exports. Explicit caller path is the only write. Tests own matching/mismatched units/player/stat, sample warm-up/timestamp/future exclusion, arithmetic/ties, finite diagnostics, XML escaping/accessibility and temporary-directory visual export. No website is needed.
|
|
229
|
+
|
|
230
|
+
### hedging — Auto-Hedge Lifecycle
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
AutoHedgeLifecycle(ledger: PaperLedger, *, probability_threshold=0.40,
|
|
234
|
+
max_stake=100.0, max_age_seconds=120.0)
|
|
235
|
+
hedger.evaluate(position: Position, latest_probability: float, hedge_quote: Quote,
|
|
236
|
+
*, probability_observed_at: UTC, hedge_id: str, as_of: UTC) -> dict
|
|
237
|
+
hedger.fill(order_id: str, *, as_of: UTC) -> dict
|
|
238
|
+
hedger.cancel(order_id: str, *, as_of: UTC) -> dict
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Threshold condition is **latest_probability < probability_threshold**, referring to the original position outcome; equality does not trigger. Require position opened<=as_of, fresh probability_observed_at (not just a fresh quote), and a fresh compatible hedge quote for the **other outcome of a binary complete market**, same currency/rules. Reject unsupported multi-outcome hedge construction, same-side quote, stale/future probability or quote snapshot, nonpositive liquidity and contradictory identities. Position is caller-supplied paper exposure, not independently verified live wallet holdings.
|
|
242
|
+
|
|
243
|
+
Equal-payout pre-fee hedge size is `position.stake*position.decimal_odds/hedge_quote.decimal_odds`; cap by local max_stake, quote liquidity, per-order and remaining ledger gross budgets. Fees charged on both original and hedge stakes must be shown. Report condition, requested/bounded hedge stake, hedge cost, original-outcome and hedge-outcome net P&L, residual payout imbalance, before/after modeled worst P&L, `order` and liquidity/cap warnings. Reject nonpositive or non-improving modeled worst-case protection rather than claiming all hedges help. Capped hedges need not fully equalize payoffs or produce profit.
|
|
244
|
+
|
|
245
|
+
Key `stable_key("hedging", hedge_id, position.position_id, position.market.key)` is repeat/restart stable; caller must use a new hedge_id for a genuinely new lifecycle. Owner_id=position.position_id. Duplicate identity returns prior durable record, never increases exposure. Fill/cancel only owned hedging orders. Tests own strict threshold, exact equalization/fees, cap/liquidity behavior and worst-case improvement, same-side/incompatible/stale rejection, cancellation/fill lifecycle and reopen duplicate protection. No automatic live hedging authorization.
|
|
246
|
+
|
|
247
|
+
### settlement — Settlement Bridge
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
SettlementBridge(ledger: PaperLedger, *, allowed_chains: Mapping | None = None,
|
|
251
|
+
max_amount=1000.0, max_age_seconds=300.0)
|
|
252
|
+
bridge.propose(request: Mapping, *, as_of: UTC) -> dict
|
|
253
|
+
bridge.paper_settle(record_id: str, *, as_of: UTC) -> dict
|
|
254
|
+
bridge.cancel(record_id: str, *, as_of: UTC) -> dict
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
No chains enabled by default: valid-shaped request returns unconfigured, no network. The explicit registry has chain-name keys mapping to exact `{chain_id, assets}`; chain_id positive integer <=2**32-1, assets maps uppercase asset code to exact `{decimals, contract}` with decimals integer 0..36 and contract null for a native asset or a supported EVM token contract address. Support only implemented chain/address/asset families; unimplemented non-EVM chains are rejected/unavailable, not silently assumed compatible. Registry is caller configuration, not independent chain identification.
|
|
258
|
+
|
|
259
|
+
Request exact keys `{request_id, chain, asset, address, amount, source_ref, observed_at}`. Validate portable request/chain IDs, registry chain/asset, nonzero EVM address and contract shape (`0x` + 40 hex), positive **decimal-string** amount <=max_amount and precise asset decimals without float rounding, fresh observed_at, and bounded source_ref. Reject zero/negative/nonfinite/excess-precision amounts, floats/bools for amount, unsupported chain/asset, zero address and malformed recipient/contract. Without Keccak/EIP-55 support do **not** claim checksum verification; mixed-case addresses must be rejected or explicitly labeled shape-only and require later verification. No balance/ownership/recipient identity verification is implied.
|
|
260
|
+
|
|
261
|
+
Construct a finite unsigned transaction **proposal**, including chain_id, recipient, asset, atomic amount as a decimal string, destination/value/calldata only when correctly implemented (native value or verified ERC-20 transfer encoding). Report missing nonce/gas/fee/balance/RPC/chain verification explicitly; a proposal is not ready for broadcast merely because its fields are shaped. Persist it with `ledger.reserve("settlement", stable_key("settlement",request_id), proposal, as_of=as_of)`. `data.intent` is the generic record, `data.proposal` the unsigned fields, and `data.lifecycle` is proposed/paper_settled/cancelled/rejected mapped to reserved/paper_completed/cancelled/rejected ledger states. `paper_settle` transitions only settlement intents to paper_completed; no signatures, private keys, RPC broadcasts, payouts, actual transfer confirmations or real reinvestment. Max_amount is a per-proposal paper limit; generic intents do not reserve actual funds or guarantee a daily financial budget.
|
|
262
|
+
|
|
263
|
+
Tests own chain/asset/address/decimal precision and atomic-unit calculations, disabled/default behavior, unsupported/malformed inputs, stale proposals, unsigned/no-key/no-network surfaces, changed-key conflict, paper lifecycle/cancellation/reopen audit and exact restart dedup. Notes must distinguish implemented address shape/unsigned encoding from genuinely unsupported live wallet dependencies.
|
|
264
|
+
|
|
265
|
+
## 5. Reducer handshake and outcome criteria
|
|
266
|
+
|
|
267
|
+
Reducer implements `FeaturePipeline(ledger: PaperLedger, *, config: Mapping | None = None)` with registry mapping the exact ten IDs to their mandatory main classes. `run(request: Mapping, *, as_of: UTC) -> dict` accepts exact `{feature, operation, inputs}` and explicitly dispatches the methods above; no `eval`, dynamic arbitrary attributes, plugin import paths or arbitrary execution. Hydrate common models from strict dicts; missing disabled adapters stay unconfigured. Ledger is injected, not inferred from a feature result. No hidden automatic fill: CLI demo must show submit then explicit paper-fill separately. A deterministic `demo(*, as_of: UTC, seed=0) -> dict` invokes actual code for **all ten IDs** using labeled offline fixtures, >=10 complete synthetic books, enough trend/prop samples, and paper execution/settlement. Result `{schema_version:1,mode:"research_paper",as_of,results:{<id>:envelope},limitations:[...]}`; requested online providers require explicit opt-in application configuration.
|
|
268
|
+
|
|
269
|
+
Reducer adds installed `uracle-features` command without changing `uracle-backtest`: a required UTC `--as-of`, explicit `--ledger` file for paper mutations, offline `demo`, a bounded finite JSON request path for `run`, and explicit application checkpoint read/write if supporting follow-state restoration. Installed packaging includes `uracle_features` while preserving distribution name/version, dependency NumPy and existing modules/scripts. No website/services or real execution switches. Public exports reflect actual implemented APIs only. Full workflow validation must show each feature invoked, not just imported or named in a feature list.
|
|
270
|
+
|
|
271
|
+
Acceptance is code + tests + honest notes, not feature marketing. Each feature suite must test malformed state rollback, finite JSON, explicit UTC and bool/nonfinite boundaries as relevant, no-network defaults, required math, provenance, and stated unavailable boundaries. Reducer owns cross-feature order-to-position conversion after explicit paper fill, shared budget/idempotence across triggers/copy/hedging, settlement separation, checkpoint + SQLite reopen tests, concurrent-connection cap tests, all-ten demo/dispatch, installed-wheel imports/CLI and legacy regression. Final read-only reviewer traces every requirement to actual invoked code/test and identifies live unconfigured gaps; parent alone decides final Git saving, never release/publish/real money.
|