neural-sde 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. neural_sde-0.6.0/LICENSE +21 -0
  2. neural_sde-0.6.0/PKG-INFO +149 -0
  3. neural_sde-0.6.0/README.md +119 -0
  4. neural_sde-0.6.0/__init__.py +69 -0
  5. neural_sde-0.6.0/api.py +350 -0
  6. neural_sde-0.6.0/claude_advisor_streaming.py +276 -0
  7. neural_sde-0.6.0/demo_forecast.py +101 -0
  8. neural_sde-0.6.0/forecast.png +0 -0
  9. neural_sde-0.6.0/forecast_example.png +0 -0
  10. neural_sde-0.6.0/forecasting.py +390 -0
  11. neural_sde-0.6.0/highlevel.py +404 -0
  12. neural_sde-0.6.0/likelihood.py +311 -0
  13. neural_sde-0.6.0/multi_asset.py +1125 -0
  14. neural_sde-0.6.0/neural_networks.py +303 -0
  15. neural_sde-0.6.0/neural_sde.egg-info/PKG-INFO +149 -0
  16. neural_sde-0.6.0/neural_sde.egg-info/SOURCES.txt +66 -0
  17. neural_sde-0.6.0/neural_sde.egg-info/dependency_links.txt +1 -0
  18. neural_sde-0.6.0/neural_sde.egg-info/requires.txt +15 -0
  19. neural_sde-0.6.0/neural_sde.egg-info/top_level.txt +1 -0
  20. neural_sde-0.6.0/ou_convergence_check.py +47 -0
  21. neural_sde-0.6.0/protocols.py +116 -0
  22. neural_sde-0.6.0/pyproject.toml +45 -0
  23. neural_sde-0.6.0/sde_core.py +349 -0
  24. neural_sde-0.6.0/setup.cfg +4 -0
  25. neural_sde-0.6.0/solvers.py +375 -0
  26. neural_sde-0.6.0/test_adjoint_debug.py +58 -0
  27. neural_sde-0.6.0/test_adjoint_fix.py +134 -0
  28. neural_sde-0.6.0/test_adjoint_grad.py +32 -0
  29. neural_sde-0.6.0/test_adjoint_verify.py +85 -0
  30. neural_sde-0.6.0/test_api_integration_v05.py +482 -0
  31. neural_sde-0.6.0/test_convergence_rate.py +771 -0
  32. neural_sde-0.6.0/test_edge_case_regression.py +420 -0
  33. neural_sde-0.6.0/test_hybrid_sweep.py +113 -0
  34. neural_sde-0.6.0/test_torch_solvers.py +442 -0
  35. neural_sde-0.6.0/test_trainer_losses.py +98 -0
  36. neural_sde-0.6.0/test_unified_entry.py +176 -0
  37. neural_sde-0.6.0/torch_solvers.py +896 -0
  38. neural_sde-0.6.0/trainer.py +495 -0
  39. neural_sde-0.6.0/wsl_test_runner.py +156 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Downie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: neural-sde
3
+ Version: 0.6.0
4
+ Summary: Probabilistic price forecasting via stochastic differential equations (GBM/OU/neural), with AIC model selection, Monte Carlo quantiles, and fan charts.
5
+ Author: Kevin Downie
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/kdownie/neural-sde
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Office/Business :: Financial :: Investment
14
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy<3,>=1.24
19
+ Requires-Dist: scipy<2,>=1.10
20
+ Requires-Dist: matplotlib<4,>=3.7
21
+ Provides-Extra: torch
22
+ Requires-Dist: torch<3,>=2.0; extra == "torch"
23
+ Provides-Extra: pandas
24
+ Requires-Dist: pandas<4,>=2.0; extra == "pandas"
25
+ Provides-Extra: demo
26
+ Requires-Dist: yfinance<2,>=1.0; extra == "demo"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # neural-sde
32
+
33
+ Probabilistic price forecasting via stochastic differential equations. Fit a
34
+ GBM or OU (mean-reverting) model to a price series, generate Monte Carlo
35
+ forecasts with quantified uncertainty, and answer questions like "what's the
36
+ probability this is up 10% in 30 days?" — without pretending to know the
37
+ future.
38
+
39
+ > **This library produces probabilistic forecasts, not point predictions.**
40
+ > `forecast()` returns a distribution over future paths, not a single
41
+ > "the price will be X" answer. Treat every number it gives you — quantiles,
42
+ > `prob_above()`, the fan chart — as a statement about *uncertainty*, not
43
+ > a promise. Financial markets are not stationary; a model fit on last
44
+ > year's regime can be a poor guide to next month's.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install -e . # core: numpy, scipy, matplotlib
50
+ pip install -e ".[torch,pandas]" # + neural SDE path and pandas Series input
51
+ pip install -e ".[demo]" # + yfinance, to run demo_forecast.py on real data
52
+ ```
53
+
54
+ Requires Python 3.9+. See [requirements.txt](requirements.txt) /
55
+ [pyproject.toml](pyproject.toml) for pinned dependency ranges.
56
+
57
+ ## Quickstart
58
+
59
+ ```python
60
+ from neural_sde.highlevel import fit, forecast
61
+
62
+ model = fit(prices) # auto: AIC picks GBM vs OU
63
+ fc = forecast(model, horizon=30) # antithetic Monte Carlo
64
+ print(fc.prob_above(prices[-1] * 1.10)) # P(+10% by day 30)
65
+ print(fc.quantiles([0.05, 0.5, 0.95])) # 5th/50th/95th percentile price
66
+ fc.plot("forecast.png") # fan chart: history -> forecast cone
67
+ ```
68
+
69
+ `prices` is any 1-D array-like or pandas Series of price levels (not
70
+ returns). `fit(model="neural")` routes to a torch-based `NeuralSDETrainer`
71
+ when torch is installed — this path is **experimental**; the GBM/OU
72
+ parametric paths use exact (unbiased) transition densities and are the
73
+ production-quality default.
74
+
75
+ ### On regimes
76
+
77
+ `fit()` estimates parameters from whatever window of history you give it. A
78
+ GBM fit on a 6-month bull run will forecast that drift forward; an OU fit on
79
+ a period of active mean-reversion will forecast reversion. Neither model
80
+ knows the regime changed the day after your training window ends. Re-fit
81
+ periodically, and sanity-check `model.summary()` (drift/vol/theta) against
82
+ what you'd expect for the asset before trusting the forecast.
83
+
84
+ ## What's inside
85
+
86
+ | Module | Purpose |
87
+ |---|---|
88
+ | [`highlevel.py`](highlevel.py) | Public API: `fit`/`forecast`/`FittedModel`/`Forecast` — start here |
89
+ | [`sde_core.py`](sde_core.py) | Core SDE theory: drift/diffusion, Ito<->Stratonovich conversion |
90
+ | [`solvers.py`](solvers.py) / [`torch_solvers.py`](torch_solvers.py) | Euler-Maruyama, Milstein, Heun solvers (numpy and torch backends) |
91
+ | [`multi_asset.py`](multi_asset.py) | Correlated multi-asset GBM/OU/CIR diffusion |
92
+ | [`neural_networks.py`](neural_networks.py) / [`trainer.py`](trainer.py) | Neural drift/diffusion networks and training loop (experimental path, requires torch) |
93
+ | [`likelihood.py`](likelihood.py) | Score-matching / contrastive-divergence loss functions |
94
+ | [`forecasting.py`](forecasting.py) | Path forecasting and option pricing utilities |
95
+ | [`api.py`](api.py) | Lower-level unified solver entry point |
96
+
97
+ ## Demo
98
+
99
+ ```bash
100
+ pip install -e ".[demo]"
101
+ python demo_forecast.py
102
+ ```
103
+
104
+ With `yfinance` installed and network access, edit the top of the script to
105
+ pull real data:
106
+
107
+ ```python
108
+ import yfinance as yf
109
+ from neural_sde.highlevel import fit, forecast
110
+
111
+ prices = yf.download("AAPL", period="2y")["Close"]
112
+ model = fit(prices)
113
+ fc = forecast(model, horizon=30)
114
+ print(fc.summary())
115
+ fc.plot("forecast.png")
116
+ ```
117
+
118
+ Offline, the script instead demos against **synthetic data with known
119
+ dynamics**, which doubles as a calibration test — it simulates GBM and OU
120
+ paths with known parameters, fits them back, and checks:
121
+
122
+ 1. `fit()` recovers the true GBM parameters and AIC selects GBM.
123
+ 2. `fit()` recovers the true OU parameters and AIC selects OU.
124
+ 3. Monte Carlo quantiles agree with the exact lognormal distribution to <1%.
125
+ 4. The `exact` and `euler` (core-library) engines agree on the median to <3%.
126
+
127
+ `forecast.png` and `forecast_example.png` in this directory are pre-generated
128
+ sample outputs from that script — regenerate them yourself with
129
+ `python demo_forecast.py`.
130
+
131
+ ## Testing
132
+
133
+ ```bash
134
+ pip install -e ".[dev]"
135
+ pytest test_convergence_rate.py test_adjoint_grad.py test_adjoint_verify.py \
136
+ test_trainer_losses.py test_torch_solvers.py test_unified_entry.py \
137
+ test_api_integration_v05.py test_edge_case_regression.py
138
+ ```
139
+
140
+ `archive/` holds superseded tests kept for historical reference (see
141
+ [archive/README.md](archive/README.md)); they aren't part of the suite.
142
+
143
+ ## License
144
+
145
+ [MIT](LICENSE).
146
+
147
+ ## Credit
148
+
149
+ Built by Kevin Downie in collaboration with Claude (Anthropic).
@@ -0,0 +1,119 @@
1
+ # neural-sde
2
+
3
+ Probabilistic price forecasting via stochastic differential equations. Fit a
4
+ GBM or OU (mean-reverting) model to a price series, generate Monte Carlo
5
+ forecasts with quantified uncertainty, and answer questions like "what's the
6
+ probability this is up 10% in 30 days?" — without pretending to know the
7
+ future.
8
+
9
+ > **This library produces probabilistic forecasts, not point predictions.**
10
+ > `forecast()` returns a distribution over future paths, not a single
11
+ > "the price will be X" answer. Treat every number it gives you — quantiles,
12
+ > `prob_above()`, the fan chart — as a statement about *uncertainty*, not
13
+ > a promise. Financial markets are not stationary; a model fit on last
14
+ > year's regime can be a poor guide to next month's.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install -e . # core: numpy, scipy, matplotlib
20
+ pip install -e ".[torch,pandas]" # + neural SDE path and pandas Series input
21
+ pip install -e ".[demo]" # + yfinance, to run demo_forecast.py on real data
22
+ ```
23
+
24
+ Requires Python 3.9+. See [requirements.txt](requirements.txt) /
25
+ [pyproject.toml](pyproject.toml) for pinned dependency ranges.
26
+
27
+ ## Quickstart
28
+
29
+ ```python
30
+ from neural_sde.highlevel import fit, forecast
31
+
32
+ model = fit(prices) # auto: AIC picks GBM vs OU
33
+ fc = forecast(model, horizon=30) # antithetic Monte Carlo
34
+ print(fc.prob_above(prices[-1] * 1.10)) # P(+10% by day 30)
35
+ print(fc.quantiles([0.05, 0.5, 0.95])) # 5th/50th/95th percentile price
36
+ fc.plot("forecast.png") # fan chart: history -> forecast cone
37
+ ```
38
+
39
+ `prices` is any 1-D array-like or pandas Series of price levels (not
40
+ returns). `fit(model="neural")` routes to a torch-based `NeuralSDETrainer`
41
+ when torch is installed — this path is **experimental**; the GBM/OU
42
+ parametric paths use exact (unbiased) transition densities and are the
43
+ production-quality default.
44
+
45
+ ### On regimes
46
+
47
+ `fit()` estimates parameters from whatever window of history you give it. A
48
+ GBM fit on a 6-month bull run will forecast that drift forward; an OU fit on
49
+ a period of active mean-reversion will forecast reversion. Neither model
50
+ knows the regime changed the day after your training window ends. Re-fit
51
+ periodically, and sanity-check `model.summary()` (drift/vol/theta) against
52
+ what you'd expect for the asset before trusting the forecast.
53
+
54
+ ## What's inside
55
+
56
+ | Module | Purpose |
57
+ |---|---|
58
+ | [`highlevel.py`](highlevel.py) | Public API: `fit`/`forecast`/`FittedModel`/`Forecast` — start here |
59
+ | [`sde_core.py`](sde_core.py) | Core SDE theory: drift/diffusion, Ito<->Stratonovich conversion |
60
+ | [`solvers.py`](solvers.py) / [`torch_solvers.py`](torch_solvers.py) | Euler-Maruyama, Milstein, Heun solvers (numpy and torch backends) |
61
+ | [`multi_asset.py`](multi_asset.py) | Correlated multi-asset GBM/OU/CIR diffusion |
62
+ | [`neural_networks.py`](neural_networks.py) / [`trainer.py`](trainer.py) | Neural drift/diffusion networks and training loop (experimental path, requires torch) |
63
+ | [`likelihood.py`](likelihood.py) | Score-matching / contrastive-divergence loss functions |
64
+ | [`forecasting.py`](forecasting.py) | Path forecasting and option pricing utilities |
65
+ | [`api.py`](api.py) | Lower-level unified solver entry point |
66
+
67
+ ## Demo
68
+
69
+ ```bash
70
+ pip install -e ".[demo]"
71
+ python demo_forecast.py
72
+ ```
73
+
74
+ With `yfinance` installed and network access, edit the top of the script to
75
+ pull real data:
76
+
77
+ ```python
78
+ import yfinance as yf
79
+ from neural_sde.highlevel import fit, forecast
80
+
81
+ prices = yf.download("AAPL", period="2y")["Close"]
82
+ model = fit(prices)
83
+ fc = forecast(model, horizon=30)
84
+ print(fc.summary())
85
+ fc.plot("forecast.png")
86
+ ```
87
+
88
+ Offline, the script instead demos against **synthetic data with known
89
+ dynamics**, which doubles as a calibration test — it simulates GBM and OU
90
+ paths with known parameters, fits them back, and checks:
91
+
92
+ 1. `fit()` recovers the true GBM parameters and AIC selects GBM.
93
+ 2. `fit()` recovers the true OU parameters and AIC selects OU.
94
+ 3. Monte Carlo quantiles agree with the exact lognormal distribution to <1%.
95
+ 4. The `exact` and `euler` (core-library) engines agree on the median to <3%.
96
+
97
+ `forecast.png` and `forecast_example.png` in this directory are pre-generated
98
+ sample outputs from that script — regenerate them yourself with
99
+ `python demo_forecast.py`.
100
+
101
+ ## Testing
102
+
103
+ ```bash
104
+ pip install -e ".[dev]"
105
+ pytest test_convergence_rate.py test_adjoint_grad.py test_adjoint_verify.py \
106
+ test_trainer_losses.py test_torch_solvers.py test_unified_entry.py \
107
+ test_api_integration_v05.py test_edge_case_regression.py
108
+ ```
109
+
110
+ `archive/` holds superseded tests kept for historical reference (see
111
+ [archive/README.md](archive/README.md)); they aren't part of the suite.
112
+
113
+ ## License
114
+
115
+ [MIT](LICENSE).
116
+
117
+ ## Credit
118
+
119
+ Built by Kevin Downie in collaboration with Claude (Anthropic).
@@ -0,0 +1,69 @@
1
+ """Neural SDE Module — Stochastic Differential Equations for Financial Modeling
2
+
3
+ Integrates machine learning with advanced stochastic calculus to create
4
+ more accurate predictive models for time-series and pricing.
5
+
6
+ Components:
7
+ - sde_core.py: Core SDE theory (drift, diffusion, Ito/Stratonovich) + TimeFeatureExtractor
8
+ - neural_networks.py: MLP architectures for drift/diffusion parameterization
9
+ - likelihood.py: Score matching / contrastive divergence likelihood estimation
10
+ - solvers.py: Euler-Maruyama, Milstein solvers with unified BaseSolver protocol
11
+ - trainer.py: Training loop with validation, early stopping, gradient monitoring
12
+ - forecasting.py: Time-series forecasting + antithetic variates for MC variance reduction
13
+
14
+ Usage:
15
+ from neural_sde import NeuralSDETrainer
16
+
17
+ # Create and train model
18
+ trainer = NeuralSDETrainer(
19
+ state_dim=1, # Single asset price
20
+ hidden_dims=[64, 64],
21
+ learning_rate=1e-3,
22
+ time_mode='calendar' # Use calendar time encoding for financial data
23
+ )
24
+
25
+ # Train on historical data
26
+ trainer.fit(price_data, dt=0.01)
27
+
28
+ # Forecast future paths with uncertainty bands
29
+ forecasts = trainer.forecast(initial_state, n_steps=100)
30
+ """
31
+
32
+ from neural_sde.sde_core import SDECore, ItoSDE, StratonovichSDE, BaseSolver, TimeFeatureExtractor, TimeFeatureNormalizer
33
+ from neural_sde.neural_networks import DriftNetwork, DiffusionNetwork, NeuralSDEArchitecture
34
+ from neural_sde.likelihood import ScoreMatchingLoss, ContrastiveDivergenceLoss
35
+ from neural_sde.solvers import EulerMaruyamaSolver, MilsteinSolver, HeunSolver
36
+ from neural_sde.torch_solvers import (
37
+ TorchEulerMaruyamaSolver,
38
+ TorchMilsteinSolver,
39
+ TorchHeunSolver,
40
+ TorchSDEAdjoint,
41
+ simulate_torch_sde,
42
+ compare_torch_solvers,
43
+ compute_torch_convergence_rate
44
+ )
45
+ from neural_sde.api import (
46
+ simulate_sde,
47
+ train_sde,
48
+ TrainResult,
49
+ _detect_backend,
50
+ _validate_inputs
51
+ )
52
+ from neural_sde.trainer import NeuralSDETrainer
53
+ from neural_sde.highlevel import fit, forecast, FittedModel, Forecast
54
+
55
+ __version__ = "0.6.0"
56
+ __all__ = [
57
+ 'fit', 'forecast', 'FittedModel', 'Forecast',
58
+ 'SDECore', 'ItoSDE', 'StratonovichSDE', 'BaseSolver',
59
+ 'TimeFeatureExtractor', 'TimeFeatureNormalizer',
60
+ 'DriftNetwork', 'DiffusionNetwork', 'NeuralSDEArchitecture',
61
+ 'ScoreMatchingLoss', 'ContrastiveDivergenceLoss',
62
+ 'EulerMaruyamaSolver', 'MilsteinSolver', 'HeunSolver',
63
+ 'TorchEulerMaruyamaSolver', 'TorchMilsteinSolver', 'TorchHeunSolver',
64
+ 'TorchSDEAdjoint',
65
+ 'simulate_torch_sde', 'compare_torch_solvers', 'compute_torch_convergence_rate',
66
+ 'simulate_sde', 'train_sde', 'TrainResult',
67
+ '_detect_backend', '_validate_inputs',
68
+ 'NeuralSDETrainer'
69
+ ]