stokestrel 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024
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,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: stokestrel
3
+ Version: 0.1.0
4
+ Summary: A modern stochastic modelling library for parameter estimation and Monte Carlo simulation.
5
+ Author-email: April Kidd <bk0851@outlook.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/april-webm/kestrel
8
+ Project-URL: Documentation, https://github.com/april-webm/kestrel#readme
9
+ Project-URL: Repository, https://github.com/april-webm/kestrel
10
+ Project-URL: Issues, https://github.com/april-webm/kestrel/issues
11
+ Project-URL: Changelog, https://github.com/april-webm/kestrel/releases
12
+ Keywords: stochastic,sde,monte-carlo,simulation,ornstein-uhlenbeck,brownian-motion,quantitative-finance,time-series
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Scientific/Engineering
25
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
26
+ Classifier: Topic :: Office/Business :: Financial
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.9
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: numpy>=1.20
32
+ Requires-Dist: scipy>=1.7
33
+ Requires-Dist: pandas>=1.3
34
+ Requires-Dist: matplotlib>=3.4
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=7.0; extra == "dev"
37
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # Kestrel
41
+
42
+ <!-- TODO: Add kestrel image -->
43
+ <p align="center">
44
+ <img src="assets/kestrel.png" alt="Kestrel" width="200">
45
+ </p>
46
+
47
+ [![PyPI version](https://img.shields.io/pypi/v/stokestrel.svg)](https://pypi.org/project/stokestrel/)
48
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
49
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
50
+
51
+ A modern Python library for stochastic process modelling, parameter estimation, and Monte Carlo simulation.
52
+
53
+ ## Overview
54
+
55
+ Kestrel provides a unified, scikit-learn-style interface for working with stochastic differential equations (SDEs). The library supports parameter estimation from time-series data and path simulation for a variety of continuous and jump-diffusion processes.
56
+
57
+ ### Supported Processes
58
+
59
+ | Process | Module | Description |
60
+ |---------|--------|-------------|
61
+ | Brownian Motion | `kestrel.diffusion` | Standard Wiener process with drift |
62
+ | Geometric Brownian Motion | `kestrel.diffusion` | Log-normal price dynamics (Black-Scholes) |
63
+ | Ornstein-Uhlenbeck | `kestrel.diffusion` | Mean-reverting Gaussian process |
64
+ | Cox-Ingersoll-Ross | `kestrel.diffusion` | Mean-reverting process with state-dependent volatility |
65
+ | Merton Jump Diffusion | `kestrel.jump_diffusion` | GBM with Poisson-distributed jumps |
66
+
67
+ ### Key Features
68
+
69
+ - **Consistent API**: All processes follow `fit()` / `sample()` pattern
70
+ - **Multiple Estimation Methods**: MLE, AR(1) regression, least squares
71
+ - **Standard Error Reporting**: Parameter uncertainty quantification
72
+ - **Flexible Time Handling**: Automatic dt inference from DatetimeIndex
73
+ - **Simulation Engine**: Euler-Maruyama discretisation with exact solutions where available
74
+
75
+ ## Installation
76
+
77
+ **Requirements**: Python 3.9+
78
+
79
+ ```bash
80
+ pip install stokestrel
81
+ ```
82
+
83
+ For development installation:
84
+
85
+ ```bash
86
+ git clone https://github.com/april-webm/kestrel.git
87
+ cd kestrel
88
+ pip install -e ".[dev]"
89
+ ```
90
+
91
+ ## Quick Start
92
+
93
+ ```python
94
+ from kestrel import OUProcess
95
+ import pandas as pd
96
+
97
+ # Load or generate time-series data
98
+ data = pd.Series([...]) # Your observed data
99
+
100
+ # Fit model parameters
101
+ model = OUProcess()
102
+ model.fit(data, dt=1/252, method='mle')
103
+
104
+ # View estimated parameters and standard errors
105
+ print(f"Mean reversion speed: {model.theta_:.4f} ± {model.theta_se_:.4f}")
106
+ print(f"Long-run mean: {model.mu_:.4f} ± {model.mu_se_:.4f}")
107
+ print(f"Volatility: {model.sigma_:.4f} ± {model.sigma_se_:.4f}")
108
+
109
+ # Simulate future paths
110
+ paths = model.sample(n_paths=1000, horizon=252)
111
+ paths.plot(title="OU Process Simulation")
112
+ ```
113
+
114
+ ## Usage Examples
115
+
116
+ ### Ornstein-Uhlenbeck Process
117
+
118
+ Mean-reverting process commonly used for interest rates and volatility modelling.
119
+
120
+ ```python
121
+ from kestrel import OUProcess
122
+
123
+ model = OUProcess()
124
+ model.fit(data, dt=1/252, method='mle') # or method='ar1'
125
+
126
+ # Simulate from fitted model
127
+ simulation = model.sample(n_paths=100, horizon=50)
128
+ ```
129
+
130
+ ### Geometric Brownian Motion
131
+
132
+ Standard model for equity prices.
133
+
134
+ ```python
135
+ from kestrel import GeometricBrownianMotion
136
+
137
+ model = GeometricBrownianMotion()
138
+ model.fit(price_data, dt=1/252)
139
+
140
+ # Expected price and variance at horizon
141
+ expected = model.expected_price(t=1.0, s0=100)
142
+ variance = model.variance_price(t=1.0, s0=100)
143
+ ```
144
+
145
+ ### Cox-Ingersoll-Ross Process
146
+
147
+ Ensures non-negativity; suitable for interest rate modelling.
148
+
149
+ ```python
150
+ from kestrel import CIRProcess
151
+
152
+ model = CIRProcess()
153
+ model.fit(rate_data, dt=1/252, method='mle')
154
+
155
+ # Check Feller condition for strict positivity
156
+ if model.feller_condition_satisfied():
157
+ print("Process guaranteed to remain positive")
158
+ ```
159
+
160
+ ### Merton Jump Diffusion
161
+
162
+ Captures sudden market movements via Poisson jumps.
163
+
164
+ ```python
165
+ from kestrel import MertonProcess
166
+
167
+ model = MertonProcess()
168
+ model.fit(log_returns, dt=1/252)
169
+
170
+ # Jump-adjusted expected return
171
+ total_drift = model.expected_return()
172
+ total_var = model.total_variance()
173
+ ```
174
+
175
+ ## API Reference
176
+
177
+ ### Base Interface
178
+
179
+ All stochastic processes inherit from `StochasticProcess` and implement:
180
+
181
+ | Method | Description |
182
+ |--------|-------------|
183
+ | `fit(data, dt, method)` | Estimate parameters from time-series |
184
+ | `sample(n_paths, horizon, dt)` | Generate Monte Carlo paths |
185
+ | `is_fitted` | Property indicating fit status |
186
+ | `params` | Dictionary of estimated parameters |
187
+
188
+ ### Fitted Attributes
189
+
190
+ After calling `fit()`, estimated parameters are available as attributes with trailing underscore:
191
+
192
+ ```python
193
+ model.theta_ # Estimated parameter value
194
+ model.theta_se_ # Standard error of estimate
195
+ ```
196
+
197
+ ## Dependencies
198
+
199
+ - numpy
200
+ - scipy
201
+ - pandas
202
+ - matplotlib
203
+
204
+ ## Testing
205
+
206
+ ```bash
207
+ pytest tests/ -v
208
+ ```
209
+
210
+ ## Contributing
211
+
212
+ Contributions are welcome. Please ensure:
213
+
214
+ 1. Code follows existing style conventions
215
+ 2. New features include appropriate tests
216
+ 3. Documentation is updated accordingly
217
+
218
+ ## License
219
+
220
+ Released under the MIT License. See [LICENSE](LICENSE) for details.
221
+
222
+ ## Citation
223
+
224
+ If Kestrel is used in academic research, citation is appreciated:
225
+
226
+ ```bibtex
227
+ @software{stokestrel,
228
+ title = {Stokestrel: A Modern Stochastic Modelling Library},
229
+ author = {Kidd, April},
230
+ url = {https://github.com/april-webm/kestrel},
231
+ version = {0.1.0},
232
+ year = {2024}
233
+ }
234
+ ```
@@ -0,0 +1,195 @@
1
+ # Kestrel
2
+
3
+ <!-- TODO: Add kestrel image -->
4
+ <p align="center">
5
+ <img src="assets/kestrel.png" alt="Kestrel" width="200">
6
+ </p>
7
+
8
+ [![PyPI version](https://img.shields.io/pypi/v/stokestrel.svg)](https://pypi.org/project/stokestrel/)
9
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
11
+
12
+ A modern Python library for stochastic process modelling, parameter estimation, and Monte Carlo simulation.
13
+
14
+ ## Overview
15
+
16
+ Kestrel provides a unified, scikit-learn-style interface for working with stochastic differential equations (SDEs). The library supports parameter estimation from time-series data and path simulation for a variety of continuous and jump-diffusion processes.
17
+
18
+ ### Supported Processes
19
+
20
+ | Process | Module | Description |
21
+ |---------|--------|-------------|
22
+ | Brownian Motion | `kestrel.diffusion` | Standard Wiener process with drift |
23
+ | Geometric Brownian Motion | `kestrel.diffusion` | Log-normal price dynamics (Black-Scholes) |
24
+ | Ornstein-Uhlenbeck | `kestrel.diffusion` | Mean-reverting Gaussian process |
25
+ | Cox-Ingersoll-Ross | `kestrel.diffusion` | Mean-reverting process with state-dependent volatility |
26
+ | Merton Jump Diffusion | `kestrel.jump_diffusion` | GBM with Poisson-distributed jumps |
27
+
28
+ ### Key Features
29
+
30
+ - **Consistent API**: All processes follow `fit()` / `sample()` pattern
31
+ - **Multiple Estimation Methods**: MLE, AR(1) regression, least squares
32
+ - **Standard Error Reporting**: Parameter uncertainty quantification
33
+ - **Flexible Time Handling**: Automatic dt inference from DatetimeIndex
34
+ - **Simulation Engine**: Euler-Maruyama discretisation with exact solutions where available
35
+
36
+ ## Installation
37
+
38
+ **Requirements**: Python 3.9+
39
+
40
+ ```bash
41
+ pip install stokestrel
42
+ ```
43
+
44
+ For development installation:
45
+
46
+ ```bash
47
+ git clone https://github.com/april-webm/kestrel.git
48
+ cd kestrel
49
+ pip install -e ".[dev]"
50
+ ```
51
+
52
+ ## Quick Start
53
+
54
+ ```python
55
+ from kestrel import OUProcess
56
+ import pandas as pd
57
+
58
+ # Load or generate time-series data
59
+ data = pd.Series([...]) # Your observed data
60
+
61
+ # Fit model parameters
62
+ model = OUProcess()
63
+ model.fit(data, dt=1/252, method='mle')
64
+
65
+ # View estimated parameters and standard errors
66
+ print(f"Mean reversion speed: {model.theta_:.4f} ± {model.theta_se_:.4f}")
67
+ print(f"Long-run mean: {model.mu_:.4f} ± {model.mu_se_:.4f}")
68
+ print(f"Volatility: {model.sigma_:.4f} ± {model.sigma_se_:.4f}")
69
+
70
+ # Simulate future paths
71
+ paths = model.sample(n_paths=1000, horizon=252)
72
+ paths.plot(title="OU Process Simulation")
73
+ ```
74
+
75
+ ## Usage Examples
76
+
77
+ ### Ornstein-Uhlenbeck Process
78
+
79
+ Mean-reverting process commonly used for interest rates and volatility modelling.
80
+
81
+ ```python
82
+ from kestrel import OUProcess
83
+
84
+ model = OUProcess()
85
+ model.fit(data, dt=1/252, method='mle') # or method='ar1'
86
+
87
+ # Simulate from fitted model
88
+ simulation = model.sample(n_paths=100, horizon=50)
89
+ ```
90
+
91
+ ### Geometric Brownian Motion
92
+
93
+ Standard model for equity prices.
94
+
95
+ ```python
96
+ from kestrel import GeometricBrownianMotion
97
+
98
+ model = GeometricBrownianMotion()
99
+ model.fit(price_data, dt=1/252)
100
+
101
+ # Expected price and variance at horizon
102
+ expected = model.expected_price(t=1.0, s0=100)
103
+ variance = model.variance_price(t=1.0, s0=100)
104
+ ```
105
+
106
+ ### Cox-Ingersoll-Ross Process
107
+
108
+ Ensures non-negativity; suitable for interest rate modelling.
109
+
110
+ ```python
111
+ from kestrel import CIRProcess
112
+
113
+ model = CIRProcess()
114
+ model.fit(rate_data, dt=1/252, method='mle')
115
+
116
+ # Check Feller condition for strict positivity
117
+ if model.feller_condition_satisfied():
118
+ print("Process guaranteed to remain positive")
119
+ ```
120
+
121
+ ### Merton Jump Diffusion
122
+
123
+ Captures sudden market movements via Poisson jumps.
124
+
125
+ ```python
126
+ from kestrel import MertonProcess
127
+
128
+ model = MertonProcess()
129
+ model.fit(log_returns, dt=1/252)
130
+
131
+ # Jump-adjusted expected return
132
+ total_drift = model.expected_return()
133
+ total_var = model.total_variance()
134
+ ```
135
+
136
+ ## API Reference
137
+
138
+ ### Base Interface
139
+
140
+ All stochastic processes inherit from `StochasticProcess` and implement:
141
+
142
+ | Method | Description |
143
+ |--------|-------------|
144
+ | `fit(data, dt, method)` | Estimate parameters from time-series |
145
+ | `sample(n_paths, horizon, dt)` | Generate Monte Carlo paths |
146
+ | `is_fitted` | Property indicating fit status |
147
+ | `params` | Dictionary of estimated parameters |
148
+
149
+ ### Fitted Attributes
150
+
151
+ After calling `fit()`, estimated parameters are available as attributes with trailing underscore:
152
+
153
+ ```python
154
+ model.theta_ # Estimated parameter value
155
+ model.theta_se_ # Standard error of estimate
156
+ ```
157
+
158
+ ## Dependencies
159
+
160
+ - numpy
161
+ - scipy
162
+ - pandas
163
+ - matplotlib
164
+
165
+ ## Testing
166
+
167
+ ```bash
168
+ pytest tests/ -v
169
+ ```
170
+
171
+ ## Contributing
172
+
173
+ Contributions are welcome. Please ensure:
174
+
175
+ 1. Code follows existing style conventions
176
+ 2. New features include appropriate tests
177
+ 3. Documentation is updated accordingly
178
+
179
+ ## License
180
+
181
+ Released under the MIT License. See [LICENSE](LICENSE) for details.
182
+
183
+ ## Citation
184
+
185
+ If Kestrel is used in academic research, citation is appreciated:
186
+
187
+ ```bibtex
188
+ @software{stokestrel,
189
+ title = {Stokestrel: A Modern Stochastic Modelling Library},
190
+ author = {Kidd, April},
191
+ url = {https://github.com/april-webm/kestrel},
192
+ version = {0.1.0},
193
+ year = {2024}
194
+ }
195
+ ```
@@ -0,0 +1,32 @@
1
+ # kestrel/__init__.py
2
+ """
3
+ Kestrel: A Modern Stochastic Modelling Library.
4
+
5
+ Provides unified interface for fitting and simulating stochastic processes.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from kestrel.base import StochasticProcess
11
+ from kestrel.diffusion import (
12
+ BrownianMotion,
13
+ GeometricBrownianMotion,
14
+ OUProcess,
15
+ CIRProcess,
16
+ )
17
+ from kestrel.jump_diffusion import MertonProcess
18
+ from kestrel.utils import KestrelResult
19
+
20
+ __all__ = [
21
+ # Base
22
+ "StochasticProcess",
23
+ # Diffusion processes
24
+ "BrownianMotion",
25
+ "GeometricBrownianMotion",
26
+ "OUProcess",
27
+ "CIRProcess",
28
+ # Jump diffusion processes
29
+ "MertonProcess",
30
+ # Utilities
31
+ "KestrelResult",
32
+ ]
@@ -0,0 +1,77 @@
1
+ # kestrel/base.py
2
+ from abc import ABC, abstractmethod
3
+ import pandas as pd
4
+ import numpy as np
5
+ from kestrel.utils.kestrel_result import KestrelResult
6
+ from typing import Optional
7
+
8
+ class StochasticProcess(ABC):
9
+ """
10
+ Abstract Base Class for Kestrel's stochastic processes.
11
+ Defines common interface for parameter fitting and path simulation.
12
+ """
13
+
14
+ def __init__(self):
15
+ self._fitted = False
16
+ self._params = {} # Stores estimated parameters
17
+
18
+ @abstractmethod
19
+ def fit(self, data: pd.Series, dt: float = None):
20
+ """
21
+ Estimates process parameters from time-series data.
22
+
23
+ Args:
24
+ data (pd.Series): Time-series data for model fitting.
25
+ dt (float, optional): Time step between observations.
26
+ If None, inferred from data; defaults to 1.0.
27
+ """
28
+ pass
29
+
30
+ @abstractmethod
31
+ def sample(self, n_paths: int = 1, horizon: int = 1, dt: float = None) -> KestrelResult:
32
+ """
33
+ Simulates future process paths.
34
+
35
+ Args:
36
+ n_paths (int): Number of simulation paths to generate.
37
+ horizon (int): Number of future time steps to simulate.
38
+ dt (float, optional): Simulation time step.
39
+ If None, uses fitted dt; defaults to 1.0.
40
+
41
+ Returns:
42
+ pd.DataFrame: DataFrame where each column is a simulated path.
43
+ """
44
+ pass
45
+
46
+ def _set_params(self, last_data_point: float = None, dt: float = None, freq: str = None, param_ses: dict = None, **kwargs):
47
+ """
48
+ Sets estimated parameters, their standard errors, and marks model as fitted.
49
+ """
50
+ for k, v in kwargs.items():
51
+ setattr(self, f"{k}_", v) # Underscore denotes estimated parameters
52
+ self._params[k] = v
53
+ self._fitted = True
54
+ if last_data_point is not None:
55
+ self._last_data_point = last_data_point
56
+ if dt is not None:
57
+ self._dt_ = dt
58
+ if freq is not None:
59
+ self._freq_ = freq
60
+ if param_ses is not None:
61
+ for k, v in param_ses.items():
62
+ setattr(self, f"{k}_se_", v) # Store standard errors
63
+ self._params[f"{k}_se"] = v # Also add to params dictionary
64
+
65
+ @property
66
+ def is_fitted(self) -> bool:
67
+ """
68
+ Returns True if model fitted, False otherwise.
69
+ """
70
+ return self._fitted
71
+
72
+ @property
73
+ def params(self) -> dict:
74
+ """
75
+ Returns dictionary of estimated parameters.
76
+ """
77
+ return self._params
@@ -0,0 +1,12 @@
1
+ """Continuous diffusion processes."""
2
+
3
+ from kestrel.diffusion.brownian import BrownianMotion, GeometricBrownianMotion
4
+ from kestrel.diffusion.ou import OUProcess
5
+ from kestrel.diffusion.cir import CIRProcess
6
+
7
+ __all__ = [
8
+ "BrownianMotion",
9
+ "GeometricBrownianMotion",
10
+ "OUProcess",
11
+ "CIRProcess",
12
+ ]