API Reference

Models

Jump-Diffusion Model Definitions

This module contains the mathematical models for various types of jump-diffusion processes.

class jump_diffusion.models.JumpDiffusionModel(mu: float = 0.05, sigma: float = 0.2, jump_prob: float = 0.1, jump_distribution: JumpDistribution | None = None, **jump_params: float)[source]

Bases: BaseStochasticModel

Jump-diffusion model with a pluggable jump-size distribution.

The model follows the SDE: dX_t = μ dt + σ dW_t + J_t dN_t

Where J_t follows the distribution given by jump_distribution (skew-normal by default) and N_t is a Poisson process approximated by Bernoulli trials.

simulate(T: float, n_steps: int, x0: float = 1.0, seed: int | None = None) Tuple[ndarray, ndarray, ndarray][source]

Simulate a jump-diffusion path.

Returns:

tuple

(times, path, jumps) where jumps contains the jump component

log_likelihood(data: ndarray, dt: float) float[source]

Calculate log-likelihood of observed increments.

get_parameter_bounds() list[source]

Get parameter bounds for optimization.

class jump_diffusion.models.BaseStochasticModel(**kwargs)[source]

Bases: ABC

Abstract base class for all stochastic process models.

This class defines the common interface that all models must implement, ensuring consistency and extensibility across different model types.

abstractmethod simulate(T: float, n_steps: int, x0: float = 1.0, seed: int | None = None) tuple[source]

Simulate a path from the stochastic process.

Parameters:

Tfloat

Total time horizon

n_stepsint

Number of time steps

x0float

Initial value

seedint, optional

Random seed for reproducibility

Returns:

tuple

(times, path) or (times, path, additional_info)

abstractmethod log_likelihood(data: ndarray, dt: float) float[source]

Calculate the log-likelihood of observed data.

Parameters:

datanp.ndarray

Observed increments

dtfloat

Time step size

Returns:

float

Log-likelihood value

abstractmethod get_parameter_bounds() list[source]

Get parameter bounds for optimization.

Returns:

list

List of (lower, upper) tuples for each parameter

update_parameters(**kwargs)[source]

Update model parameters.

get_parameters() Dict[str, Any][source]

Get current model parameters.

Simulation

Simulation Tools for Jump-Diffusion Processes

This module provides tools for simulating various jump-diffusion processes with different jump distributions and arrival mechanisms.

class jump_diffusion.simulation.JumpDiffusionSimulator(mu: float = 0.05, sigma: float = 0.2, jump_prob: float = 0.1, jump_distribution: JumpDistribution | None = None, **jump_params: float)[source]

Bases: BaseSimulator, JumpDiffusionModel

Simulator for jump-diffusion processes with asymmetric jumps.

Inherits path generation from JumpDiffusionModel and adds state-tracking (for repeated plotting) and visualisation on top.

simulate_path(T: float = 1.0, n_steps: int = 252, x0: float = 1.0, seed: int | None = None) Tuple[ndarray, ndarray, ndarray][source]

Simulate a complete jump-diffusion path.

Parameters:

Tfloat

Total simulation time

n_stepsint

Number of time steps

x0float

Initial value

seedint, optional

Random seed for reproducibility

Returns:

tuple

(times, path, jumps)

plot_simulation(times=None, path=None, jumps=None, figsize=(12, 8), show_theoretical=True)[source]

Plot simulation results with comprehensive diagnostics.

Parameters:
  • times (array-like, optional) – Time grid for the plotted path. When None, the time points from the most recent call to simulate_path() (uniformly spaced between 0 and 1) are used.

  • path (array-like, optional) – Simulated trajectory to visualise. Defaults to the last simulated path stored by the simulator.

  • jumps (array-like, optional) – Jump magnitudes for each step. Required to display jump-related diagnostics. If None, the jump component from the last simulation is used.

  • figsize (tuple, optional) – Figure size passed to matplotlib.pyplot.subplots().

  • show_theoretical (bool, optional) – When True (default) and at least one jump was realized, overlay the jump distribution’s theoretical pdf (evaluated at self.jump_distribution / self._jump_params()) on top of the empirical jump-size histogram, so the plot doubles as a visual check that simulated jumps match the selected distribution’s shape.

Returns:

The created figure, e.g. for further customization or testing.

Return type:

matplotlib.figure.Figure

Notes

The method creates a 2×2 grid of plots showing the trajectory with jump markers, a stem plot of jump magnitudes, the distribution of increments, and the distribution of jump sizes. If no arrays are provided and a simulation has been run previously, these plots display the stored results. Supplying times, path and jumps overrides the stored data and visualises the provided arrays instead.

class jump_diffusion.simulation.BaseSimulator(**kwargs)[source]

Bases: ABC

Abstract base class for all simulators.

abstractmethod simulate_path(T: float, n_steps: int, x0: float = 1.0, seed: int | None = None) Tuple[ndarray, ...][source]

Simulate a single path.

Parameters:

Tfloat

Time horizon

n_stepsint

Number of time steps

x0float

Initial value

seedint, optional

Random seed

Returns:

tuple

Simulation results

abstractmethod plot_simulation(*args, **kwargs)[source]

Plot simulation results.

Estimation

Parameter Estimation Methods

This module implements various methods for estimating parameters of jump-diffusion models, including maximum likelihood, method of moments, and Bayesian approaches.

class jump_diffusion.estimation.JumpDiffusionEstimator(data: ndarray, dt: float, jump_distribution: JumpDistribution | None = None)[source]

Bases: BaseEstimator

Maximum likelihood estimator for jump-diffusion models.

This estimator handles jump-diffusion processes with a pluggable jump-size distribution (skew-normal by default) using mixture likelihood functions. The input data must be a one-dimensional array of increments.

References: - Ardia, D., Ospina, J. D., & Giraldo, N. D. (2011). Jump-diffusion

calibration using differential evolution. Wilmott, 2011(55), 76-79.

property param_names: Tuple[str, ...]

Ordered parameter names for this estimator.

Always ("mu", "sigma", "jump_prob", *jump_distribution.param_names). This is the order used by every parameter vector, standard-error and confidence-interval dictionary the estimator produces, so it is the natural key for iterating over results.

log_likelihood(params: ndarray) float[source]

Calculate negative log-likelihood for optimization.

Parameters:

paramsnp.ndarray

Parameter vector, ordered as self._param_names: [mu, sigma, jump_prob, *jump_distribution.param_names].

Returns:

float

Negative log-likelihood value

estimate(initial_guess: ndarray | None = None, method: str = 'L-BFGS-B', bounds: List[Tuple[float, float]] | None = None, **kwargs) Dict[str, Any][source]

Estimate parameters using maximum likelihood.

Parameters:

initial_guessnp.array, optional

Initial parameter values. Optional for every method: gradient methods fall back to a moment-based heuristic guess, while "differential_evolution" does not need one at all (its initial population is sampled over bounds; when a guess is supplied it merely seeds one population member).

methodstr

Optimization method. Any scipy.optimize.minimize method name (default "L-BFGS-B"), or "differential_evolution" for the global, population-based optimizer from scipy.optimize.differential_evolution. Differential evolution is markedly more robust to poor prior knowledge on this mixture likelihood – the applied finding of Ospina Arango (2009), where L-BFGS-B stalled at box boundaries and simulated annealing diverged, while DE (rand/1, population 70, 400 generations in R’s DEoptim) recovered the true parameters even under very wide bounds. The trade-off is computational cost (thousands of likelihood evaluations). For the differential evolution algorithm, see Storn & Price (1997).

boundslist of (low, high) tuples, optional

Optimization box, one pair per parameter in the order [mu, sigma, jump_prob, *jump_distribution.param_names]. Defaults to the model’s own bounds for gradient methods, or a wide data-driven finite box (see _finite_bounds) for differential evolution, which requires every bound finite.

**kwargsdict

Additional arguments for the optimizer: merged into options for scipy.optimize.minimize, passed directly to scipy.optimize.differential_evolution (e.g. seed=42 for reproducibility, maxiter, popsize, workers).

Returns:

dict

Estimation results

estimate_standard_errors(n_points: int = 7, confidence_level: float = 0.95, grid_width_factor: float = 3.0) Dict[str, Any][source]

Estimate parameter standard errors and confidence intervals using likelihood profiling based on Wilks’ theorem (Wilks, 1938).

Parameters:

n_pointsint

Number of points to evaluate in the grid for profiling.

confidence_levelfloat

Confidence level for the intervals (e.g. 0.95 for 95% confidence).

grid_width_factorfloat

Factor determining the width of the grid around the MLE.

Returns:

dict

Dictionary containing standard errors and confidence intervals.

estimate_wald_standard_errors(confidence_level: float = 0.95) Dict[str, Any][source]

Estimate standard errors and confidence intervals from the observed Fisher information (the Wald method).

This is the classical large-sample alternative to the profile likelihood intervals of estimate_standard_errors(). It inverts the observed information matrix (see _observed_information_matrix()) to obtain the asymptotic covariance of the maximum likelihood estimator, takes the square root of its diagonal as the standard errors, and forms symmetric intervals estimate +/- z * SE with z the standard normal quantile.

Wald intervals are cheap (a single Hessian, no re-optimization) but are symmetric by construction and are known to under-cover in finite samples for parameters near a boundary – notably the jump probability as it approaches zero. Providing both Wald and profile intervals is deliberate: comparing their coverage across jump distributions is one of the intended research uses of this library.

Parameters:

confidence_levelfloat

Confidence level for the intervals (e.g. 0.95 for 95%).

Returns:

dict

Dictionary with standard_errors and confidence_intervals, each keyed by parameter name. A parameter’s standard error is nan when the observed information could not be evaluated or inverted to a positive variance (e.g. an estimate pinned to a bound, or a singular Hessian); its interval is then (nan, nan). The results are also stored on self.results under wald_standard_errors, wald_confidence_intervals and observed_information.

Raises:

ValueError

If the model has not been fitted yet.

estimate_bootstrap_standard_errors(n_bootstrap: int = 200, confidence_level: float = 0.95, seed: int | None = None, **estimate_kwargs: Any) Dict[str, Any][source]

Estimate standard errors and confidence intervals by parametric bootstrap.

This is the third inference route in the library, alongside the profile likelihood intervals of estimate_standard_errors() and the Wald intervals of estimate_wald_standard_errors(). It makes no asymptotic-normality or regularity assumption, so it is the most trustworthy of the three near a boundary (e.g. the jump probability approaching zero) – at the cost of re-fitting the model n_bootstrap times.

The procedure is the textbook parametric bootstrap: treat the fitted parameters as if they were the truth, simulate n_bootstrap fresh datasets of the same length from that model, re-estimate the parameters on each, and read the sampling variability directly off the resulting replicate estimates. Standard errors are their (ddof=1) standard deviation and confidence intervals are percentile intervals.

Parameters:

n_bootstrapint

Number of bootstrap replicates (model re-fits). More replicates reduce Monte Carlo error in the standard errors and intervals but scale the cost linearly.

confidence_levelfloat

Confidence level for the percentile intervals (e.g. 0.95).

seedint, optional

Base seed for reproducibility. When given, replicate b is simulated with seed seed + b; when None the replicates draw from NumPy’s global random state and are not reproducible.

**estimate_kwargsdict

Forwarded to estimate() for each replicate re-fit (e.g. method="differential_evolution"). Defaults to the same gradient-based fit used elsewhere.

Returns:

dict

Dictionary with standard_errors and confidence_intervals (each keyed by parameter name), plus n_successful – the number of replicates whose re-fit converged and contributed to the estimates. Non-converged replicates are discarded. If fewer than two replicates succeed, all standard errors and interval endpoints are nan. The results are also stored on self.results under bootstrap_standard_errors, bootstrap_confidence_intervals and bootstrap_estimates (the raw replicate matrix).

Raises:

ValueError

If the model has not been fitted yet.

test_for_jumps(n_bootstrap: int = 200, seed: int | None = None, **estimate_kwargs: Any) Dict[str, Any][source]

Test for the presence of jumps via a parametric bootstrap likelihood ratio test of H0: jump_prob = 0 (pure diffusion) against H1: jump_prob > 0.

The statistic is the usual likelihood ratio LR = 2 * (loglik_full - loglik_null), where loglik_full is the maximized jump-diffusion log-likelihood (already available from the fit) and loglik_null is the closed-form maximized Gaussian log-likelihood (see _pure_diffusion_log_likelihood()).

Its asymptotic null distribution is non-standard: under H0 the jump probability sits on the boundary of the parameter space (Chernoff, 1954; Self & Liang, 1987) and the jump-size parameters become unidentified (Davies, 1977, 1987) – so the usual chi-squared calibration does not apply. We therefore obtain the p-value by parametric bootstrap (a Monte Carlo test): simulate n_bootstrap pure-diffusion datasets from the fitted null model, recompute the LR statistic on each, and compare the observed statistic against that simulated null distribution. This sidesteps both pathologies by construction.

Parameters:

n_bootstrapint

Number of bootstrap datasets drawn under the null. Each requires re-fitting the full jump-diffusion model, so cost scales linearly.

seedint, optional

Seed for the bootstrap data generation, for reproducibility.

**estimate_kwargsdict

Forwarded to estimate() for each bootstrap re-fit.

Returns:

dict

Dictionary with:

  • lr_statistic – observed likelihood ratio statistic.

  • p_value – bootstrap p-value (1 + #{LR* >= LR_obs}) / (n_successful + 1); nan if no bootstrap re-fit converged.

  • log_likelihood_full / log_likelihood_null – the two maximized log-likelihoods on the observed data.

  • n_bootstrap / n_successful – requested and converged replicate counts.

  • bootstrap_statistics – the simulated null LR values.

The result is also stored on self.results under jump_test.

Raises:

ValueError

If the model has not been fitted yet.

summary() DataFrame[source]

Tidy table of the estimates and every inference route computed so far.

Returns one row per parameter with its point estimate plus, for each inference method that has been run, the standard error and confidence interval bounds. Columns are only added for methods that were actually computed:

  • estimate_standard_errors -> profile_se, profile_ci_low, profile_ci_high

  • estimate_wald_standard_errors -> wald_se, wald_ci_low, wald_ci_high

  • estimate_bootstrap_standard_errors -> bootstrap_se, bootstrap_ci_low, bootstrap_ci_high

This is the structured counterpart to diagnostics() (which prints a single-method table): it puts the profile, Wald and bootstrap results side by side, which is exactly what a coverage comparison or a results table for a paper needs.

Returns:

pandas.DataFrame

One row per parameter, indexed by insertion order, with an estimate column and the SE/CI columns of whichever methods have been run.

Raises:

ValueError

If the model has not been fitted yet.

plot_profiles(figsize: Tuple[float, float] = (15, 10)) None[source]

Plot the profile log-likelihood curves for each parameter.

diagnostics() None[source]

Print diagnostic information about the estimation.

The method writes a summary of the fitted model to stdout and returns None. The following metrics are reported:

  • Estimated parameters (μ, σ, jump probability, and the jump distribution’s own parameters)

  • Log-likelihood value

  • Information criteria (AIC and BIC)

  • Optimizer convergence flag

  • Comparison of empirical vs. theoretical mean, standard deviation and the expected number of jumps

class jump_diffusion.estimation.BaseEstimator(data: ndarray, dt: float)[source]

Bases: ABC

Abstract base class for all parameter estimators.

abstractmethod estimate(**kwargs) Dict[str, Any][source]

Estimate model parameters.

Returns:

dict

Estimation results including parameters and diagnostics

abstractmethod log_likelihood(params: ndarray) float[source]

Calculate log-likelihood for given parameters.

Parameters:

paramsnp.ndarray

Parameter values

Returns:

float

Log-likelihood value

get_results() Dict[str, Any] | None[source]

Get estimation results if available.

Jump Distributions

Pluggable Jump-Size Distributions

This module contains the jump-size distributions that can be plugged into JumpDiffusionModel via its jump_distribution argument.

class jump_diffusion.distributions.JumpDistribution[source]

Bases: ABC

Abstract interface for a jump-size distribution.

param_names: Tuple[str, ...] = ()
abstractmethod default_params() Dict[str, float][source]

Return sensible default parameter values.

abstractmethod pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

abstractmethod param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

abstractmethod initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

characteristic_scale(params: Dict[str, float]) float[source]

Rough scale of the jump size, used to size the FFT/inverse-CDF grids in fft_convolved_pdf() and rvs().

Default reads jump_scale directly, the convention used by NormalJump/SkewNormalJump/SGEDJump. Override this for distributions with a different parameterization (e.g. KouJump, which has separate up/down scales instead of a single one).

diffusion_convolved_pdf(x: ndarray, params: Dict[str, float], diffusion_mean: float, diffusion_std: float) ndarray | None[source]

Closed-form density of (diffusion + jump), if one is known.

Returns None when no closed form is available, signalling callers to fall back to fft_convolved_pdf().

fft_convolved_pdf(x: ndarray, params: Dict[str, float], diffusion_mean: float, diffusion_std: float, j: int = 15, h: float | None = None) ndarray[source]

Numerically approximate the density of (diffusion + jump) via FFT convolution.

Implements the discretization scheme from Ospina Arango (2009), “Estimacion de un modelo de difusion con saltos con distribucion de error generalizada asimetrica usando algoritmos evolutivos” (Universidad Nacional de Colombia): both densities are discretized on a symmetric grid of 2 * 2**j half-integer-offset points around zero, convolved via FFT, and linearly interpolated to evaluate at the requested points.

rvs(params: Dict[str, float], size: int, random_state: Generator | None = None) ndarray[source]

Draw random jump sizes via numerical inverse-CDF sampling.

Generic fallback for distributions without a native fast sampler: discretizes pdf on a grid (in the same spirit as fft_convolved_pdf()) and inverts its cumulative sum.

When random_state is None (the default), draws from NumPy’s global legacy random state – the same one seeded by JumpDiffusionModel.simulate(seed=...) via np.random.seed – so that simulations stay reproducible. Pass an explicit np.random.Generator for an isolated, independent stream.

class jump_diffusion.distributions.SkewNormalJump[source]

Bases: JumpDistribution

Jump sizes distributed as a skew-normal centered at zero.

param_names: Tuple[str, ...] = ('jump_scale', 'jump_skew')
default_params() Dict[str, float][source]

Return sensible default parameter values.

pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

diffusion_convolved_pdf(x: ndarray, params: Dict[str, float], diffusion_mean: float, diffusion_std: float) ndarray | None[source]

Closed-form density of (diffusion + jump), if one is known.

Returns None when no closed form is available, signalling callers to fall back to fft_convolved_pdf().

rvs(params: Dict[str, float], size: int, random_state: Generator | None = None) ndarray[source]

Draw random jump sizes via numerical inverse-CDF sampling.

Generic fallback for distributions without a native fast sampler: discretizes pdf on a grid (in the same spirit as fft_convolved_pdf()) and inverts its cumulative sum.

When random_state is None (the default), draws from NumPy’s global legacy random state – the same one seeded by JumpDiffusionModel.simulate(seed=...) via np.random.seed – so that simulations stay reproducible. Pass an explicit np.random.Generator for an isolated, independent stream.

class jump_diffusion.distributions.NormalJump[source]

Bases: JumpDistribution

Jump sizes distributed as a normal centered at zero.

References: - Merton, R. C. (1976). Option pricing when underlying stock returns

are discontinuous. Journal of financial economics, 3(1-2), 125-144.

param_names: Tuple[str, ...] = ('jump_scale',)
default_params() Dict[str, float][source]

Return sensible default parameter values.

pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

diffusion_convolved_pdf(x: ndarray, params: Dict[str, float], diffusion_mean: float, diffusion_std: float) ndarray | None[source]

Closed-form density of (diffusion + jump), if one is known.

Returns None when no closed form is available, signalling callers to fall back to fft_convolved_pdf().

rvs(params: Dict[str, float], size: int, random_state: Generator | None = None) ndarray[source]

Draw random jump sizes via numerical inverse-CDF sampling.

Generic fallback for distributions without a native fast sampler: discretizes pdf on a grid (in the same spirit as fft_convolved_pdf()) and inverts its cumulative sum.

When random_state is None (the default), draws from NumPy’s global legacy random state – the same one seeded by JumpDiffusionModel.simulate(seed=...) via np.random.seed – so that simulations stay reproducible. Pass an explicit np.random.Generator for an isolated, independent stream.

class jump_diffusion.distributions.SGEDJump[source]

Bases: JumpDistribution

Jump sizes distributed as a Skewed Generalized Error Distribution.

References: - Ospina Arango, J. D. (2009). Tesis de Maestría. Universidad Nacional de Colombia. - Theodossiou, P. (2015). Skewed Generalized Error Distribution of

Financial Assets and Option Pricing. Multinational Finance Journal, 19(4), 223-266.

param_names: Tuple[str, ...] = ('jump_loc', 'jump_scale', 'jump_nu', 'jump_xi')
default_params() Dict[str, float][source]

Return sensible default parameter values.

pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

class jump_diffusion.distributions.KouJump[source]

Bases: JumpDistribution

Jump sizes distributed as Kou’s asymmetric double exponential.

param_names: Tuple[str, ...] = ('jump_prob_up', 'jump_scale_up', 'jump_scale_down')
default_params() Dict[str, float][source]

Return sensible default parameter values.

pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

characteristic_scale(params: Dict[str, float]) float[source]

Rough scale of the jump size, used to size the FFT/inverse-CDF grids in fft_convolved_pdf() and rvs().

Default reads jump_scale directly, the convention used by NormalJump/SkewNormalJump/SGEDJump. Override this for distributions with a different parameterization (e.g. KouJump, which has separate up/down scales instead of a single one).

initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

diffusion_convolved_pdf(x: ndarray, params: Dict[str, float], diffusion_mean: float, diffusion_std: float) ndarray | None[source]

Closed-form density of (diffusion + jump), if one is known.

Returns None when no closed form is available, signalling callers to fall back to fft_convolved_pdf().

rvs(params: Dict[str, float], size: int, random_state: Generator | None = None) ndarray[source]

Draw random jump sizes via numerical inverse-CDF sampling.

Generic fallback for distributions without a native fast sampler: discretizes pdf on a grid (in the same spirit as fft_convolved_pdf()) and inverts its cumulative sum.

When random_state is None (the default), draws from NumPy’s global legacy random state – the same one seeded by JumpDiffusionModel.simulate(seed=...) via np.random.seed – so that simulations stay reproducible. Pass an explicit np.random.Generator for an isolated, independent stream.

class jump_diffusion.distributions.StudentTJump[source]

Bases: JumpDistribution

Jump sizes distributed as a (standardized) Student-t.

param_names: Tuple[str, ...] = ('jump_loc', 'jump_scale', 'jump_df')
default_params() Dict[str, float][source]

Return sensible default parameter values.

pdf(x: ndarray, params: Dict[str, float]) ndarray[source]

Probability density of the jump size at x.

param_bounds() Dict[str, Tuple[float | None, float | None]][source]

Optimization bounds for each parameter in param_names.

initial_guess(mean_increment: float, std_increment: float, skewness: float) Dict[str, float][source]

Heuristic initial parameter guess derived from data moments.

rvs(params: Dict[str, float], size: int, random_state: Generator | None = None) ndarray[source]

Draw random jump sizes via numerical inverse-CDF sampling.

Generic fallback for distributions without a native fast sampler: discretizes pdf on a grid (in the same spirit as fft_convolved_pdf()) and inverts its cumulative sum.

When random_state is None (the default), draws from NumPy’s global legacy random state – the same one seeded by JumpDiffusionModel.simulate(seed=...) via np.random.seed – so that simulations stay reproducible. Pass an explicit np.random.Generator for an isolated, independent stream.

Validation

Validation and Testing Tools

This module provides tools for validating estimation methods through Monte Carlo experiments and diagnostic tests.

class jump_diffusion.validation.ValidationExperiment(true_params: Dict[str, float], jump_distribution: JumpDistribution | None = None)[source]

Bases: object

Monte Carlo validation experiment for jump-diffusion estimators.

This class orchestrates validation experiments where we simulate data with known parameters and test how well our estimators can recover those parameters.

run_experiment(n_simulations: int = 10, T: float = 1.0, n_steps: int = 252, x0: float = 100.0, seed_base: int = 42) DataFrame[source]

Run Monte Carlo validation experiment.

Parameters:

n_simulationsint

Number of simulation runs

Tfloat

Time horizon for each simulation

n_stepsint

Number of time steps per simulation

x0float

Initial value

seed_baseint

Base seed for reproducibility

Returns:

pd.DataFrame

Results of all experiments

analyze_results() Dict[str, Any][source]

Analyze validation results and compute statistics.

Returns:

dict

Analysis results including bias, RMSE, etc.

plot_results(figsize: tuple = (15, 10))[source]

Create plots summarizing parameter estimation accuracy.

Parameters:

figsize (tuple, optional) – Width and height of the Matplotlib figure in inches.

Notes

Generates a grid of subplots showing scatter plots for each parameter and a summary bar chart of bias and RMSE. The run_experiment() method must be called beforehand to populate self.results. This function displays the plots directly and returns None.

class jump_diffusion.validation.JumpDistributionComparison(data: ndarray, dt: float)[source]

Bases: object

Fits several jump-size distributions to the same data and compares their goodness of fit.

fit(name: str, jump_distribution: JumpDistribution, seed: int | None = None, n_bootstrap: int = 199, ks_reference_size: int | None = None, **estimate_kwargs: Any) Dict[str, Any][source]

Fit jump_distribution to the data and record its goodness of fit.

The KS statistic is the distance between the data and the fitted model’s distribution, the latter approximated by a large simulated reference sample so that simulation noise in the statistic itself is negligible. Its p-value is obtained by parametric bootstrap (see _parametric_bootstrap_ks_pvalue()), which is the dominant cost of this method.

Parameters:

namestr

Label used to identify this fit in results/compare().

jump_distributionJumpDistribution

Jump-size distribution to fit.

seedint, optional

Base random seed. When given, the reference sample, the plotting sample and every bootstrap replicate use distinct derived seeds, so the whole fit is reproducible.

n_bootstrapint

Number of parametric bootstrap replicates for the KS p-value. Each re-fits the model, so cost scales linearly; set to 0 to skip the p-value (it is then reported as nan).

ks_reference_sizeint, optional

Size of the reference sample used to evaluate the KS statistic. Defaults to max(20 * n_obs, 20000). Larger values give a more stable statistic at higher simulation cost.

**estimate_kwargsdict

Additional arguments forwarded to JumpDiffusionEstimator.estimate (also used for every bootstrap re-fit).

Returns:

dict

The estimation results, extended with ks_statistic, ks_pvalue (parametric bootstrap), ks_n_bootstrap and simulated_increments (an observation-sized sample kept for plot_comparison()).

compare() DataFrame[source]

Summarize all fitted distributions, ranked by AIC (best first).

plot_comparison(bins: int = 50, figsize: Tuple[float, float] = (12, 6)) None[source]

Overlay a histogram of the real data with each fitted distribution’s simulated sample.