Enforces scalability, integration, and compatibility requirements when creating any new module in stochastic-rs — covers stochastic, quant, stats, distributions, copulas, and ai Use when this capability is needed.
Every new module must be scalable (trait-based extensibility), integrated (works with existing traits and pipelines), and compatible (derives, bounds, API conventions match the rest of the codebase).
1. Where to place new code
Determine the correct top-level module first. Do NOT create a new top-level module without explicit approval.
1---2name: new-module-23description: Enforces scalability, integration, and compatibility requirements when creating any new module in stochastic-rs — covers stochastic, quant, stats, distributions, copulas, and ai Use when this capability is needed.4---56# New Module Integration Rules78Every new module must be **scalable** (trait-based extensibility), **integrated** (works with existing traits and pipelines), and **compatible** (derives, bounds, API conventions match the rest of the codebase).910## 1. Where to place new code1112Determine the correct top-level module first. Do NOT create a new top-level module without explicit approval.1314| Domain | Top-level module | Registration file | Examples |15|---|---|---|---|16| Stochastic processes (diffusion, jump, volatility, noise, interest rate, autoregressive) | `stochastic/` | `src/stochastic.rs` | GBM, Heston, CIR, fBM, GARCH |17| Quantitative finance (pricing, bonds, calibration, calendar, FX, portfolio, strategies, vol-surface) | `quant/` | `src/quant.rs` | BSM pricer, schedule builder, FX forward |18| Statistical estimators & tests (MLE, KDE, stationarity, normality, spectral) | `stats/` | `src/stats.rs` | Gaussian KDE, ADF test, Hurst estimator |19| Probability distributions | `distributions/` | `src/distributions.rs` | Normal, Alpha-stable, NIG |20| Copula models | `copulas/` | `src/copulas.rs` | Clayton, Gaussian, Student-t |21| Neural network / AI models | `ai/` (feature-gated) | `src/lib.rs` | Vol calibration NN |2223### Adding a submodule within an existing top-level module2425Three file patterns exist in the project — choose the simplest that fits:2627**Pattern A — Leaf file** (single file, no subdirectory):28```29src/stats/my_estimator.rs30```31Use when the implementation is self-contained in one file. Most `stats/` and `distributions/` modules follow this.3233**Pattern B — Root file + directory** (multiple subfiles):34```35src/quant/my_module.rs ← module root: doc header, pub mod, re-exports, shared traits36src/quant/my_module/37 engine.rs38 types.rs39```40Use when the module has 2+ logical components. Most `quant/` modules (pricing, calibration, calendar, fx, bonds, vol_surface) follow this.4142**Pattern C — Directory with mod.rs** (when root defines shared types):43```44src/stochastic/mc/45 mod.rs ← defines McEstimate<T> + pub mod declarations46 lsm.rs47 mlmc.rs48```49Use when the module root itself defines shared types alongside submodule declarations. The `mc/` module and `noise/fgn/` follow this.5051### Module root must contain52531. `//!` doc comment with LaTeX formula summarising the core concept542. `pub mod` declarations for all submodules553. `pub use` re-exports of user-facing types564. Shared traits or types that submodules need (define at root, not in a subfile)5758### Registration5960- **Submodule within existing top-level:** add `pub mod my_module;` in the parent's `.rs` file (alphabetical order)61- **New top-level module:** add `pub mod my_module;` in `src/lib.rs` (requires approval per dev-rules)62- **Feature-gated module:** `#[cfg(feature = "my_feature")] pub mod my_module;`6364## 2. Trait integration map6566Before writing code, determine which existing traits the new types should implement.6768### `stochastic/` modules6970| Type | Required trait | Effect |71|---|---|---|72| Any stochastic process | `ProcessExt<T: FloatExt>: Send + Sync` | Gets `sample()`, `sample_par(m)` (rayon parallel), `sample_cuda(m)` |73| Process with Malliavin support | `MalliavinExt<T>` or `Malliavin2DExt<T>` | Malliavin derivative computation |74| Probability distribution | `DistributionExt` | CF, PDF, CDF, moments |75| SIMD-accelerated distribution | `DistributionSampler<T>` (from `distributions.rs`) | Bulk `fill_slice()` + `sample_matrix()` |7677### `quant/` modules7879| Type | Required trait | Effect |80|---|---|---|81| Option / derivative pricer | `TimeExt` + `PricerExt` | Date-aware pricing, `calculate_call_put()`, implied vol |82| Pricing model for (K, T) grids | `ModelPricer` | Enables vol-surface construction via `ModelSurface` blanket impl |83| Fourier / characteristic-function model | `FourierModelExt` | Auto-gets `ModelPricer` → `ModelSurface` via blanket impls |84| Calibration result | `ToModel` | Connects to `build_surface_from_calibration()` pipeline |85| Holiday / business-day calendar | `CalendarExt` | Plugs into `BusinessDayConvention::adjust()` and `ScheduleBuilder` |86| Type needing tau from dates | Use `TimeExt::tau_with_dcc(DayCountConvention)` | Proper day-count instead of hardcoded `/365.0` |8788### `copulas/` modules8990| Type | Required trait | Effect |91|---|---|---|92| Bivariate copula | `BivariateExt` | `sample()`, `fit()`, `pdf()`, `cdf()`, Kendall's tau |93| Multivariate copula | `MultivariateExt` | `sample()`, `fit()`, `pdf()`, `cdf()` |9495### Blanket-impl chains (do NOT duplicate by hand)9697```98FourierModelExt ──blanket──▸ ModelPricer ──blanket──▸ ModelSurface99```100101Implement the lowest-level trait; upstream is automatic.102103## 3. Extensibility — require a trait, not a concrete type104105When a new module accepts a pluggable component, define or reuse a **trait**.106107Pattern (from `BusinessDayConvention::adjust`):108```rust109pub fn my_function(calendar: &(impl CalendarExt + ?Sized)) -> NaiveDate {110 // works with &Calendar AND &dyn CalendarExt (trait objects)111}112```113114The `+ ?Sized` bound is required to also accept `&dyn Trait`.115116If the module creates a **new** extensibility point:1171. Define the trait in the **module root** (e.g., `my_module.rs`)1182. Implement it for the built-in concrete type1193. Re-export it1204. Accept `&(impl MyTrait + ?Sized)` in functions, not the concrete type121122## 4. Type requirements123124Every new `pub struct` and `pub enum` must have:125126| Requirement | How | Why |127|---|---|---|128| `Debug` | `#[derive(Debug)]` | Debugging, error messages |129| `Clone` | `#[derive(Clone)]` | Composability — users clone pricers, processes, calendars |130| `Send + Sync` | Automatic for simple types; verify with `Box<dyn …>` or `Rc` | Required for `ProcessExt`, `sample_par()`, rayon |131| `Display` (enums) | `impl Display` | Logging, error messages |132| `Default` (where meaningful) | `#[derive(Default)]` + `#[default]` on variant | Ergonomic construction |133| `Copy` (small value types) | `#[derive(Copy)]` | Enums and small structs without heap data |134| `Eq + Hash` (identifier types) | `#[derive(PartialEq, Eq, Hash)]` | Map keys, dedup, comparisons |135136**Do NOT add** `Serialize` / `Deserialize` — `serde` is not a dependency.137138## 5. Numeric conventions139140| Rule | Detail |141|---|---|142| Generic float | All numerical structs/functions use `T: FloatExt`. Never hardcode `f64`. Use `T::from_f64_fast()` for constants. |143| Arrays | Use `ndarray::Array1<T>`, `Array2<T>`. Never `Vec<T>` for numerical data. |144| Day fractions | Use `DayCountConvention::year_fraction()` or `TimeExt::tau_with_dcc()`. Never hardcode `/365.0` or `/360.0`. |145| Annualisation | Accept the factor as a parameter. Never hardcode `252.0` or `365.0`. |146| Random sampling | Use the project's `SimdRng` / `SimdFloatExt` infrastructure for SIMD-accelerated generation. |147| Complex numbers | Use `num_complex::Complex<T>`. |148149## 6. Re-export conventions150151In the module root, re-export **user-facing** types only:152153```rust154pub use engine::MyEngine;155pub use types::{MyConfig, MyResult};156```157158Keep internal helpers `pub(crate)` or private. Match the pattern of sibling modules in the same top-level module.159160## 7. Integration with existing pipelines161162### Pricing pipeline (quant)163If the module produces a pricer, verify it works with:164- `build_surface_from_model(&dyn ModelPricer, …)` — vol-surface construction165- `build_surface_from_calibration(&dyn ToModel, …)` — calibration → vol-surface166167### Calendar pipeline (quant)168If the module uses dates, verify it works with:169- `BusinessDayConvention::adjust(date, &calendar)` — business day adjustment170- `ScheduleBuilder::new(…).calendar(cal).build()` — schedule generation171- `TimeExt::tau_with_dcc(dcc)` — year fraction from dates172173### Process pipeline (stochastic)174If the module defines a stochastic process, verify:175- `sample()` returns the correct `Output` type176- `sample_par(m)` works (all fields must be `Send + Sync`)177- Noise inputs follow the `SeedExt` pattern if seeded178179### Distribution pipeline (distributions)180If the module defines a distribution, verify:181- `DistributionSampler<T>` is implemented for bulk sampling182- `fill_slice()` uses SIMD where possible183- `sample_matrix()` works for multi-core benchmarks184185## 8. Feature gating186187If the module requires an optional external dependency:1881891. Add dependency with `optional = true` in `Cargo.toml`1902. Add feature: `my_feature = ["dep:my_crate"]`1913. Gate module: `#[cfg(feature = "my_feature")] pub mod my_module;`1924. Gate imports in shared code: `#[cfg(feature = "my_feature")]`193194Default features remain `default = []`.195196## 9. Testing and benchmarks197198Every new module must include:1992001. **Comparison test** (`tests/my_module_test.rs`):201 - Validate output against reference (Python, R, MATLAB, or paper's tables/figures)202 - Test trait integrations (e.g., custom `CalendarExt` impl, `sample_par` correctness)203 - Test edge cases (zero maturity, degenerate parameters, boundary conditions)2042052. **Criterion benchmark** (`benches/my_module.rs`):206 - Benchmark the hot path207 - Register in `Cargo.toml`: `[[bench]] name = "my_module" harness = false`2082093. **Integration test** — verify end-to-end with existing pipelines where applicable210211## 10. Documentation212213Every new file must have:214- `//!` doc header citing the paper/reference (title, authors, DOI or arXiv ID)215- LaTeX formula in the doc header216- `///` docs on all public items217218## Quick checklist219220Before marking a new module as done:221222- [ ] Placed in the correct top-level module (`stochastic/`, `quant/`, `stats/`, `distributions/`, `copulas/`)223- [ ] Module root has LaTeX doc header and re-exports224- [ ] Registered in the parent module's `.rs` file (alphabetical order)225- [ ] All numerical code generic over `FloatExt`, arrays use `ndarray`226- [ ] Correct domain traits implemented (see §2 trait integration map)227- [ ] Extensibility points use traits, not concrete types (see §3)228- [ ] `Debug`, `Clone`, `Display`, `Default` derives on public types229- [ ] `Send + Sync` verified (no `Rc`, `Cell`, or unshared interior mutability)230- [ ] No hardcoded `/365.0`, `/360.0`, or `/252.0`231- [ ] Comparison test against reference implementation232- [ ] Criterion benchmark registered in `Cargo.toml`233- [ ] Scientific reference cited in file header234- [ ] `cargo clippy` clean235236---237> Source: [rust-dd/stochastic-rs](https://github.com/rust-dd/stochastic-rs) — distributed by [TomeVault](https://tomevault.io).238<!-- tomevault:4.0:skill_md:2026-05-23 -->
Run npx skillmds@latest add tomevault-io/new-module-2 in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Enforces scalability, integration, and compatibility requirements when creating any new module in stochastic-rs — covers stochastic, quant, stats, distributions, copulas, and ai Use when this capability is needed. It is listed under Integrations & APIs on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
tomevault-io (@tomevault-io) published this skill. Their other Agent Skills are listed on their SkillMD profile.