Math Module¶
See also
NumPy Interoperability for detailed NumPy interoperability documentation.
Linear Algebra¶
Array¶
- class pyquantlib.Array¶
Bases:
pybind11_object1-dimensional array of Real values.
- __init__(*args, **kwargs)¶
Overloaded function.
__init__() -> None
Default constructor (empty array).
__init__(size: SupportsInt | SupportsIndex) -> None
Creates an array of given size.
__init__(size: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None
Creates an array of given size with all elements set to value.
__init__(iterable: collections.abc.Iterable) -> None
Creates an array from a Python iterable.
__init__(numpy_array: Annotated[numpy.ArrayLike, numpy.float64]) -> None
Creates an array from a 1D NumPy array.
- at(i: SupportsInt | SupportsIndex) float¶
Access element with bounds checking.
- fill(value: SupportsFloat | SupportsIndex) None¶
Fills the array with a value.
- resize(*args, **kwargs)¶
Overloaded function.
resize(size: SupportsInt | SupportsIndex) -> None
Resizes the array.
resize(size: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None
Resizes the array, filling new elements with value.
import pyquantlib as ql
import numpy as np
arr = ql.Array([1.0, 2.0, 3.0])
arr = ql.Array(np.array([1, 2, 3]))
# Zero-copy view to numpy
np_view = np.array(arr, copy=False)
Functions expecting Array accept Python lists and numpy arrays directly:
result = ql.DotProduct([1, 2, 3], [4, 5, 6]) # automatic conversion
Matrix¶
- class pyquantlib.Matrix¶
Bases:
pybind11_object2-dimensional matrix of Real values.
- __init__(*args, **kwargs)¶
Overloaded function.
__init__() -> None
Default constructor (empty matrix).
__init__(rows: SupportsInt | SupportsIndex, columns: SupportsInt | SupportsIndex) -> None
Creates a zero-filled matrix.
__init__(rows: SupportsInt | SupportsIndex, columns: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None
Creates a matrix filled with value.
__init__(numpy_array: Annotated[numpy.ArrayLike, numpy.float64]) -> None
Creates a matrix from a 2D NumPy array.
__init__(list_of_lists: list) -> None
Creates a matrix from a list of lists.
- column(index: SupportsInt | SupportsIndex) Array¶
Returns a column as an Array.
- property shape¶
Returns (rows, columns) tuple.
mat = ql.Matrix([[1, 2], [3, 4]])
mat = ql.Matrix(np.array([[1, 2], [3, 4]], dtype=float))
# Zero-copy view to numpy
np_view = np.array(mat, copy=False)
SVD¶
- class pyquantlib.SVD¶
Bases:
pybind11_objectSingular value decomposition of a matrix.
Singular value decomposition of a matrix.
m = ql.Matrix([[1, 2], [3, 4], [5, 6]])
svd = ql.SVD(m)
U = svd.U()
V = svd.V()
s = svd.singularValues()
SymmetricSchurDecomposition¶
- class pyquantlib.SymmetricSchurDecomposition¶
Bases:
pybind11_objectSymmetric Schur decomposition (eigenvalue decomposition).
Eigenvalue decomposition of a symmetric matrix.
m = ql.Matrix([[4, 1], [1, 3]])
ssd = ql.SymmetricSchurDecomposition(m)
eigenvalues = ssd.eigenvalues()
eigenvectors = ssd.eigenvectors()
Interpolation¶
Interpolation classes for constructing continuous functions from discrete data points.
LinearInterpolation¶
- class pyquantlib.LinearInterpolation¶
Bases:
InterpolationLinear interpolation between discrete points.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
x = [1.0, 2.0, 3.0]
y = [10.0, 20.0, 30.0]
interp = ql.LinearInterpolation(x, y)
interp(1.5) # 15.0
interp.derivative(1.5) # 10.0
LogLinearInterpolation¶
- class pyquantlib.LogLinearInterpolation¶
Bases:
InterpolationLog-linear interpolation between discrete points.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
Log-linear interpolation interpolates linearly in log-space, useful for discount factors.
x = [1.0, 2.0]
y = [1.0, math.e]
interp = ql.LogLinearInterpolation(x, y)
interp(1.5) # exp(0.5)
BackwardFlatInterpolation¶
- class pyquantlib.BackwardFlatInterpolation¶
Bases:
InterpolationBackward-flat interpolation between discrete points.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
Step function that uses the value at the next node.
x = [1.0, 2.0, 3.0]
y = [10.0, 20.0, 30.0]
interp = ql.BackwardFlatInterpolation(x, y)
interp(1.5) # 20.0 (uses next node's value)
CubicInterpolation¶
- class pyquantlib.CubicInterpolation¶
Bases:
InterpolationCubic interpolation between discrete points.
- __init__(x: collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], y: collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], derivativeApprox: CubicDerivativeApprox = <CubicDerivativeApprox.Kruger: 7>, monotonic: bool = False, leftCondition: CubicBoundaryCondition = <CubicBoundaryCondition.SecondDerivative: 2>, leftConditionValue: typing.SupportsFloat | typing.SupportsIndex = 0.0, rightCondition: CubicBoundaryCondition = <CubicBoundaryCondition.SecondDerivative: 2>, rightConditionValue: typing.SupportsFloat | typing.SupportsIndex = 0.0) None¶
Constructs cubic interpolation from x and y arrays.
Cubic spline interpolation with configurable derivative approximation and boundary conditions.
x = [1.0, 2.0, 3.0, 4.0]
y = [1.0, 4.0, 9.0, 16.0]
# Default (Kruger derivative approximation)
interp = ql.CubicInterpolation(x, y)
# Natural spline (second derivative = 0 at boundaries)
interp = ql.CubicInterpolation(
x, y,
derivativeApprox=ql.CubicDerivativeApprox.Spline,
leftCondition=ql.CubicBoundaryCondition.SecondDerivative,
leftConditionValue=0.0,
rightCondition=ql.CubicBoundaryCondition.SecondDerivative,
rightConditionValue=0.0
)
CubicNaturalSpline¶
- class pyquantlib.CubicNaturalSpline¶
Bases:
InterpolationNatural cubic spline interpolation.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
Convenience class for natural cubic spline (second derivative = 0 at boundaries).
MonotonicCubicNaturalSpline¶
- class pyquantlib.MonotonicCubicNaturalSpline¶
Bases:
InterpolationMonotonic natural cubic spline interpolation.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
Monotonicity-preserving cubic spline that prevents oscillations.
Enums¶
- class pyquantlib.CubicDerivativeApprox¶
Bases:
pybind11_objectDerivative approximation methods for cubic interpolation.
Members:
Spline
SplineOM1
SplineOM2
FourthOrder
Parabolic
FritschButland
Akima
Kruger
Harmonic
- __init__(value: SupportsInt | SupportsIndex) None¶
- Akima = <CubicDerivativeApprox.Akima: 6>¶
- FourthOrder = <CubicDerivativeApprox.FourthOrder: 3>¶
- FritschButland = <CubicDerivativeApprox.FritschButland: 5>¶
- Harmonic = <CubicDerivativeApprox.Harmonic: 8>¶
- Kruger = <CubicDerivativeApprox.Kruger: 7>¶
- Parabolic = <CubicDerivativeApprox.Parabolic: 4>¶
- Spline = <CubicDerivativeApprox.Spline: 0>¶
- SplineOM1 = <CubicDerivativeApprox.SplineOM1: 1>¶
- SplineOM2 = <CubicDerivativeApprox.SplineOM2: 2>¶
- CubicDerivativeApprox.name -> str
- property value¶
- class pyquantlib.CubicBoundaryCondition¶
Bases:
pybind11_objectBoundary conditions for cubic interpolation.
Members:
NotAKnot
FirstDerivative
SecondDerivative
Periodic
Lagrange
- __init__(value: SupportsInt | SupportsIndex) None¶
- FirstDerivative = <CubicBoundaryCondition.FirstDerivative: 1>¶
- Lagrange = <CubicBoundaryCondition.Lagrange: 4>¶
- NotAKnot = <CubicBoundaryCondition.NotAKnot: 0>¶
- Periodic = <CubicBoundaryCondition.Periodic: 3>¶
- SecondDerivative = <CubicBoundaryCondition.SecondDerivative: 2>¶
- CubicBoundaryCondition.name -> str
- property value¶
MixedLinearCubicInterpolation¶
Mixed interpolation that uses linear for the first n points and cubic for the rest.
Useful for yield curves where short-end behavior differs from long-end.
x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
y = [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]
interp = ql.MixedLinearCubicInterpolation(x, y, n=2)
MixedLinearCubicNaturalSpline¶
MixedLinearMonotonicCubicNaturalSpline¶
MixedLinearKrugerCubic¶
MixedLinearFritschButlandCubic¶
LogCubicInterpolation¶
Interpolation in log-space using cubic splines. Essential for yield curve construction where discount factors must remain positive.
x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [0.99, 0.97, 0.94, 0.90, 0.85]
interp = ql.LogCubicInterpolation(x, y)
LogCubicNaturalSpline¶
MonotonicLogCubicNaturalSpline¶
KrugerLogCubic¶
HarmonicLogCubic¶
FritschButlandLogCubic¶
LogMixedLinearCubicInterpolation¶
Log-space mixed interpolation: log-linear for the first n points, log-cubic for the rest.
LogMixedLinearCubicNaturalSpline¶
SABRInterpolation¶
SABR smile interpolation that calibrates alpha, beta, nu, rho to market volatilities.
strikes = [0.03, 0.04, 0.05, 0.06, 0.07]
vols = [0.25, 0.22, 0.20, 0.21, 0.23]
interp = ql.SABRInterpolation(
strikes, vols, expiry=1.0, forward=0.05,
alpha=0.2, beta=0.5, nu=0.4, rho=-0.3,
alphaIsFixed=False, betaIsFixed=True,
nuIsFixed=False, rhoIsFixed=False,
)
interp.update()
print(f"alpha={interp.alpha():.4f}, rho={interp.rho():.4f}, rms={interp.rmsError():.6f}")
ConvexMonotoneInterpolation¶
Convex monotone yield-curve interpolation (Hagan & West, 2006). Preserves monotonicity and convexity of the forward rate curve.
x = [0.0, 0.5, 1.0, 2.0, 3.0, 5.0]
y = [0.01, 0.015, 0.02, 0.025, 0.03, 0.035]
interp = ql.ConvexMonotoneInterpolation(x, y, quadraticity=0.3, monotonicity=0.7)
BackwardflatLinearInterpolation¶
2-D interpolation: backward-flat in the first component, linear in the second.
FlatExtrapolator2D¶
Decorator that adds flat extrapolation outside the range of any 2-D interpolation.
inner = ql.BilinearInterpolation(x, y, z)
extrap = ql.FlatExtrapolator2D(inner)
extrap.enableExtrapolation()
extrap(0.0, 0.0) # clamps to boundary value
ForwardFlatInterpolation¶
- class pyquantlib.ForwardFlatInterpolation¶
Bases:
InterpolationForward-flat interpolation (step function using current node’s value).
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
Step function that uses the current node’s value (forward-flat).
x = [1.0, 2.0, 3.0]
y = [10.0, 20.0, 30.0]
interp = ql.ForwardFlatInterpolation(x, y)
interp(1.5) # 10.0 (uses current node's value)
LagrangeInterpolation¶
- class pyquantlib.LagrangeInterpolation¶
Bases:
InterpolationLagrange interpolation through discrete points.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex]) None¶
Constructs interpolation from x and y arrays.
- value(y: Array, x: SupportsFloat | SupportsIndex) float¶
Evaluates at x using alternative y values.
Lagrange polynomial interpolation. Supports evaluation with alternative y values via value(y, x).
x = [1.0, 2.0, 3.0]
y = [1.0, 4.0, 9.0]
interp = ql.LagrangeInterpolation(x, y)
interp(1.5) # 2.25
# Evaluate with different y values
alt_y = ql.Array([1.0, 8.0, 27.0])
interp.value(alt_y, 2.0) # 8.0
BilinearInterpolation¶
- class pyquantlib.BilinearInterpolation¶
Bases:
Interpolation2DBilinear interpolation on a 2-D grid.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex], z: Matrix) None¶
Constructs from x, y arrays and z matrix.
Bilinear interpolation on a 2-D grid. Matrix z uses QuantLib convention: z[y_idx][x_idx].
x = [0.0, 1.0]
y = [0.0, 1.0]
z = ql.Matrix([[1.0, 2.0], [3.0, 4.0]])
interp = ql.BilinearInterpolation(x, y, z)
interp(0.5, 0.5) # 2.5
BicubicSpline¶
- class pyquantlib.BicubicSpline¶
Bases:
Interpolation2DBicubic spline interpolation on a 2-D grid.
- __init__(x: collections.abc.Sequence[SupportsFloat | SupportsIndex], y: collections.abc.Sequence[SupportsFloat | SupportsIndex], z: Matrix) None¶
Constructs from x, y arrays and z matrix.
- derivativeX(x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex) float¶
Returns the partial derivative with respect to x.
- derivativeXY(x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex) float¶
Returns the cross partial derivative.
- derivativeY(x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex) float¶
Returns the partial derivative with respect to y.
- secondDerivativeX(x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex) float¶
Returns the second partial derivative with respect to x.
- secondDerivativeY(x: SupportsFloat | SupportsIndex, y: SupportsFloat | SupportsIndex) float¶
Returns the second partial derivative with respect to y.
Bicubic spline interpolation on a 2-D grid with derivative methods.
x = [0.0, 1.0, 2.0]
y = [0.0, 1.0, 2.0]
z = ql.Matrix([[0, 0, 0], [0, 1, 2], [0, 2, 4]])
interp = ql.BicubicSpline(x, y, z)
interp(1.0, 1.0) # 1.0
interp.derivativeX(1, 1) # ~1.0
ChebyshevInterpolation¶
- class pyquantlib.ChebyshevInterpolation¶
Bases:
InterpolationChebyshev interpolation on [-1, 1].
- static nodesStatic(n: SupportsInt | SupportsIndex, pointsType: ChebyshevPointsType) Array¶
Returns Chebyshev nodes for given n and type.
- __init__(*args, **kwargs)¶
Overloaded function.
__init__(n: SupportsInt | SupportsIndex, f: collections.abc.Callable[[SupportsFloat | SupportsIndex], float], pointsType: ChebyshevPointsType = <ChebyshevPointsType.SecondKind: 1>) -> None
Constructs from n points and function f on [-1, 1].
__init__(y: Array, pointsType: ChebyshevPointsType = <ChebyshevPointsType.SecondKind: 1>) -> None
Constructs from pre-computed y values at Chebyshev nodes.
- class pyquantlib.ChebyshevPointsType¶
Bases:
pybind11_objectChebyshev node type.
Members:
FirstKind
SecondKind
- __init__(value: SupportsInt | SupportsIndex) None¶
- FirstKind = <ChebyshevPointsType.FirstKind: 0>¶
- SecondKind = <ChebyshevPointsType.SecondKind: 1>¶
- ChebyshevPointsType.name -> str
- property value¶
Chebyshev polynomial interpolation on [-1, 1].
import math
interp = ql.ChebyshevInterpolation(20, math.sin)
interp(0.5) # sin(0.5)
RichardsonExtrapolation¶
- class pyquantlib.RichardsonExtrapolation¶
Bases:
pybind11_objectRichardson extrapolation for improving convergence.
- __init__(f: collections.abc.Callable[[SupportsFloat | SupportsIndex], float], deltaH: SupportsFloat | SupportsIndex, n: object = None) None¶
Constructs from function f, step size delta_h, and optional order n.
Richardson extrapolation for improving convergence of numerical methods.
f = lambda h: math.sin(h) / h
re = ql.RichardsonExtrapolation(f, 0.01, n=2.0)
re(2.0) # ~1.0 (limit as h->0)
Note
The abstract base classes Interpolation and Interpolation2D are available in pyquantlib.base for type checking.
Statistics¶
Statistics¶
- class pyquantlib.Statistics¶
Bases:
pybind11_objectStatistics tool with empirical-distribution risk measures.
- add(value: SupportsFloat | SupportsIndex, weight: SupportsFloat | SupportsIndex = 1.0) None¶
Adds a datum to the set, possibly with a weight.
- addSequence(*args, **kwargs)¶
Overloaded function.
addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None
Adds a sequence of data to the set.
addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex], weights: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None
Adds a sequence of data with weights.
- averageShortfall(target: SupportsFloat | SupportsIndex) float¶
Returns the averaged shortfallness below target.
- expectedShortfall(percentile: SupportsFloat | SupportsIndex) float¶
Returns the expected shortfall at a given percentile.
- gaussianAverageShortfall(target: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption averaged shortfallness.
- gaussianExpectedShortfall(percentile: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption expected shortfall.
- gaussianPercentile(percentile: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption percentile.
- gaussianPotentialUpside(percentile: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption potential upside.
- gaussianRegret(target: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption regret below target.
- gaussianShortfall(target: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption shortfall probability.
- gaussianTopPercentile(percentile: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption top percentile.
- gaussianValueAtRisk(percentile: SupportsFloat | SupportsIndex) float¶
Returns the gaussian-assumption VaR.
- percentile(y: SupportsFloat | SupportsIndex) float¶
Returns the y-th percentile.
- potentialUpside(percentile: SupportsFloat | SupportsIndex) float¶
Returns the potential upside at a given percentile.
- regret(target: SupportsFloat | SupportsIndex) float¶
Returns the variance of observations below target.
- shortfall(target: SupportsFloat | SupportsIndex) float¶
Returns the probability of missing the target.
- topPercentile(y: SupportsFloat | SupportsIndex) float¶
Returns the y-th top percentile.
- valueAtRisk(percentile: SupportsFloat | SupportsIndex) float¶
Returns the value-at-risk at a given percentile.
General statistics accumulator with empirical-distribution risk measures, Gaussian-assumption analytics, and percentile/VaR/ES methods.
stats = ql.Statistics()
stats.addSequence([1.0, 2.0, 3.0, 4.0, 5.0])
print(stats.mean(), stats.standardDeviation(), stats.skewness())
IncrementalStatistics¶
- class pyquantlib.IncrementalStatistics¶
Bases:
pybind11_objectStatistics tool based on incremental accumulation (boost accumulators).
- add(value: SupportsFloat | SupportsIndex, weight: SupportsFloat | SupportsIndex = 1.0) None¶
Adds a datum to the set, possibly with a weight.
- addSequence(*args, **kwargs)¶
Overloaded function.
addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None
Adds a sequence of data to the set.
addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex], weights: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None
Adds a sequence of data with weights.
Online (streaming) statistics via boost accumulators. Supports weighted observations.
stats = ql.IncrementalStatistics()
stats.add(1.0, 1.0)
stats.add(2.0, 1.0)
print(stats.mean(), stats.weightSum())
SequenceStatistics¶
- class pyquantlib.SequenceStatistics¶
Bases:
pybind11_objectN-dimensional statistics tool with covariance and correlation.
- __init__(dimension: SupportsInt | SupportsIndex = 0) None¶
Constructs with given dimension (0 for auto-detection).
- add(sample: collections.abc.Sequence[SupportsFloat | SupportsIndex], weight: SupportsFloat | SupportsIndex = 1.0) None¶
Adds an N-dimensional sample, possibly with a weight.
- averageShortfall(target: SupportsFloat | SupportsIndex) list[float]¶
Returns the average shortfall for each dimension.
- expectedShortfall(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the expected shortfall for each dimension.
- gaussianAverageShortfall(target: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian average shortfall for each dimension.
- gaussianExpectedShortfall(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian expected shortfall for each dimension.
- gaussianPercentile(y: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian percentile for each dimension.
- gaussianPotentialUpside(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian potential upside for each dimension.
- gaussianShortfall(target: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian shortfall for each dimension.
- gaussianValueAtRisk(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the gaussian VaR for each dimension.
- percentile(y: SupportsFloat | SupportsIndex) list[float]¶
Returns the percentile for each dimension.
- potentialUpside(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the potential upside for each dimension.
- regret(target: SupportsFloat | SupportsIndex) list[float]¶
Returns the regret for each dimension.
- reset(dimension: SupportsInt | SupportsIndex = 0) None¶
Resets the data, optionally with a new dimension.
- shortfall(target: SupportsFloat | SupportsIndex) list[float]¶
Returns the shortfall for each dimension.
- valueAtRisk(percentile: SupportsFloat | SupportsIndex) list[float]¶
Returns the VaR for each dimension.
N-dimensional statistics with covariance and correlation matrices.
stats = ql.SequenceStatistics(2)
stats.add([1.0, 2.0])
stats.add([3.0, 4.0])
print(stats.mean(), stats.covariance())
Optimization¶
EndCriteria¶
- class pyquantlib.EndCriteria¶
Bases:
pybind11_objectCriteria to end optimization processes.
- class Type¶
Bases:
pybind11_objectEnd criteria type enumeration.
Members:
MaxIterations
StationaryPoint
StationaryFunctionValue
StationaryFunctionAccuracy
ZeroGradientNorm
FunctionEpsilonTooSmall
Unknown
- __init__(value: SupportsInt | SupportsIndex) None¶
- FunctionEpsilonTooSmall = <Type.FunctionEpsilonTooSmall: 6>¶
- MaxIterations = <Type.MaxIterations: 1>¶
- None_ = <Type.None_: 0>¶
- StationaryFunctionAccuracy = <Type.StationaryFunctionAccuracy: 4>¶
- StationaryFunctionValue = <Type.StationaryFunctionValue: 3>¶
- StationaryPoint = <Type.StationaryPoint: 2>¶
- Unknown = <Type.Unknown: 7>¶
- ZeroGradientNorm = <Type.ZeroGradientNorm: 5>¶
- EndCriteria.Type.name -> str
- property value¶
- static succeeded(ecType: EndCriteria.Type) bool¶
Returns true if the optimization succeeded.
- __init__(maxIterations: SupportsInt | SupportsIndex, maxStationaryStateIterations: SupportsInt | SupportsIndex, rootEpsilon: SupportsFloat | SupportsIndex, functionEpsilon: SupportsFloat | SupportsIndex, gradientNormEpsilon: SupportsFloat | SupportsIndex) None¶
Creates end criteria for optimization.
- checkMaxIterations(iteration: SupportsInt | SupportsIndex, ecType: EndCriteria.Type) tuple[bool, EndCriteria.Type]¶
Checks if maximum iterations reached. Returns (bool, ecType).
- checkStationaryFunctionAccuracy(f: SupportsFloat | SupportsIndex, positiveOptimization: bool, ecType: EndCriteria.Type) tuple[bool, EndCriteria.Type]¶
Checks for stationary function accuracy. Returns (bool, ecType).
- checkStationaryFunctionValue(fxOld: SupportsFloat | SupportsIndex, fxNew: SupportsFloat | SupportsIndex, statStateIterations: SupportsInt | SupportsIndex, ecType: EndCriteria.Type) tuple[bool, int, EndCriteria.Type]¶
Checks for stationary function value. Returns (bool, statStateIterations, ecType).
- checkStationaryPoint(xOld: SupportsFloat | SupportsIndex, xNew: SupportsFloat | SupportsIndex, statState: SupportsInt | SupportsIndex, ecType: EndCriteria.Type) tuple[bool, EndCriteria.Type]¶
Checks for stationary point. Returns (bool, ecType).
- checkZeroGradientNorm(gNorm: SupportsFloat | SupportsIndex, ecType: EndCriteria.Type) tuple[bool, EndCriteria.Type]¶
Checks for zero gradient norm. Returns (bool, ecType).
- property functionEpsilon¶
Returns the function epsilon.
- property gradientNormEpsilon¶
Returns the gradient norm epsilon.
- property maxIterations¶
Returns the maximum number of iterations.
- property maxStationaryStateIterations¶
Returns the maximum stationary state iterations.
- property rootEpsilon¶
Returns the root epsilon.
LevenbergMarquardt¶
- class pyquantlib.LevenbergMarquardt¶
Bases:
OptimizationMethodLevenberg-Marquardt optimization method.
- __init__(epsfcn: SupportsFloat | SupportsIndex = 1e-08, xtol: SupportsFloat | SupportsIndex = 1e-08, gtol: SupportsFloat | SupportsIndex = 1e-08) None¶
Creates a Levenberg-Marquardt optimizer.
Simplex¶
- class pyquantlib.Simplex¶
Bases:
OptimizationMethodMulti-dimensional simplex optimization method.
- __init__(lambda_: SupportsFloat | SupportsIndex) None¶
Constructs with the characteristic length scale lambda.
Nelder-Mead simplex optimization method.
optimizer = ql.Simplex(0.1)
ConjugateGradient¶
SteepestDescent¶
BFGS¶
DifferentialEvolution¶
- class pyquantlib.DifferentialEvolution¶
Bases:
OptimizationMethodDifferential evolution global optimization method.
- __init__(configuration: DEConfiguration = <DEConfiguration object at 0x7f253435c0b0>) None¶
Constructs with the given configuration.
- configuration() DEConfiguration¶
Returns the configuration.
- class pyquantlib.DEConfiguration¶
Bases:
pybind11_objectConfiguration for the differential evolution optimizer.
- withAdaptiveCrossover(b: bool = True) DEConfiguration¶
Sets whether crossover is adaptive.
- withBounds(b: bool = True) DEConfiguration¶
Sets whether to apply bounds.
- withCrossoverProbability(p: SupportsFloat | SupportsIndex) DEConfiguration¶
Sets crossover probability.
- withCrossoverType(crossoverType: DECrossoverType) DEConfiguration¶
Sets crossover type.
- withLowerBound(l: Array) DEConfiguration¶
Sets lower bounds.
- withPopulationMembers(n: SupportsInt | SupportsIndex) DEConfiguration¶
Sets number of population members.
- withSeed(seed: SupportsInt | SupportsIndex) DEConfiguration¶
Sets random seed.
- withStepsizeWeight(w: SupportsFloat | SupportsIndex) DEConfiguration¶
Sets step size weight.
- withStrategy(strategy: DEStrategy) DEConfiguration¶
Sets mutation strategy.
- withUpperBound(u: Array) DEConfiguration¶
Sets upper bounds.
- property applyBounds¶
Whether to apply bounds.
- property crossoverIsAdaptive¶
Whether crossover is adaptive.
- property crossoverProbability¶
Crossover probability (CR).
- property crossoverType¶
Crossover type.
- property lowerBound¶
Lower bounds for parameters.
- property populationMembers¶
Number of population members.
- property seed¶
Random seed.
- property stepsizeWeight¶
Step size weight (F).
- property strategy¶
Mutation strategy.
- property upperBound¶
Upper bounds for parameters.
- class pyquantlib.DEStrategy¶
Bases:
pybind11_objectDifferential evolution mutation strategy.
Members:
Rand1Standard
BestMemberWithJitter
CurrentToBest2Diffs
Rand1DiffWithPerVectorDither
Rand1DiffWithDither
EitherOrWithOptimalRecombination
Rand1SelfadaptiveWithRotation
- __init__(value: SupportsInt | SupportsIndex) None¶
- BestMemberWithJitter = <DEStrategy.BestMemberWithJitter: 1>¶
- CurrentToBest2Diffs = <DEStrategy.CurrentToBest2Diffs: 2>¶
- EitherOrWithOptimalRecombination = <DEStrategy.EitherOrWithOptimalRecombination: 5>¶
- Rand1DiffWithDither = <DEStrategy.Rand1DiffWithDither: 4>¶
- Rand1DiffWithPerVectorDither = <DEStrategy.Rand1DiffWithPerVectorDither: 3>¶
- Rand1SelfadaptiveWithRotation = <DEStrategy.Rand1SelfadaptiveWithRotation: 6>¶
- Rand1Standard = <DEStrategy.Rand1Standard: 0>¶
- DEStrategy.name -> str
- property value¶
- class pyquantlib.DECrossoverType¶
Bases:
pybind11_objectDifferential evolution crossover type.
Members:
Normal
Binomial
Exponential
- __init__(value: SupportsInt | SupportsIndex) None¶
- Binomial = <DECrossoverType.Binomial: 1>¶
- Exponential = <DECrossoverType.Exponential: 2>¶
- Normal = <DECrossoverType.Normal: 0>¶
- DECrossoverType.name -> str
- property value¶
Global optimizer using differential evolution. Configuration uses a builder pattern:
config = ql.DEConfiguration()
config = config.withStepsizeWeight(0.5).withCrossoverProbability(0.9)
optimizer = ql.DifferentialEvolution(config)
Problem¶
- class pyquantlib.Problem¶
Bases:
pybind11_objectConstrained optimization problem.
- __init__(costFunction: base.CostFunction, constraint: base.Constraint, initialValue: Array) None¶
Creates an optimization problem.
- constraint() base.Constraint¶
Returns the constraint.
- costFunction() base.CostFunction¶
Returns the cost function.
Constraints¶
- class pyquantlib.PositiveConstraint¶
Bases:
ConstraintConstraint enforcing positive values.
- class pyquantlib.BoundaryConstraint¶
Bases:
ConstraintConstraint enforcing values within bounds.
- __init__(low: SupportsFloat | SupportsIndex, high: SupportsFloat | SupportsIndex) None¶
- class pyquantlib.CompositeConstraint¶
Bases:
ConstraintComposite of two constraints.
Note
Abstract base classes like Constraint, OptimizationMethod, and CostFunction are available in pyquantlib.base for subclassing.
Distributions¶
NormalDistribution¶
- class pyquantlib.NormalDistribution¶
Bases:
pybind11_objectNormal (Gaussian) distribution function.
- __init__(average: SupportsFloat | SupportsIndex = 0.0, sigma: SupportsFloat | SupportsIndex = 1.0) None¶
Constructs NormalDistribution.
- derivative(x: SupportsFloat | SupportsIndex) float¶
Returns the derivative of the density at x.
Normal (Gaussian) probability density function.
pdf = ql.NormalDistribution() # standard normal (mean=0, sigma=1)
pdf(0.0) # ~0.3989 (peak)
pdf.derivative(0.0) # 0.0 (at the peak)
pdf2 = ql.NormalDistribution(average=5.0, sigma=2.0)
CumulativeNormalDistribution¶
- class pyquantlib.CumulativeNormalDistribution¶
Bases:
pybind11_objectCumulative normal distribution function.
- __init__(average: SupportsFloat | SupportsIndex = 0.0, sigma: SupportsFloat | SupportsIndex = 1.0) None¶
Constructs CumulativeNormalDistribution.
- derivative(x: SupportsFloat | SupportsIndex) float¶
Returns the derivative (density) at x.
Cumulative distribution function of the normal distribution.
cdf = ql.CumulativeNormalDistribution()
cdf(0.0) # 0.5
cdf(1.96) # ~0.975
InverseCumulativeNormal¶
- class pyquantlib.InverseCumulativeNormal¶
Bases:
pybind11_objectInverse cumulative normal distribution function.
- static standard_value(x: SupportsFloat | SupportsIndex) float¶
Returns the inverse for standard normal (average=0, sigma=1).
- __init__(average: SupportsFloat | SupportsIndex = 0.0, sigma: SupportsFloat | SupportsIndex = 1.0) None¶
Constructs InverseCumulativeNormal.
Inverse of the cumulative normal distribution (quantile function).
inv = ql.InverseCumulativeNormal()
inv(0.5) # 0.0
inv(0.975) # ~1.96
# Static method for standard normal
ql.InverseCumulativeNormal.standard_value(0.975) # ~1.96
BivariateCumulativeNormalDistribution¶
- class pyquantlib.BivariateCumulativeNormalDistribution¶
Bases:
pybind11_objectCumulative bivariate normal distribution (West 2004).
- __init__(rho: SupportsFloat | SupportsIndex) None¶
Constructs BivariateCumulativeNormalDistribution with correlation rho.
Cumulative bivariate normal distribution with given correlation.
bvn = ql.BivariateCumulativeNormalDistribution(rho=0.5)
bvn(0.0, 0.0) # P(X<=0, Y<=0) with correlation 0.5
1-D Solvers¶
Root-finding algorithms for one-dimensional functions.
Brent¶
- class pyquantlib.Brent¶
Bases:
pybind11_objectBrent 1-D solver.
- setLowerBound(lowerBound: SupportsFloat | SupportsIndex) None¶
Sets lower bound for the function domain.
- setMaxEvaluations(evaluations: SupportsInt | SupportsIndex) None¶
Sets maximum number of function evaluations.
- setUpperBound(upperBound: SupportsFloat | SupportsIndex) None¶
Sets upper bound for the function domain.
- solve(*args, **kwargs)¶
Overloaded function.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float
Finds root with automatic bracketing.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, xMin: SupportsFloat | SupportsIndex, xMax: SupportsFloat | SupportsIndex) -> float
Finds root within explicit bracket.
Brent’s method combines bisection, secant, and inverse quadratic interpolation.
solver = ql.Brent()
root = solver.solve(lambda x: x**2 - 4, 1e-10, 1.0, 0.0, 10.0) # 2.0
Bisection¶
- class pyquantlib.Bisection¶
Bases:
pybind11_objectBisection 1-D solver.
- setLowerBound(lowerBound: SupportsFloat | SupportsIndex) None¶
Sets lower bound for the function domain.
- setMaxEvaluations(evaluations: SupportsInt | SupportsIndex) None¶
Sets maximum number of function evaluations.
- setUpperBound(upperBound: SupportsFloat | SupportsIndex) None¶
Sets upper bound for the function domain.
- solve(*args, **kwargs)¶
Overloaded function.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float
Finds root with automatic bracketing.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, xMin: SupportsFloat | SupportsIndex, xMax: SupportsFloat | SupportsIndex) -> float
Finds root within explicit bracket.
Simple bisection method. Robust but slower than Brent.
Secant¶
- class pyquantlib.Secant¶
Bases:
pybind11_objectSecant 1-D solver.
- setLowerBound(lowerBound: SupportsFloat | SupportsIndex) None¶
Sets lower bound for the function domain.
- setMaxEvaluations(evaluations: SupportsInt | SupportsIndex) None¶
Sets maximum number of function evaluations.
- setUpperBound(upperBound: SupportsFloat | SupportsIndex) None¶
Sets upper bound for the function domain.
- solve(*args, **kwargs)¶
Overloaded function.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float
Finds root with automatic bracketing.
solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, xMin: SupportsFloat | SupportsIndex, xMax: SupportsFloat | SupportsIndex) -> float
Finds root within explicit bracket.
Secant method. Faster convergence than bisection, does not require derivative.
Newton¶
- class pyquantlib.Newton¶
Bases:
pybind11_objectNewton 1-D solver (requires derivative function).
- setLowerBound(lowerBound: SupportsFloat | SupportsIndex) None¶
Sets lower bound for the function domain.
- setMaxEvaluations(evaluations: SupportsInt | SupportsIndex) None¶
Sets maximum number of function evaluations.
- setUpperBound(upperBound: SupportsFloat | SupportsIndex) None¶
Sets upper bound for the function domain.
- solve(*args, **kwargs)¶
Overloaded function.
solve(f: collections.abc.Callable, derivative: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float
Finds root with automatic bracketing.
solve(f: collections.abc.Callable, derivative: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, xMin: SupportsFloat | SupportsIndex, xMax: SupportsFloat | SupportsIndex) -> float
Finds root within explicit bracket.
Newton-Raphson method. Requires a separate derivative function.
solver = ql.Newton()
root = solver.solve(
lambda x: x**2 - 4, # f(x)
lambda x: 2 * x, # f'(x)
1e-10, 1.0, 0.0, 10.0,
)
All solvers support two calling conventions:
# Automatic bracketing (guess + step)
root = solver.solve(f, accuracy, guess, step)
# Explicit bracket
root = solver.solve(f, accuracy, guess, xMin, xMax)
Common methods: setMaxEvaluations(n), setLowerBound(x), setUpperBound(x).
ODE Solvers¶
AdaptiveRungeKutta¶
- class pyquantlib.AdaptiveRungeKutta¶
Bases:
pybind11_objectAdaptive step-size Runge-Kutta ODE integrator (Cash-Karp method).
- __init__(eps: SupportsFloat | SupportsIndex = 1e-06, h1: SupportsFloat | SupportsIndex = 0.0001, hmin: SupportsFloat | SupportsIndex = 0.0) None¶
Constructs with prescribed error eps, initial step h1, and minimum step hmin.
- solve1d(ode: collections.abc.Callable[[SupportsFloat | SupportsIndex, SupportsFloat | SupportsIndex], float], y1: SupportsFloat | SupportsIndex, x1: SupportsFloat | SupportsIndex, x2: SupportsFloat | SupportsIndex) float¶
Integrates 1-dimensional ODE from x1 to x2 with initial condition y(x1) = y1.
Adaptive step-size Runge-Kutta ODE integrator using the Cash-Karp method.
rk = ql.AdaptiveRungeKutta(eps=1e-8)
# 1-D ODE: y' = f(x, y)
import math
result = rk.solve1d(lambda x, y: y, 1.0, 0.0, 1.0) # y' = y => e
print(result) # ~2.71828
# N-D ODE system: y' = F(x, y)
result = rk(lambda x, y: [y[1], -y[0]], [1.0, 0.0], 0.0, math.pi)
print(result) # ~[-1, 0] (harmonic oscillator)