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:
| Problem | Method | Notes |
|---|---|---|
| Smooth, unconstrained | BFGS (the default) | Quasi-Newton; supply jac if you can |
| Box bounds only | L-BFGS-B | Also the default when bounds is given |
| Equalities, inequalities, bounds | SLSQP or trust-constr | Constraints as dicts or constraint objects |
| Non-smooth or noisy | Nelder-Mead, Powell | Slow, 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 extra evaluations and add noise; scale parameters to similar magnitudes (optimise rather than 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 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 gives , a useful sanity check.)
curve_fit(model, x, y, p0=...) is nonlinear least squares with a covariance estimate of the parameters. Fitting to ten noisy autocorrelations generated with , returned , . 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 , , . Find the fully invested minimum-variance portfolio (weights sum to 1) in closed form and with minimize, then add a long-only constraint.
Show solutionHide solution
Minimising subject to with a Lagrange multiplier gives . Compute by solving , 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:
success=Truedoes not mean accurate. With default tolerances SLSQP stopped at weights off in the third decimal, because the objective is flat near the optimum. Tighteningtolrecovers the closed form. Always compare an optimiser with a closed form when one exists.- 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%.
- With the long-only bound, asset 1 drops out and the problem reduces to two assets. The two-asset formula matches, and the volatility rises to 14.91%.
scipy.stats
Every distribution is an object with the same methods: pdf/pmf, cdf, sf (survival, ), ppf (quantile, ), isf (inverse survival), logpdf, rvs, fit, mean, var. Freeze parameters once (t4 = stats.t(df=4)) and reuse. Points worth knowing:
- Use
sffor tails.1 - stats.norm.cdf(9)is0.0, because the cdf rounds to 1;stats.norm.sf(9)is1.13e-19. Likewiseisf(1e-10)gives the extreme quantile 6.36 directly. - Fat tails are large. For a Student with 4 degrees of freedom,
sf(4)is 0.0081, against 3.2e-5 for the normal: 250 times more likely. Notet(4).var()is 2, so a raw is not unit-variance; rescale by 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:
| Test | Question | Main caveat |
|---|---|---|
ttest_1samp(r, 0) | Is the mean return non-zero? | Assumes independent observations; autocorrelation inflates |
jarque_bera | Are skewness and kurtosis normal? | With thousands of returns it rejects almost always |
kstest(x, "norm", args=...) | Does follow this exact distribution? | p-values are wrong if the parameters were estimated from (use a Lilliefors-type correction) |
pearsonr, spearmanr | Is there correlation? | Pearson is dominated by outliers; Spearman is rank-based |
A p-value is , 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 solutionHide 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 statistic is , with a two-sided p-value of 0.11: not significant at 5%. Notice the identity
so . A Sharpe ratio of 0.8 needs about years of data to reach . That is the single most useful number to quote in an interview about backtest significance.
The fat tails do not invalidate the -test here: with 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 , call linalg.solve(A, b). It factorises (about flops) and does two triangular solves; forming inv(A) costs about 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 at about 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 has independent standard normal entries, has covariance .
- A validity test. It fails exactly when the matrix is not positive definite. A hand-edited "correlation matrix" with and raises
LinAlgError(its eigenvalues are ): 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 ; 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
minimizemethod from the constraints (BFGS, L-BFGS-B, SLSQP); pass gradients, scale parameters, checksuccessand compare with a closed form or a tighter tolerance. root_scalarwith a bracket andbrentqis the robust one-dimensional solver;curve_fitstandard errors assume independent residuals.- Use
sf/isffor tails. Every test's p-value is conditional on its assumptions, especially independence. - : a Sharpe ratio of 1 needs about 4 years to reach .
- 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).