Metadata-Version: 2.4
Name: sablier-flow
Version: 0.4.1
Summary: Synthetic alternative-history generation for backtest overfitting detection
Project-URL: Homepage, https://sablier.ai/flow
Project-URL: Repository, https://github.com/sablier-it/sablier-flow
Project-URL: Issues, https://github.com/sablier-it/sablier-flow/issues
Project-URL: Documentation, https://sablier.ai/flow/docs
Project-URL: Changelog, https://github.com/sablier-it/sablier-flow/blob/main/CHANGELOG.md
Author-email: Sablier <team@sablier.it>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Sablier
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: backtesting,flow-matching,overfitting,quantitative-finance,synthetic-data
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: cryptography>=42.0
Requires-Dist: httpx>=0.27
Requires-Dist: numpy<2.0,>=1.24
Requires-Dist: pandas<3.0,>=2.0
Requires-Dist: pyarrow>=14.0
Requires-Dist: pydantic<3.0,>=2.0
Requires-Dist: scipy>=1.11
Requires-Dist: tqdm>=4.65
Requires-Dist: typing-extensions>=4.8
Provides-Extra: adapters-backtrader
Requires-Dist: backtrader>=1.9.78; extra == 'adapters-backtrader'
Provides-Extra: adapters-vectorbt
Requires-Dist: vectorbt>=0.26; extra == 'adapters-vectorbt'
Provides-Extra: all
Requires-Dist: backtrader>=1.9.78; extra == 'all'
Requires-Dist: causal-conv1d==1.2.0.post2; extra == 'all'
Requires-Dist: einops>=0.7; extra == 'all'
Requires-Dist: fastapi>=0.110; extra == 'all'
Requires-Dist: google-cloud-tasks>=2.16; extra == 'all'
Requires-Dist: hypothesis>=6.92; extra == 'all'
Requires-Dist: mamba-ssm==2.0.4; extra == 'all'
Requires-Dist: mkdocs-gen-files>=0.5; extra == 'all'
Requires-Dist: mkdocs-material>=9.5; extra == 'all'
Requires-Dist: mkdocstrings[python]>=0.25; extra == 'all'
Requires-Dist: mypy>=1.10; extra == 'all'
Requires-Dist: pytest-asyncio>=0.23; extra == 'all'
Requires-Dist: pytest-cov>=4.1; extra == 'all'
Requires-Dist: pytest>=8.0; extra == 'all'
Requires-Dist: ruff>=0.4.0; extra == 'all'
Requires-Dist: scikit-learn>=1.3; extra == 'all'
Requires-Dist: scipy>=1.11; extra == 'all'
Requires-Dist: sqlalchemy>=2.0; extra == 'all'
Requires-Dist: torch<2.3,>=2.2; extra == 'all'
Requires-Dist: vectorbt>=0.26; extra == 'all'
Provides-Extra: core
Requires-Dist: causal-conv1d==1.2.0.post2; extra == 'core'
Requires-Dist: einops>=0.7; extra == 'core'
Requires-Dist: mamba-ssm==2.0.4; extra == 'core'
Requires-Dist: scikit-learn>=1.3; extra == 'core'
Requires-Dist: scipy>=1.11; extra == 'core'
Requires-Dist: torch<2.3,>=2.2; extra == 'core'
Provides-Extra: dev
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: google-cloud-tasks>=2.16; extra == 'dev'
Requires-Dist: hypothesis>=6.92; extra == 'dev'
Requires-Dist: mkdocs-gen-files>=0.5; extra == 'dev'
Requires-Dist: mkdocs-material>=9.5; extra == 'dev'
Requires-Dist: mkdocstrings[python]>=0.25; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: sqlalchemy>=2.0; extra == 'dev'
Provides-Extra: validation
Requires-Dist: scikit-learn>=1.3; extra == 'validation'
Requires-Dist: scipy>=1.11; extra == 'validation'
Description-Content-Type: text/markdown

# sablier-flow

> **Stop shipping overfit backtests.**
> Run your strategy on **N alternative versions of history** that share your data's statistical fingerprint. If the strategy only works on the one specific past that happened, that's a problem you can now measure.

---

## What you get in 30 lines

```python
import pandas as pd
import sablier_flow as sf

# 0. Auth — set SABLIER_FLOW_API_KEY env var, or pass api_key="sk_live_..." per call
# 1. Load your data: any DataFrame with a DatetimeIndex + numeric columns
real = pd.read_parquet("my_universe.parquet")
backtest_window = real.loc["2023-01-01":"2024-01-01"]   # the slice you'll evaluate

# 2. Fit (~5–10 min, ~48 credits). Server splits 80/20 with a 21-bar embargo
#    and keeps the held-out OOS slice encrypted next to the model for validate().
fit = sf.fit(real, target_features=list(real.columns), horizon=504,
             train_split=0.8, embargo_days=21, seed=42)

# 3. Validate on the held-out OOS (zero-config, 1 credit). 'pass' + 'low' is good.
report = sf.validate(fit.model_id)
assert report.overall == "pass" and report.memorization_risk == "low"

# 4. Generate paths shaped like your backtest window (~2 credits, sub-minute)
paths = sf.generate(fit.model_id, n_paths=1000, like=backtest_window, seed=42)
synth_dfs = paths.as_dataframes()                          # list[pd.DataFrame]

# 5. Run your existing backtest — unchanged — on the real window and on each synthetic
real_result   = my_backtest(backtest_window)
synth_results = [my_backtest(df) for df in synth_dfs]

# 6. The smoking gun
verdict = sf.robustness(real_result, synth_results, primary_metric="sharpe")
print(verdict.verdict)         # 'robust' | 'borderline' | 'overfit' | 'highly_overfit'
print(verdict.overfit_score)   # 0.85 → real result sits at the top 15% of synth → overfit
print(verdict.summary())       # one-line English summary you can paste into Slack
verdict.to_html("audit.html")  # shareable single-file report
```

Two-step fit + generate (instead of one-shot) means you fit once and generate as many windows as you want from the same `model_id` — cheap iteration on your strategy without paying to retrain. See [`examples/00_getting_started.ipynb`](examples/00_getting_started.ipynb) for the explicit 7-step walkthrough.

**Real verdict from a real customer flow** (SPY MA-crossover, 2023):

```
VERDICT: OVERFIT
Backtest Overfitting Score: 85%

Your real Sharpe:       +1.639
Synthetic median:       +0.510
Synthetic 95% CI:       [-1.036, +2.315]

Diagnostics from the TEE (bundled with the result):
  Memorization risk:    low (NN-ratio 1.18)
  Structural validation: PASS
    - marginal_std_ratio              +0.97  [pass]
    - marginal_kurtosis_ratio         +0.93  [pass]
    - cross_asset_correlation_mae     +0.005 [pass]
    - lag1_autocorr_error             +0.04  [pass]
```

What it's telling you: the strategy's real-data Sharpe of 1.64 looks great, but it sits in the top 5% of what the same strategy would have produced on alternative histories with identical statistical structure. That gap *is* the overfit signal.

---

## Install

```bash
pip install sablier-flow                            # thin client only
pip install 'sablier-flow[adapters-backtrader]'     # + backtrader integration
pip install 'sablier-flow[adapters-vectorbt]'       # + vectorbt integration
```

Get your API key:

1. Sign in (or sign up — 500 free credits for new accounts) at <https://sablier.ai>
2. Dashboard → Settings → API Keys → New API Key
3. Copy the `sk_live_...` value (shown once)

```bash
export SABLIER_FLOW_API_KEY=sk_live_<your-token>
```

That's the whole setup. The default endpoint is `https://flow.sablier.ai/v1` over standard TLS — no `gcloud`, no cert pinning, no extra steps. A typical fit + validate + generate cycle costs ~51 credits (fit ~48 cr + validate 1 cr + generate ~2 cr); the free signup gift covers ~10 full cycles. Top up via credit packs on the dashboard.

---

## What happens under the hood

```
your laptop ──HTTPS──> Sablier API (Cloud Run) ──Cloud Tasks──> Confidential VM (A3 H100)
     │                                                                │
     │   1.  POST /v1/jobs                                             │
     │   ◄── 2. attestation quote                                      │
     │                                                                 │
     │   3. envelope-encrypt your DataFrame                            │
     │   ──> PUT /v1/jobs/{id}/data ──────────────────────────────────►│
     │                                                                 │
     │                                       4. AMD SEV-SNP enclave    │
     │                                          decrypts your data     │
     │                                          trains flow model      │
     │                                          generates N paths      │
     │                                          AES-GCM-encrypts back  │
     │                                                                 │
     │   5. GET /v1/jobs/{id}/result ◄────────────────────────────────-│
     │   6. decrypt locally; result.paths_returns is yours             │
     ▼
backtester (pandas / backtrader / vectorbt / LEAN / your own)
```

**Trust narrative**: Every customer job runs inside an [AMD SEV-SNP](https://www.amd.com/en/developer/sev.html) confidential VM with an attestation quote you cryptographically verify against AMD's published root key, baked into the SDK release. Sablier insiders, GCP operators, and the host OS *cannot* see your data — it's encrypted in memory the moment it leaves your laptop until the moment it's encrypted back to you. See [`docs/concepts/data-sourcing.md`](docs/concepts/data-sourcing.md) for the full pitch on why this is the only architecture that works for proprietary fund data.

---

## Status

**Alpha — `v0.0.x`**, not on PyPI yet.

| Piece | State |
|---|---|
| Flow-model pipeline (train + generate + validate) | ✅ Working — real L4 GPU training verified end-to-end |
| Robustness scoring (`sablier_flow.robustness`) | ✅ Working |
| Memorization + structural validation bundled in response | ✅ Working — `result.memorization_risk` + `result.validation_overall` |
| Engine adapters (DataFrame / backtrader / vectorbt / LEAN) | ✅ Working — see `examples/02-04_*.ipynb` |
| Client ↔ TEE wire protocol (envelope encryption + attestation) | ✅ Locked, in-process tested, **plus live HTTPS roundtrip against a real SEV-SNP confidential VM verified** |
| Real AMD SEV-SNP attestation parser + AMD root chain | ✅ Working — VCEK→ASK→ARK verified against AMD's Milan root |
| Confidential VM deploy (n2d-standard SEV-SNP, CPU only) | ✅ Working — script + systemd unit |
| Confidential VM deploy (A3 H100 CC mode, GPU + CPU dual protection) | 🚧 Awaiting GCP H100 quota |
| NVIDIA NRAS GPU attestation chain | 🚧 Same gate |
| HXZ 452-anomaly validation study | 🚧 Harness scaffolded — needs the q-factor data |
| SOC 2 Type 1 | ⏳ External clock |
| PyPI publish | ⏳ Namespace reservation pending |

---

## Run the customer experience locally — no API key needed

```bash
git clone https://github.com/sablier-it/sablier-flow.git
cd sablier-flow
pip install -e '.[adapters-backtrader,adapters-vectorbt]' yfinance matplotlib
python examples/try_it_yourself.py
```

This script does the full workflow — yfinance pull → real Client class → in-process mock TEE that block-bootstraps your real returns → backtest distribution → robustness verdict + diagnostics → matplotlib histogram. The mock TEE returns realistic-looking synthetic paths in milliseconds (production uses a real GPU and produces *much* better data, but the API surface is identical). Run `examples/try_it_with_backtrader.py` for the backtrader-engine version.

For the live confidential-VM E2E run, see [`scripts/run_live_tee_demo.py`](scripts/run_live_tee_demo.py).

---

## Engine integrations

`sablier-flow` is a data layer, not a backtest engine. We integrate with whatever you already use:

| Engine | How |
|---|---|
| Raw pandas / numpy | `as_dataframes(result, index=...)` → `list[pd.DataFrame]` |
| backtrader | `as_backtrader_feeds(result, ticker_column=..., index=...)` → `list[bt.feeds.PandasData]` |
| vectorbt | `as_vectorbt_panel(result, ticker_column=..., index=...)` → wide `pd.DataFrame` |
| LEAN / QuantConnect | `write_lean_csv_universe(result, "lean-data/", index=...)` → per-path directories |
| In-house C++ / KDB / proprietary | `result.paths_prices` is plain `np.float32[n_paths, horizon, n_features]` — shim ≤ 50 lines |

See [`docs/concepts/engine-integration.md`](docs/concepts/engine-integration.md).

---

## Why "in-sample is correct" — short version

The model is trained on the same history your backtest will run on. If that triggers your overfit alarm, read [`docs/concepts/in-sample-is-correct.md`](docs/concepts/in-sample-is-correct.md). The TL;DR: the synthetic distribution is the data-generating process's neighborhood, not a re-creation of the data points themselves. We *gate* every result on a memorization metric (`result.memorization_risk`) that catches if the model is just regurgitating training samples — when it is, the SDK tells you `high` and you should not trust the overfit verdict.

---

## License

- **`src/sablier_flow/`** — Apache-2.0. SDK is open.
- **`server/`** (the TEE container code) — proprietary. Ships as a signed Docker image with a hash baked into each SDK release; customers verify the running image matches the digest they downloaded.

---

## Links

- [Examples](examples/)
- [Concepts docs](docs/concepts/)
- [Issues](https://github.com/sablier-it/sablier-flow/issues)
- [sablier.ai](https://sablier.ai)
