quanttoolbox.maths¶
maths.numerical_diff¶
Python alternatives
Hybrid: numdifftools uses adaptive step sizing and Richardson extrapolation — meaningfully more accurate than this module's fixed-step approach. Worth using where precision matters; keep this module for the magnitude-scaled step convention already wired into econometrics.estimation/whittle.
quanttoolbox.maths.numerical_diff
¶
Numerical gradient, Jacobian, and Hessian, with an adaptive magnitude-scaled step size.
Ported from QuantToolBox/maths/{numerical_gradient,numerical_hessian, numerical_jacobian,sign_operator}.m
Translation notes:
numerical_gradient.mhandles three cases based on output shape (scalar-output gradient, vector-output-matching-input gradient, and general Jacobian) via a single dispatch; here this is split intonumerical_gradient(scalar-valued fun) andnumerical_jacobian(vector-valued fun) for clarity, matching how they're actually called elsewhere in this package.- The step size dh is scaled per-parameter by
max(|x0_i|, 0.01) * sign(x0_i)(falling back to a fixed direction when x0_i == 0), exactly as in the original, so the step is proportional to each parameter's magnitude rather than a fixed absolute value. - method="forward" (default) or "central" difference, matching the original's method=1/2.
numerical_gradient(fun, x0, dh=1e-08, method='forward')
¶
Numerical gradient of a scalar-valued function fun at x0 (each parameter perturbed one at a time, holding the others fixed).
Original: maths/numerical_gradient.m (scalar-output case)
Source code in src/quanttoolbox/maths/numerical_diff.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
numerical_hessian(fun, x0, dh=6e-05)
¶
Numerical Hessian of a scalar-valued function fun at x0, via second-order finite differences.
Original: maths/numerical_hessian.m
Source code in src/quanttoolbox/maths/numerical_diff.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
numerical_jacobian(fun, x0, dh=1e-08, method='forward')
¶
Numerical Jacobian of a vector-valued function fun at x0: fun(x0) has shape (n,), x0 has shape (p,), result has shape (n, p).
Original: maths/{numerical_gradient,numerical_jacobian}.m (Jacobian case)
Source code in src/quanttoolbox/maths/numerical_diff.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
sign_operator(x)
¶
Sign function: 1 if x>0, -1 if x<0, 0 if x==0 (equivalent to numpy.sign, provided here for direct call-site compatibility with the original).
Original: maths/sign_operator.m
Source code in src/quanttoolbox/maths/numerical_diff.py
137 138 139 140 141 142 143 144 145 | |
Examples¶
Numerical gradient and Hessian vs. analytical, near a small coordinate — maths/hess2.py
"""Translated from Examples/maths/hess2.m -- numerical gradient and Hessian
of the same function as grad2.m, at a point with a very small second
coordinate (x2=1e-5), compared against their known analytical forms."""
import numpy as np
from quanttoolbox.maths.numerical_diff import numerical_gradient, numerical_hessian
def fun(x):
x1, x2 = x[0], x[1]
return 3 * x1**2 + 6 * x1 + 7 + np.log(x1) + x1 * x2 + x2**2 + np.exp(x2)
def grad_analytical(x):
x1, x2 = x[0], x[1]
return np.array([6 * x1 + 6 + 1.0 / x1 + x2, x1 + 2 * x2 + np.exp(x2)])
def hess_analytical(x):
x1, x2 = x[0], x[1]
h = np.zeros((2, 2))
h[0, 0] = 6 - 1.0 / (x1**2)
h[1, 0] = 1.0
h[0, 1] = h[1, 0]
h[1, 1] = 2 + np.exp(x2)
return h
x0 = np.array([0.5, 0.00001])
g = grad_analytical(x0)
h = hess_analytical(x0)
g1 = numerical_gradient(fun, x0)
print("Gradient, forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
h1 = numerical_hessian(fun, x0, dh=6e-5)
print("\nNumerical Hessian:")
print(h1)
print("\nAnalytical Hessian:")
print(h)
Numerical gradient of a two-variable scalar function — maths/grad2.py
"""Translated from Examples/maths/grad2.m -- numerical vs. analytical
gradient of a scalar function of two variables that mixes polynomial,
log, and exponential terms."""
import numpy as np
from quanttoolbox.maths.numerical_diff import numerical_gradient
def fun(x):
x1, x2 = x[0], x[1]
return 3 * x1**2 + 6 * x1 + 7 + np.log(x1) + x1 * x2 + x2**2 + np.exp(x2)
def grad_analytical(x):
x1, x2 = x[0], x[1]
return np.array([6 * x1 + 6 + 1.0 / x1 + x2, x1 + 2 * x2 + np.exp(x2)])
x0 = np.array([0.5, 0.001])
g = grad_analytical(x0)
g1 = numerical_gradient(fun, x0)
print("Forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
g1 = numerical_gradient(fun, x0, method="central")
print("Central difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
Numerical gradient of an elementwise function via a sum trick — maths/grad3.py
"""Translated from Examples/maths/grad3.m -- numerical vs. analytical
gradient of the separable, elementwise function f(x) = x^2 * exp(x^2/3).
The original MATLAB `numerical_gradient` accepts an elementwise-vectorized
function and returns an elementwise gradient. This package's
`numerical_gradient` is scalar-valued only (see `numerical_jacobian` for
the general vector case), so the elementwise function is summed first --
since each term depends on a single x_i, the gradient of the sum w.r.t.
x_i equals the elementwise derivative at x_i (see also grad1.m's
translation in building_blocks.md, which uses the same trick)."""
import numpy as np
from quanttoolbox.maths.numerical_diff import numerical_gradient
def fun_elementwise(x):
return x**2 * np.exp(x**2 / 3)
def fun_sum(x):
return np.sum(fun_elementwise(x))
def grad_analytical(x):
return 2 * x * np.exp(x**2 / 3) + x**2 * (2 * x / 3) * np.exp(x**2 / 3)
x0 = np.array([2.5, 3.0, 3.5])
g = grad_analytical(x0)
g1 = numerical_gradient(fun_sum, x0)
print("Forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
g1 = numerical_gradient(fun_sum, x0, method="central")
print("Central difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
Numerical gradient, same elementwise-sum trick as grad3 — maths/grad4.py
"""Translated from Examples/maths/grad4.m -- numerical vs. analytical
gradient of the separable, elementwise function f(x) = 2*x * exp(x^2/3).
Same elementwise-via-sum approach as grad3.py's translation (see that
file's docstring for why)."""
import numpy as np
from quanttoolbox.maths.numerical_diff import numerical_gradient
def fun_elementwise(x):
return 2 * x * np.exp(x**2 / 3)
def fun_sum(x):
return np.sum(fun_elementwise(x))
def grad_analytical(x):
return 2 * np.exp(x**2 / 3) + 2 * x * (2 * x / 3) * np.exp(x**2 / 3)
x0 = np.array([2.5, 3.0, 3.5])
g = grad_analytical(x0)
g1 = numerical_gradient(fun_sum, x0)
print("Forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
g1 = numerical_gradient(fun_sum, x0, method="central")
print("Central difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
Numerical gradient, scalar vs. explicit-sum function forms — maths/grad5.py
"""Translated from Examples/maths/grad5.m -- two equivalent formulations of
the same gradient: fun(x) = 0.5*x'x + exp(x)'*(1/x) (already scalar-valued,
so it needs no summing trick), and fun2(x) = sum(0.5*x_i^2 + exp(x_i)/x_i)
(explicitly written as a sum of separable terms). Both have gradient
g(x) = x + exp(x) .* (1/x - 1/x^2), confirming the two formulations agree
numerically."""
import numpy as np
from quanttoolbox.maths.numerical_diff import numerical_gradient
def fun(x):
return 0.5 * x @ x + np.exp(x) @ (1.0 / x)
def fun2(x):
return np.sum(0.5 * x * x + np.exp(x) / x)
def grad_analytical(x):
return x + np.exp(x) * (1.0 / x - 1.0 / (x * x))
x0 = np.array([1.0, 2.0, 3.0])
g = grad_analytical(x0)
print("fun(x) = 0.5*x'x + exp(x)'*(1/x)")
g1 = numerical_gradient(fun, x0)
print("Forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
g1 = numerical_gradient(fun, x0, method="central")
print("Central difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
print("\nfun2(x) = sum(0.5*x^2 + exp(x)/x) (same gradient, written as a sum)")
g1 = numerical_gradient(fun2, x0)
print("Forward difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
g1 = numerical_gradient(fun2, x0, method="central")
print("Central difference (numerical, analytical, |diff|):")
print(np.column_stack([g1, g, np.abs(g - g1)]))
print("d =", np.max(np.abs(g - g1)))
maths.simulation¶
Python alternatives
compute_ewma: hybrid — pandas.DataFrame.ewm() is highly optimized but uses a different parameterization (alpha/span/halflife vs. this module's mean-reversion-rate lambda_ + explicit dt); a small translation layer would be needed to switch. GBM simulation and the Riccati/Lyapunov solvers: keep — the latter already route through scipy.linalg.solve_continuous_are/solve_lyapunov (that is the switch), and GBM simulation has no equally-simple standard-library equivalent (QuantLib-Python is a much heavier dependency).
quanttoolbox.maths.simulation
¶
Geometric Brownian motion simulation, EWMA-based mean/vol estimation, volatility targeting, and continuous algebraic Riccati / Lyapunov equation solvers.
Ported from QuantToolBox/maths/{simulate_gbm,simulate_gbm2, simulate_multi_gbm,compute_ewma,momentum_ewma,volatility_target, algebraic_riccati_equation,lyapunov_equation}.m
Translation notes:
algebraic_riccati_equation.m/lyapunov_equation.mhand-roll a Schur-decomposition solver and a Kronecker-product linear solve, respectively, for two classic control-theory equations thatscipy.linalgalready solves directly and robustly (solve_continuous_are,solve_lyapunov) -- used here instead of porting the custom solvers.simulate_multi_gbm.m's body is byte-identical tosimulate_gbm.m(single-asset simulation) despite taking a correlation parameterrhothat is never used -- this looks like an incomplete/unfinished implementation in the original rather than an intentional simplification.simulate_multi_gbmhere instead implements what the name and signature promise: a genuine N-asset correlated GBM simulation via Cholesky decomposition of the correlation matrix (generalizingsimulate_gbm2's 2-asset case, which is correctly implemented in the original and is ported as-is).momentum_ewmasimulates and analytically decomposes a simple EWMA-momentum trend-following strategy, matching the original's field names conceptually (renamed to snake_case, e.g.V_t->v_t/result.v_t) via aMomentumEWMAResultdataclass rather than a MATLAB-style long positional return tuple.
algebraic_riccati_equation(a, b, c)
¶
Solve the continuous algebraic Riccati equation A'X + XA - XBX + C = 0 (B assumed symmetric positive semi-definite).
Original: maths/algebraic_riccati_equation.m (reimplemented via scipy.linalg.solve_continuous_are -- see module docstring)
Source code in src/quanttoolbox/maths/simulation.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | |
compute_ewma(prices, lambda_mu, lambda_sigma=None, dt=1.0 / 260)
¶
Exponentially-weighted moving average mean and volatility of a return series (in the mean-reversion-rate parameterization: larger lambda means faster decay toward the new observation).
Original: maths/compute_ewma.m
Source code in src/quanttoolbox/maths/simulation.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
lyapunov_equation(a, c)
¶
Solve the Lyapunov equation AX + XA' = C.
Original: maths/lyapunov_equation.m (reimplemented via scipy.linalg.solve_lyapunov -- see module docstring)
Source code in src/quanttoolbox/maths/simulation.py
382 383 384 385 386 387 388 389 390 | |
momentum_ewma(prices, alpha, lambda_mu, lambda_sigma=None, dt=1.0 / 260, multiplier=1.0)
¶
Simulate and analytically decompose a simple EWMA-momentum trend-following strategy: exposure e_t = alpha * mu_t (position size proportional to the EWMA-estimated drift mu_t), applied with a one-period lag to next-period returns.
Returns both the actually-realized strategy wealth index (v_t,
from compounding the lagged-exposure-weighted returns) and a
continuous-time-motivated analytical approximation to it, decomposed
into a "gamma" component driven by changes in the squared EWMA drift
(g_t) and a "theta"/variance-drag component (g_small_t); their
product-equivalent sum is v_tilde_t, which approximates v_t.
Original: maths/momentum_ewma.m
Source code in src/quanttoolbox/maths/simulation.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
simulate_gbm(x0, mu, sigma, t, n_paths, rng=None)
¶
Simulate geometric Brownian motion paths (exact scheme, no discretization bias) for a single asset.
Original: maths/simulate_gbm.m
Returns an (n_times, n_paths) array.
Source code in src/quanttoolbox/maths/simulation.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
simulate_gbm2(x01, x02, mu1, mu2, sigma1, sigma2, rho, t, n_paths, rng=None)
¶
Simulate two correlated geometric Brownian motion processes (exact scheme).
Original: maths/simulate_gbm2.m
Source code in src/quanttoolbox/maths/simulation.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
simulate_multi_gbm(x0, mu, sigma, rho, t, n_paths, rng=None)
¶
Simulate N correlated geometric Brownian motion processes (exact scheme), via Cholesky decomposition of the correlation matrix rho.
Note: implemented as a genuine N-asset correlated simulator (see
module docstring for why this differs from the original, whose
simulate_multi_gbm.m body is identical to the uncorrelated
single-asset simulate_gbm.m despite taking a correlation
parameter).
Original: maths/simulate_multi_gbm.m (reimplemented -- see docstring)
Returns an (n_times, n_assets, n_paths) array.
Source code in src/quanttoolbox/maths/simulation.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
volatility_target(x_t, lambda_, vol_target, min_leverage=0.0, max_leverage=1.0, dt=1.0 / 260, multiplier=1.0)
¶
Apply a volatility-targeting overlay to a price series: scale daily returns by leverage = vol_target / (EWMA volatility), clipped to [min_leverage, max_leverage] and lagged by one period (leverage is set using yesterday's volatility estimate).
Original: maths/volatility_target.m
Source code in src/quanttoolbox/maths/simulation.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |