Skip to content
LeetQuant
QR01 Python for Quantitative Research

QR01 · Python for Quantitative Research · Lesson 3 of 5

SciPy: Optimisation, Statistics, Linear Algebra

scipy.optimize (minimize with bounds and constraints, root_scalar, curve_fit), scipy.stats distributions and tests and how to read them, and scipy.linalg solve and Cholesky instead of explicit inverses.

18 min

Objective

SciPy is where research code goes once NumPy arithmetic is not enough: fitting, inverting, testing and solving. The library calls are short; the skill is choosing the right routine, giving it what it needs (bounds, gradients, a bracket, good scaling) and checking the result rather than trusting it. The examples ran on SciPy 1.17.

scipy.optimize

minimize(fun, x0, ...) finds a local minimum. The method follows from the problem:

ProblemMethodNotes
Smooth, unconstrainedBFGS (the default)Quasi-Newton; supply jac if you can
Box bounds onlyL-BFGS-BAlso the default when bounds is given
Equalities, inequalities, boundsSLSQP or trust-constrConstraints as dicts or constraint objects
Non-smooth or noisyNelder-Mead, PowellSlow, no gradients, small dimension only

Habits that prevent wrong answers: check res.success and res.message; pass an analytic gradient (jac=), since finite differences cost nn extra evaluations and add noise; scale parameters to similar magnitudes (optimise log⁡σ\log\sigma rather than σ\sigma when it spans orders of magnitude, which also enforces positivity); restart from several x0 for non-convex problems; and know that the default tolerances are loose.

root_scalar(f, bracket=[a, b], method="brentq") solves f(x)=0f(x) = 0 in one dimension. With a sign-changing bracket, Brent's method is guaranteed to converge and is usually fast. Implied volatility of an at-the-money one-year call priced at 10 on spot 100 with zero rates:

from scipy import optimize
from scipy.stats import norm
import numpy as np

def bs_call(S, K, T, r, sig):
    d1 = (np.log(S / K) + (r + 0.5 * sig**2) * T) / (sig * np.sqrt(T))
    return S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d1 - sig * np.sqrt(T))

sol = optimize.root_scalar(lambda s: bs_call(100, 100, 1.0, 0.0, s) - 10.0,
                           bracket=[1e-4, 5.0], method="brentq")
print(sol.root, sol.iterations, sol.converged)   # 0.2513226937101481 7 True

(The rule of thumb C≈0.4 σSTC \approx 0.4\,\sigma S\sqrt{T} gives σ≈0.25\sigma \approx 0.25, a useful sanity check.)

curve_fit(model, x, y, p0=...) is nonlinear least squares with a covariance estimate of the parameters. Fitting ae−k/τa e^{-k/\tau} to ten noisy autocorrelations generated with a=0.6a = 0.6, τ=3\tau = 3 returned a^=0.603±0.019\hat a = 0.603 \pm 0.019, τ^=2.99±0.11\hat\tau = 2.99 \pm 0.11. The standard errors assume independent, equal-variance residuals, which autocorrelation estimates at adjacent lags are not, so treat them as optimistic.

Worked example

minimum-variance portfolio, closed form versus optimiser

Three assets have volatilities 20%, 15%, 30% and correlations ρ12=0.9\rho_{12} = 0.9, ρ13=0.2\rho_{13} = 0.2, ρ23=0.4\rho_{23} = 0.4. Find the fully invested minimum-variance portfolio (weights sum to 1) in closed form and with minimize, then add a long-only constraint.

Show solution

Minimising w⊤Σww^\top \Sigma w subject to 1⊤w=1\mathbf 1^\top w = 1 with a Lagrange multiplier gives w∗=Σ−11/(1⊤Σ−11)w^\ast = \Sigma^{-1}\mathbf 1 / (\mathbf 1^\top \Sigma^{-1}\mathbf 1). Compute Σ−11\Sigma^{-1}\mathbf 1 by solving Σx=1\Sigma x = \mathbf 1, not by inverting.

import numpy as np
from scipy import linalg, optimize

vols = np.array([0.20, 0.15, 0.30])
corr = np.array([[1.0, 0.9, 0.2],
                 [0.9, 1.0, 0.4],
                 [0.2, 0.4, 1.0]])
cov = corr * np.outer(vols, vols)
ones = np.ones(3)

x = linalg.solve(cov, ones, assume_a="pos")
w_closed = x / x.sum()

def var(w):
    return w @ cov @ w

def grad(w):
    return 2 * cov @ w

budget = {"type": "eq", "fun": lambda w: w.sum() - 1}
res = optimize.minimize(var, ones / 3, jac=grad, method="SLSQP", constraints=[budget])
res_tight = optimize.minimize(var, ones / 3, jac=grad, method="SLSQP",
                              constraints=[budget], tol=1e-12)
res_long = optimize.minimize(var, ones / 3, jac=grad, method="SLSQP",
                             constraints=[budget], bounds=[(0, 1)] * 3, tol=1e-12)

print(w_closed.round(4), np.sqrt(var(w_closed)).round(4))   # [-0.55    1.5667 -0.0167] 0.1418
print(res.success, res.x.round(4))                          # True [-0.5498  1.5688 -0.0191]
print(res_tight.x.round(4))                                 # [-0.55    1.5667 -0.0167]
print(res_long.x.round(4), np.sqrt(res_long.fun).round(4))  # [0.     0.9412 0.0588] 0.1491

Three lessons in one output:

  1. success=True does not mean accurate. With default tolerances SLSQP stopped at weights off in the third decimal, because the objective is flat near the optimum. Tightening tol recovers the closed form. Always compare an optimiser with a closed form when one exists.
  2. The unconstrained answer shorts asset 1. Assets 1 and 2 are 0.9 correlated and asset 2 is less volatile, so the optimiser holds 157% of asset 2 against −55% of asset 1 to hedge the common factor. Volatility is 14.18%.
  3. With the long-only bound, asset 1 drops out and the problem reduces to two assets. The two-asset formula w2=(σ32−ρσ2σ3)/(σ22+σ32−2ρσ2σ3)=(0.09−0.018)/(0.0225+0.09−0.036)=0.072/0.0765=0.9412w_2 = (\sigma_3^2 - \rho\sigma_2\sigma_3)/(\sigma_2^2 + \sigma_3^2 - 2\rho\sigma_2\sigma_3) = (0.09 - 0.018)/(0.0225 + 0.09 - 0.036) = 0.072/0.0765 = 0.9412 matches, and the volatility rises to 14.91%.

scipy.stats

Every distribution is an object with the same methods: pdf/pmf, cdf, sf (survival, 1−F1 - F), ppf (quantile, F−1F^{-1}), isf (inverse survival), logpdf, rvs, fit, mean, var. Freeze parameters once (t4 = stats.t(df=4)) and reuse. Points worth knowing:

  • Use sf for tails. 1 - stats.norm.cdf(9) is 0.0, because the cdf rounds to 1; stats.norm.sf(9) is 1.13e-19. Likewise isf(1e-10) gives the extreme quantile 6.36 directly.
  • Fat tails are large. For a Student tt with 4 degrees of freedom, sf(4) is 0.0081, against 3.2e-5 for the normal: 250 times more likely. Note t(4).var() is 2, so a raw t4t_4 is not unit-variance; rescale by 1/21/\sqrt 2 before comparing like with like.
  • stats.t.ppf(0.975, df=4) is 2.776, the critical value used in small-sample confidence intervals.

Tests return a statistic and a p-value. Read them with their assumptions:

TestQuestionMain caveat
ttest_1samp(r, 0)Is the mean return non-zero?Assumes independent observations; autocorrelation inflates tt
jarque_beraAre skewness and kurtosis normal?With thousands of returns it rejects almost always
kstest(x, "norm", args=...)Does xx follow this exact distribution?p-values are wrong if the parameters were estimated from xx (use a Lilliefors-type correction)
pearsonr, spearmanrIs there correlation?Pearson is dominated by outliers; Spearman is rank-based

A p-value is P(data this extreme∣H0)P(\text{data this extreme} \mid H_0), not the probability the strategy works, and testing many variants inflates false positives.

Worked example

is this strategy's mean return significant?

A strategy has 1,000 daily returns with sample mean 0.0500% and sample standard deviation 1.0007%. The returns are fat-tailed. Is the mean significantly different from zero, and what is the annualised Sharpe ratio?

Show solution
from scipy import stats

rng = np.random.default_rng(1)
r = 0.0004 + 0.01 * rng.standard_t(df=4, size=1000) / np.sqrt(2)   # t4 rescaled to sd 1%
print(r.mean(), r.std(ddof=1))          # 0.0004998... 0.0100065...
tt = stats.ttest_1samp(r, 0.0)
print(tt.statistic, tt.pvalue)          # 1.5795 0.1145
print(np.sqrt(252) * r.mean() / r.std(ddof=1))   # 0.7929
print(stats.jarque_bera(r).pvalue)      # 1.1e-220

The tt statistic is rˉ/(s/n)=(0.0005/0.0100065)1000≈1.58\bar r / (s/\sqrt n) = (0.0005/0.0100065)\sqrt{1000} \approx 1.58, with a two-sided p-value of 0.11: not significant at 5%. Notice the identity

t=SRdailyn=SRannualyears,t = \text{SR}_{\text{daily}} \sqrt n = \text{SR}_{\text{annual}} \sqrt{\text{years}} ,

so 0.79×1000/252=0.79×1.99≈1.580.79 \times \sqrt{1000/252} = 0.79 \times 1.99 \approx 1.58. A Sharpe ratio of 0.8 needs about (2/0.8)2≈6(2/0.8)^2 \approx 6 years of data to reach t=2t = 2. That is the single most useful number to quote in an interview about backtest significance.

The fat tails do not invalidate the tt-test here: with n=1000n = 1000 the sample mean is close to normal by the central limit theorem, and Jarque–Bera's tiny p-value only confirms what we built in (the sample excess kurtosis is about 4.9). What would invalidate it is serial correlation or the strategy having been selected from many tried.

scipy.linalg: solve, do not invert

To compute A−1bA^{-1}b, call linalg.solve(A, b). It factorises A=LUA = LU (about 23n3\tfrac23 n^3 flops) and does two triangular solves; forming inv(A) costs about 2n32n^3 and then a matrix–vector product, and is less accurate. For a symmetric positive definite matrix such as a covariance, assume_a="pos" uses a Cholesky factorisation A=LL⊤A = LL^\top at about 13n3\tfrac13 n^3 flops. When the same matrix is used with many right-hand sides, factor once with cho_factor and reuse it with cho_solve:

# n = 2000 SPD matrix, one machine, best of 5
linalg.inv(S) @ b                     # 138 ms
linalg.solve(S, b)                    # 68 ms
linalg.solve(S, b, assume_a="pos")    # 58 ms
c = linalg.cho_factor(S)
linalg.cho_solve(c, b)                # 3.7 ms per extra right-hand side

Cholesky also does two research jobs on its own:

  • Correlated simulation. If ZZ has independent standard normal entries, LZLZ has covariance LL⊤=ΣLL^\top = \Sigma.
  • A validity test. It fails exactly when the matrix is not positive definite. A hand-edited "correlation matrix" with ρ12=ρ13=0.9\rho_{12} = \rho_{13} = 0.9 and ρ23=−0.9\rho_{23} = -0.9 raises LinAlgError (its eigenvalues are −0.8,1.9,1.9-0.8, 1.9, 1.9): no three random variables can have those correlations.

For regression use linalg.lstsq (or np.linalg.lstsq), which works from the design matrix through an orthogonal factorisation instead of forming X⊤XX^\top X; the next lesson shows why that matters numerically.

Knowledge check

You need P(Z > 10) for a standard normal Z. Which call returns a usable non-zero number?

Knowledge check

A backtest has an annualised Sharpe ratio of 1.0 over 4 years of daily data (independent returns). What is the approximate t-statistic of its mean return?

Knowledge check

minimize returns success=True for a portfolio problem, but the weights differ from the known closed form in the third decimal. What is the most likely explanation?

Knowledge check

You must compute Σ⁻¹μ for a 3,000 × 3,000 covariance matrix and 50 different μ vectors. What is the best approach?

Key takeaways

  • Pick the minimize method from the constraints (BFGS, L-BFGS-B, SLSQP); pass gradients, scale parameters, check success and compare with a closed form or a tighter tolerance.
  • root_scalar with a bracket and brentq is the robust one-dimensional solver; curve_fit standard errors assume independent residuals.
  • Use sf/isf for tails. Every test's p-value is conditional on its assumptions, especially independence.
  • t≈SRannualyearst \approx \text{SR}_{\text{annual}}\sqrt{\text{years}}: a Sharpe ratio of 1 needs about 4 years to reach t=2t = 2.
  • Solve, do not invert. Cholesky for covariances: fast solves, correlated simulation and a positive-definiteness test.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).