Math Module

See also

NumPy Interoperability for detailed NumPy interoperability documentation.

Linear Algebra

Array

class pyquantlib.Array

Bases: pybind11_object

1-dimensional array of Real values.

__init__(*args, **kwargs)

Overloaded function.

  1. __init__() -> None

Default constructor (empty array).

  1. __init__(size: SupportsInt | SupportsIndex) -> None

Creates an array of given size.

  1. __init__(size: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None

Creates an array of given size with all elements set to value.

  1. __init__(iterable: collections.abc.Iterable) -> None

Creates an array from a Python iterable.

  1. __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.

back() float

Returns the last element.

empty() bool

Returns true if the array is empty.

fill(value: SupportsFloat | SupportsIndex) None

Fills the array with a value.

front() float

Returns the first element.

resize(*args, **kwargs)

Overloaded function.

  1. resize(size: SupportsInt | SupportsIndex) -> None

Resizes the array.

  1. resize(size: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None

Resizes the array, filling new elements with value.

size() int

Returns the number of elements.

swap(other: Array) None

Swaps contents with another array.

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_object

2-dimensional matrix of Real values.

__init__(*args, **kwargs)

Overloaded function.

  1. __init__() -> None

Default constructor (empty matrix).

  1. __init__(rows: SupportsInt | SupportsIndex, columns: SupportsInt | SupportsIndex) -> None

Creates a zero-filled matrix.

  1. __init__(rows: SupportsInt | SupportsIndex, columns: SupportsInt | SupportsIndex, value: SupportsFloat | SupportsIndex) -> None

Creates a matrix filled with value.

  1. __init__(numpy_array: Annotated[numpy.ArrayLike, numpy.float64]) -> None

Creates a matrix from a 2D NumPy array.

  1. __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.

columns() int

Returns the number of columns.

diagonal() Array

Returns the diagonal as an Array.

empty() bool

Returns true if the matrix is empty.

rows() int

Returns the number of rows.

swap(other: Matrix) None

Swaps contents with another matrix.

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_object

Singular value decomposition of a matrix.

S() Matrix

Returns the diagonal matrix of singular values.

U() Matrix

Returns the U matrix.

V() Matrix

Returns the V matrix.

__init__(matrix: Matrix) None

Constructs SVD from a matrix.

cond() float

Returns the condition number.

norm2() float

Returns the 2-norm (largest singular value).

rank() int

Returns the numerical rank.

singularValues() Array

Returns the singular values.

solveFor(b: Array) Array

Solves Ax = b using the SVD.

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_object

Symmetric Schur decomposition (eigenvalue decomposition).

__init__(matrix: Matrix) None

Constructs decomposition from a symmetric matrix.

eigenvalues() Array

Returns the eigenvalues in decreasing order.

eigenvectors() Matrix

Returns the eigenvector matrix.

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: Interpolation

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.

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: Interpolation

Log-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: Interpolation

Backward-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: Interpolation

Cubic 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: Interpolation

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.

Convenience class for natural cubic spline (second derivative = 0 at boundaries).

MonotonicCubicNaturalSpline

class pyquantlib.MonotonicCubicNaturalSpline

Bases: Interpolation

Monotonic 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_object

Derivative 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_object

Boundary 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: Interpolation

Forward-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: Interpolation

Lagrange 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: Interpolation2D

Bilinear 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: Interpolation2D

Bicubic 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: Interpolation

Chebyshev 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.

  1. __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].

  1. __init__(y: Array, pointsType: ChebyshevPointsType = <ChebyshevPointsType.SecondKind: 1>) -> None

Constructs from pre-computed y values at Chebyshev nodes.

nodes() Array

Returns the Chebyshev nodes.

updateY(y: Array) None

Updates the y values.

class pyquantlib.ChebyshevPointsType

Bases: pybind11_object

Chebyshev 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_object

Richardson 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_object

Statistics tool with empirical-distribution risk measures.

__init__() None
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.

  1. addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None

Adds a sequence of data to the set.

  1. 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.

downsideDeviation() float

Returns the downside deviation.

downsideVariance() float

Returns the variance of observations below 0.

errorEstimate() float

Returns the error estimate on the mean value.

expectedShortfall(percentile: SupportsFloat | SupportsIndex) float

Returns the expected shortfall at a given percentile.

gaussianAverageShortfall(target: SupportsFloat | SupportsIndex) float

Returns the gaussian-assumption averaged shortfallness.

gaussianDownsideDeviation() float

Returns the gaussian-assumption downside deviation.

gaussianDownsideVariance() float

Returns the gaussian-assumption downside variance.

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.

kurtosis() float

Returns the excess kurtosis.

max() float

Returns the maximum sample value.

mean() float

Returns the mean.

min() float

Returns the minimum sample value.

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.

reset() None

Resets the data to a null set.

samples() int

Returns the number of samples collected.

semiDeviation() float

Returns the semi deviation.

semiVariance() float

Returns the variance of observations below the mean.

shortfall(target: SupportsFloat | SupportsIndex) float

Returns the probability of missing the target.

skewness() float

Returns the skewness.

sort() None

Sorts the data set in increasing order.

standardDeviation() float

Returns the standard deviation.

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.

variance() float

Returns the variance.

weightSum() float

Returns the sum of data weights.

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_object

Statistics tool based on incremental accumulation (boost accumulators).

__init__() None
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.

  1. addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None

Adds a sequence of data to the set.

  1. addSequence(values: collections.abc.Sequence[SupportsFloat | SupportsIndex], weights: collections.abc.Sequence[SupportsFloat | SupportsIndex]) -> None

Adds a sequence of data with weights.

downsideDeviation() float

Returns the downside deviation.

downsideSamples() int

Returns the number of negative samples collected.

downsideVariance() float

Returns the downside variance.

downsideWeightSum() float

Returns the sum of data weights for negative samples.

errorEstimate() float

Returns the error estimate on the mean value.

kurtosis() float

Returns the excess kurtosis.

max() float

Returns the maximum sample value.

mean() float

Returns the mean.

min() float

Returns the minimum sample value.

reset() None

Resets the data to a null set.

samples() int

Returns the number of samples collected.

skewness() float

Returns the skewness.

standardDeviation() float

Returns the standard deviation.

variance() float

Returns the variance.

weightSum() float

Returns the sum of data 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_object

N-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.

correlation() Matrix

Returns the correlation matrix.

covariance() Matrix

Returns the covariance matrix.

downsideDeviation() list[float]

Returns the downside deviation for each dimension.

downsideVariance() list[float]

Returns the downside variance for each dimension.

errorEstimate() list[float]

Returns the error estimate 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.

kurtosis() list[float]

Returns the kurtosis for each dimension.

max() list[float]

Returns the maximum for each dimension.

mean() list[float]

Returns the mean for each dimension.

min() list[float]

Returns the minimum 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.

samples() int

Returns the number of samples collected.

semiDeviation() list[float]

Returns the semi deviation for each dimension.

semiVariance() list[float]

Returns the semi variance for each dimension.

shortfall(target: SupportsFloat | SupportsIndex) list[float]

Returns the shortfall for each dimension.

size() int

Returns the dimension.

skewness() list[float]

Returns the skewness for each dimension.

standardDeviation() list[float]

Returns the standard deviation for each dimension.

valueAtRisk(percentile: SupportsFloat | SupportsIndex) list[float]

Returns the VaR for each dimension.

variance() list[float]

Returns the variance for each dimension.

weightSum() float

Returns the sum of data weights.

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_object

Criteria to end optimization processes.

class Type

Bases: pybind11_object

End criteria type enumeration.

Members:

None_

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: OptimizationMethod

Levenberg-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: OptimizationMethod

Multi-dimensional simplex optimization method.

__init__(lambda_: SupportsFloat | SupportsIndex) None

Constructs with the characteristic length scale lambda.

lambda_() float

Returns the characteristic length scale.

Nelder-Mead simplex optimization method.

optimizer = ql.Simplex(0.1)

ConjugateGradient

class pyquantlib.ConjugateGradient

Bases: OptimizationMethod

Fletcher-Reeves-Polak-Ribiere conjugate gradient optimization method.

__init__() None

Constructs with default line search.

SteepestDescent

class pyquantlib.SteepestDescent

Bases: OptimizationMethod

Multi-dimensional steepest descent optimization method.

__init__() None

Constructs with default line search.

BFGS

class pyquantlib.BFGS

Bases: OptimizationMethod

Broyden-Fletcher-Goldfarb-Shanno optimization method.

__init__() None

Constructs with default line search.

DifferentialEvolution

class pyquantlib.DifferentialEvolution

Bases: OptimizationMethod

Differential 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_object

Configuration for the differential evolution optimizer.

__init__() None

Constructs with default settings.

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_object

Differential 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_object

Differential 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_object

Constrained 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.

currentValue() Array

Returns the current parameter values.

functionValue() float

Returns the current function value.

value(x: Array) float

Evaluates the cost function at the given point.

values(x: Array) Array

Evaluates the cost function values at the given point.

Constraints

class pyquantlib.NoConstraint

Bases: Constraint

No constraint (always satisfied).

__init__() None
class pyquantlib.PositiveConstraint

Bases: Constraint

Constraint enforcing positive values.

__init__() None
class pyquantlib.BoundaryConstraint

Bases: Constraint

Constraint enforcing values within bounds.

__init__(low: SupportsFloat | SupportsIndex, high: SupportsFloat | SupportsIndex) None
class pyquantlib.CompositeConstraint

Bases: Constraint

Composite of two constraints.

__init__(c1: base.Constraint, c2: base.Constraint) None

Note

Abstract base classes like Constraint, OptimizationMethod, and CostFunction are available in pyquantlib.base for subclassing.

Distributions

NormalDistribution

class pyquantlib.NormalDistribution

Bases: pybind11_object

Normal (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_object

Cumulative 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_object

Inverse 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_object

Cumulative 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_object

Brent 1-D solver.

__init__() None
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.

  1. solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float

Finds root with automatic bracketing.

  1. 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_object

Bisection 1-D solver.

__init__() None
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.

  1. solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float

Finds root with automatic bracketing.

  1. 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_object

Secant 1-D solver.

__init__() None
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.

  1. solve(f: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float

Finds root with automatic bracketing.

  1. 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_object

Newton 1-D solver (requires derivative function).

__init__() None
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.

  1. solve(f: collections.abc.Callable, derivative: collections.abc.Callable, accuracy: SupportsFloat | SupportsIndex, guess: SupportsFloat | SupportsIndex, step: SupportsFloat | SupportsIndex) -> float

Finds root with automatic bracketing.

  1. 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_object

Adaptive 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)