btQuant package
Submodules
btQuant.bootstrap module
- btQuant.bootstrap.creditCurve(maturities, cdsSpreads, recoveryRate=0.4, method='linear', nPoints=100)[source]
Bootstrap credit default swap curve.
- Parameters:
maturities – CDS maturities
cdsSpreads – CDS spreads (in basis points)
recoveryRate – recovery rate assumption
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘defaultProbabilities’
- btQuant.bootstrap.curve(x, y, z=None, method='cubic', nPoints=100)[source]
Bootstrap curves using interpolation.
- Parameters:
x – maturities/tenors (1D array)
y – rates/prices (1D array)
z – optional cash flows/coupons (1D array)
method – ‘linear’, ‘cubic’, ‘pchip’
nPoints – number of interpolation points
- Returns:
dict with ‘x’ and ‘y’ arrays
- btQuant.bootstrap.discountCurve(maturities, zeroRates, method='linear', nPoints=100)[source]
Derive discount factor curve from zero rates.
- Parameters:
maturities – maturities
zeroRates – zero rates
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘discountFactors’
- btQuant.bootstrap.forwardCurve(maturities, zeroRates, method='linear', nPoints=100)[source]
Derive forward rate curve from zero rates.
- Parameters:
maturities – maturities
zeroRates – zero rates
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘forwardRates’
- btQuant.bootstrap.fxForwardCurve(spot, domesticRates, foreignRates, maturities, method='linear', nPoints=100)[source]
Bootstrap FX forward curve.
- Parameters:
spot – spot FX rate
domesticRates – domestic interest rates
foreignRates – foreign interest rates
maturities – forward maturities
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘forwardRates’
- btQuant.bootstrap.inflationCurve(maturities, breakevens, realRates, method='linear', nPoints=100)[source]
Bootstrap inflation curve from breakeven rates.
- Parameters:
maturities – maturities
breakevens – breakeven inflation rates
realRates – real interest rates
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘inflationRates’
- btQuant.bootstrap.surface(x, y, z, method='linear', gridSize=(100, 100))[source]
Bootstrap 2D surfaces (e.g., volatility surfaces).
- Parameters:
x – first dimension (e.g., maturities)
y – second dimension (e.g., strikes)
z – values at (x, y) points
method – ‘linear’, ‘cubic’
gridSize – (nx, ny) tuple
- Returns:
dict with ‘X’, ‘Y’, ‘Z’ arrays
- btQuant.bootstrap.volSurface(maturities, strikes, impliedVols, method='linear', gridSize=(50, 50))[source]
Bootstrap implied volatility surface.
- Parameters:
maturities – option maturities
strikes – strike prices
impliedVols – implied volatilities
method – interpolation method
gridSize – grid dimensions
- Returns:
dict with ‘maturities’, ‘strikes’, ‘vols’
- btQuant.bootstrap.yieldCurve(maturities, prices, coupons=None, method='linear', nPoints=100)[source]
Bootstrap yield curve from bond data.
- Parameters:
maturities – bond maturities
prices – bond prices
coupons – coupon rates (optional)
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘yields’
- btQuant.bootstrap.zeroRateCurve(maturities, prices, method='linear', nPoints=100)[source]
Bootstrap zero rate curve from bond prices.
- Parameters:
maturities – bond maturities (years)
prices – bond prices
method – interpolation method
nPoints – number of points
- Returns:
dict with ‘maturities’ and ‘zeroRates’
btQuant.dimension module
- btQuant.dimension.ica(X, nComponents=None, maxIter=200, tol=0.0001)[source]
Independent component analysis.
- Parameters:
X – features
nComponents – number of components
maxIter – maximum iterations
tol – convergence tolerance
- Returns:
dict with ‘transformed’, ‘mixingMatrix’, ‘unmixingMatrix’
- btQuant.dimension.isomap(X, nComponents=2, nNeighbors=5)[source]
Isomap non-linear dimensionality reduction.
- Parameters:
X – features
nComponents – target dimensions
nNeighbors – number of nearest neighbors
- Returns:
dict with ‘transformed’
- btQuant.dimension.kernelPca(X, nComponents=None, kernel='rbf', gamma=None)[source]
Kernel PCA for non-linear dimensionality reduction.
- Parameters:
X – features
nComponents – number of components
kernel – ‘rbf’, ‘poly’, ‘linear’
gamma – kernel parameter
- Returns:
dict with ‘transformed’, ‘eigenvalues’, ‘eigenvectors’
- btQuant.dimension.lda(X, y, nComponents=None)[source]
Linear discriminant analysis.
- Parameters:
X – features
y – class labels
nComponents – number of components
- Returns:
dict with ‘transformed’, ‘eigenvalues’, ‘eigenvectors’
- btQuant.dimension.mds(X, nComponents=2, metric=True, maxIter=300)[source]
Multidimensional scaling.
- Parameters:
X – features or distance matrix
nComponents – target dimensions
metric – use metric MDS (True) or non-metric (False)
maxIter – maximum iterations for non-metric
- Returns:
dict with ‘transformed’
- btQuant.dimension.nmf(X, nComponents, maxIter=200, tol=0.0001)[source]
Non-negative matrix factorization.
- Parameters:
X – non-negative features
nComponents – number of components
maxIter – maximum iterations
tol – convergence tolerance
- Returns:
dict with ‘W’ (basis), ‘H’ (coefficients)
- btQuant.dimension.pca(X, nComponents=None)[source]
Principal component analysis.
- Parameters:
X – features (nSamples x nFeatures)
nComponents – number of components to keep
- Returns:
dict with ‘transformed’, ‘eigenvalues’, ‘eigenvectors’, ‘explained_variance’
- btQuant.dimension.tsne(X, nComponents=2, perplexity=30.0, maxIter=1000, learningRate=200.0)[source]
t-SNE dimensionality reduction.
- Parameters:
X – features
nComponents – target dimensions
perplexity – perplexity parameter
maxIter – maximum iterations
learningRate – learning rate
- Returns:
dict with ‘transformed’
btQuant.distributions module
- btQuant.distributions.adTest(data, distName='normal')[source]
Anderson-Darling test for normality.
- Parameters:
data – array of observations
distName – currently only ‘normal’ supported
- Returns:
dict with statistic, critical values
- btQuant.distributions.fitBeta(data, maxIter=100)[source]
Fit beta distribution using method of moments.
- Parameters:
data – array of observations in (0, 1)
maxIter – maximum iterations
- Returns:
dict with alpha, beta parameters, logLikelihood
- btQuant.distributions.fitExponential(data)[source]
Fit exponential distribution.
- Parameters:
data – array of positive observations
- Returns:
dict with lambda (rate), logLikelihood
- btQuant.distributions.fitGamma(data, maxIter=100)[source]
Fit gamma distribution using method of moments.
- Parameters:
data – array of positive observations
maxIter – maximum iterations
- Returns:
dict with alpha (shape), beta (rate), logLikelihood
- btQuant.distributions.fitLognormal(data)[source]
Fit lognormal distribution.
- Parameters:
data – array of positive observations
- Returns:
dict with mu, sigma (of log), logLikelihood
- btQuant.distributions.fitMixture(data, nComponents=2, maxIter=100)[source]
Fit Gaussian mixture model using EM algorithm.
- Parameters:
data – array of observations
nComponents – number of mixture components
maxIter – maximum iterations
- Returns:
dict with means, sigmas, weights
- btQuant.distributions.fitNormal(data)[source]
Fit normal distribution.
- Parameters:
data – array of observations
- Returns:
dict with mu, sigma, logLikelihood
- btQuant.distributions.fitT(data, maxIter=50)[source]
Fit Student’s t distribution.
- Parameters:
data – array of observations
maxIter – maximum iterations
- Returns:
dict with df (degrees of freedom), mu, sigma, logLikelihood
- btQuant.distributions.jsDivergence(p, q)[source]
Jensen-Shannon divergence.
- Parameters:
p – first distribution
q – second distribution
- Returns:
JS divergence
- btQuant.distributions.klDivergence(p, q)[source]
Kullback-Leibler divergence.
- Parameters:
p – true distribution (probabilities)
q – approximate distribution (probabilities)
- Returns:
KL divergence
- btQuant.distributions.ksTest(data, distName='normal', params=None)[source]
Kolmogorov-Smirnov test for distribution fit.
- Parameters:
data – array of observations
distName – ‘normal’, ‘lognormal’, ‘exponential’
params – dict of distribution parameters (if None, estimated)
- Returns:
dict with statistic, pValue (approximate)
- btQuant.distributions.moments(data)[source]
Calculate distribution moments.
- Parameters:
data – array of observations
- Returns:
dict with mean, variance, skewness, kurtosis
btQuant.econometrics module
- btQuant.econometrics.adfTest(series, lags=None, regression='c', autolag='AIC')[source]
Augmented Dickey-Fuller test for unit root.
- Parameters:
series – time series
lags – number of lags (auto if None)
regression – ‘nc’ (no constant), ‘c’ (constant), ‘ct’ (constant+trend)
autolag – ‘AIC’ or ‘BIC’
- Returns:
dict with testStatistic, pValue, criticalValues, conclusion, optimalLag
- btQuant.econometrics.breuschPaganTest(y, X, addConst=True)[source]
Breusch-Pagan test for heteroskedasticity.
- Parameters:
y – dependent variable
X – independent variables
addConst – add constant term
- Returns:
dict with testStatistic, pValue, df, conclusion
- btQuant.econometrics.durbinWatson(residuals)[source]
Durbin-Watson statistic for autocorrelation. DW ~ 2: no autocorrelation 0 < DW < 2: positive autocorrelation 2 < DW < 4: negative autocorrelation
- Parameters:
residuals – residuals from regression
- Returns:
Durbin-Watson statistic
- Return type:
float
- btQuant.econometrics.grangerCausality(y, x, maxLag=4)[source]
Granger causality test: does x Granger-cause y?
- Parameters:
y – dependent variable (time series)
x – independent variable (time series)
maxLag – maximum lag to test
- Returns:
dict with lags, fStats, pValues, conclusion
- btQuant.econometrics.kpssTest(series, lags=None, regression='c')[source]
KPSS test for stationarity.
- Parameters:
series – time series
lags – number of lags (auto if None)
regression – ‘c’ (constant) or ‘ct’ (constant+trend)
- Returns:
dict with testStatistic, pValue, criticalValues, conclusion, lags
- btQuant.econometrics.ljungBox(residuals, lags=None)[source]
Ljung-Box test for autocorrelation in residuals.
- Parameters:
residuals – residuals from regression
lags – number of lags (default min(10, n//5))
- Returns:
dict with lags, autocorrelations, qStats, pValues, criticalValues
- btQuant.econometrics.ols(y, X, addConst=True, robust=False, covType='HC3')[source]
Ordinary least squares regression with optional robust standard errors.
- Parameters:
y – dependent variable (1D array)
X – independent variables (2D array or 1D for single predictor)
addConst – add constant term
robust – use robust standard errors
covType – ‘HC0’, ‘HC1’, ‘HC2’, ‘HC3’, ‘HC4’
- Returns:
dict with coefficients, std_errors, t_stats, p_values, r_squared, etc.
btQuant.factor module
- btQuant.factor.appraisalRatio(alpha, residualRisk)[source]
Appraisal ratio (alpha / residual risk).
- Parameters:
alpha – Jensen’s alpha
residualRisk – residual standard deviation
- Returns:
appraisal ratio
- btQuant.factor.apt(riskFactors, factorBetas, riskFree=0.02)[source]
Arbitrage Pricing Theory expected return.
- Parameters:
riskFactors – array of factor returns
factorBetas – array of factor sensitivities
riskFree – risk-free rate
- Returns:
expected return
- btQuant.factor.capm(marketReturn, beta, riskFree=0.02)[source]
Capital Asset Pricing Model expected return.
- Parameters:
marketReturn – market return
beta – systematic risk
riskFree – risk-free rate
- Returns:
expected return
- btQuant.factor.carhart4(marketReturns, smb, hml, momentum, betaM, betaSmb, betaHml, betaMom, riskFree=0.02)[source]
Carhart 4-factor model expected return.
- Parameters:
marketReturns – market excess returns
smb – size factor
hml – value factor
momentum – momentum factor
betaM – market beta
betaSmb – size beta
betaHml – value beta
betaMom – momentum beta
riskFree – risk-free rate
- Returns:
expected return
- btQuant.factor.estimateBeta(assetReturns, marketReturns)[source]
Estimate beta coefficient.
- Parameters:
assetReturns – asset returns
marketReturns – market returns
- Returns:
dict with beta, alpha, rSquared
- btQuant.factor.estimateFactorLoading(assetReturns, factorReturns)[source]
Estimate factor loadings via OLS.
- Parameters:
assetReturns – asset returns (1D array)
factorReturns – factor returns (2D array, nObs x nFactors)
- Returns:
dict with loadings, intercept, rSquared
- btQuant.factor.factorMimicking(assetReturns, characteristicData, nPortfolios=5)[source]
Create factor-mimicking portfolios (e.g., SMB, HML).
- Parameters:
assetReturns – returns matrix (nObs x nAssets)
characteristicData – characteristic values (1D array, nAssets)
nPortfolios – number of portfolios for sorting
- Returns:
dict with longShort factor returns
- btQuant.factor.famaFrench3(marketReturns, smb, hml, betaM, betaSmb, betaHml, riskFree=0.02)[source]
Fama-French 3-factor model expected return.
- Parameters:
marketReturns – market excess returns (array)
smb – size factor returns (array)
hml – value factor returns (array)
betaM – market beta
betaSmb – size beta
betaHml – value beta
riskFree – risk-free rate
- Returns:
expected return
- btQuant.factor.informationRatio(assetReturns, benchmarkReturns)[source]
Information ratio (active return / tracking error).
- Parameters:
assetReturns – portfolio returns
benchmarkReturns – benchmark returns
- Returns:
information ratio
- btQuant.factor.jensenAlpha(assetReturns, marketReturns, riskFree=0.0)[source]
Calculate Jensen’s alpha.
- Parameters:
assetReturns – asset returns
marketReturns – market returns
riskFree – risk-free rate per period
- Returns:
Jensen’s alpha
- btQuant.factor.multifactor(assetReturns, factorReturns, riskFree=0.0)[source]
Multi-factor model regression.
- Parameters:
assetReturns – asset returns
factorReturns – matrix of factor returns (nObs x nFactors)
riskFree – risk-free rate
- Returns:
dict with alpha, betas, rSquared, residuals
- btQuant.factor.pcaFactors(returns, nFactors=3)[source]
Extract principal component factors.
- Parameters:
returns – returns matrix (nObs x nAssets)
nFactors – number of factors to extract
- Returns:
dict with factors, loadings, explainedVariance
- btQuant.factor.rollingBeta(assetReturns, marketReturns, window=60)[source]
Calculate rolling beta.
- Parameters:
assetReturns – asset returns
marketReturns – market returns
window – rolling window size
- Returns:
array of rolling betas
btQuant.fit module
- btQuant.fit.aic(logLikelihood, nParams)[source]
Akaike Information Criterion.
- Parameters:
logLikelihood – log-likelihood value
nParams – number of parameters
- Returns:
AIC value
- btQuant.fit.bic(logLikelihood, nParams, nObs)[source]
Bayesian Information Criterion.
- Parameters:
logLikelihood – log-likelihood value
nParams – number of parameters
nObs – number of observations
- Returns:
BIC value
- btQuant.fit.fitAr1(series)[source]
Fit AR(1) model.
- Parameters:
series – time series array
- Returns:
dict with phi (AR coefficient), intercept, sigma2 (error variance)
- btQuant.fit.fitArma(series, p=1, q=1, maxIter=100)[source]
Fit ARMA(p,q) model using approximate method.
- Parameters:
series – time series
p – AR order
q – MA order
maxIter – maximum iterations
- Returns:
dict with arCoefs, maCoefs, sigma2
- btQuant.fit.fitCir(rates, dt=0.003968253968253968)[source]
Fit Cox-Ingersoll-Ross model to interest rate data.
- Parameters:
rates – interest rate series
dt – time step
- Returns:
dict with kappa, theta, sigma
- btQuant.fit.fitCopula(data1, data2, copulaType='gaussian')[source]
Fit copula to bivariate data.
- Parameters:
data1 – first variable
data2 – second variable
copulaType – ‘gaussian’ (only type supported)
- Returns:
dict with rho (correlation parameter)
- btQuant.fit.fitDistributions(data, distributions=None)[source]
Fit multiple distributions and rank by AIC.
- Parameters:
data – array of observations
distributions – list of distribution names (None = all common)
- Returns:
list of (distName, params, aic) sorted by AIC
- btQuant.fit.fitGarch(series, p=1, q=1, maxIter=50)[source]
Fit GARCH(p,q) model.
- Parameters:
series – returns series
p – ARCH order
q – GARCH order
maxIter – maximum iterations
- Returns:
dict with omega, alphas, betas, aic, bic
- btQuant.fit.fitGbm(prices, dt=0.003968253968253968)[source]
Fit Geometric Brownian Motion to price data.
- Parameters:
prices – array of prices
dt – time step (default 1/252 for daily)
- Returns:
dict with mu (drift), sigma (volatility)
- btQuant.fit.fitHeston(prices, dt=0.003968253968253968)[source]
Fit Heston stochastic volatility model.
- Parameters:
prices – price series
dt – time step
- Returns:
dict with mu, kappa, theta, sigmaV, rho, v0
- btQuant.fit.fitJumpDiffusion(prices, dt=0.003968253968253968, threshold=3.0)[source]
Fit jump-diffusion model by separating jumps from diffusion.
- Parameters:
prices – price series
dt – time step
threshold – jump detection threshold (std devs)
- Returns:
dict with mu, sigma, jumpLambda, jumpMu, jumpSigma
- btQuant.fit.fitLevyOu(spread, jumpDetectionThreshold=0.4, dt=0.003968253968253968)[source]
Fit Lévy OU (jump-diffusion OU) model to spread data.
- Parameters:
spread – array of spread/price data
jumpDetectionThreshold – Bayesian jump detection threshold
dt – time step
- Returns:
dict with theta, mu, sigma, halfLife, jumpLambda, jumpMu, jumpSigma
btQuant.ml module
- btQuant.ml.anomalyScore(trees, X)[source]
Compute anomaly scores from isolation forest.
- Parameters:
trees – list of isolation trees
X – features to score
- Returns:
anomaly scores (higher = more anomalous)
- btQuant.ml.decisionTree(X, y, maxDepth=5)[source]
Decision tree classifier using Gini impurity.
- Parameters:
X – features (n_samples, n_features)
y – target labels
maxDepth – maximum tree depth
- Returns:
tree structure
- Return type:
dict
- btQuant.ml.gradientBoosting(X, y, nEstimators=100, learningRate=0.1, maxDepth=3)[source]
Gradient boosting regressor.
- Parameters:
X – features
y – target values
nEstimators – number of boosting rounds
learningRate – learning rate (shrinkage)
maxDepth – maximum tree depth
- Returns:
predict function
- btQuant.ml.isolationForest(X, nTrees=100, maxSamples=None, maxDepth=10)[source]
Isolation forest for anomaly detection.
- Parameters:
X – features (n_samples, n_features)
nTrees – number of trees
maxSamples – samples per tree (default all)
maxDepth – maximum tree depth
- Returns:
list of isolation trees
- btQuant.ml.kmeans(X, k=3, maxIters=100, tol=0.0001)[source]
K-means clustering.
- Parameters:
X – features (n_samples, n_features)
k – number of clusters
maxIters – maximum iterations
tol – convergence tolerance
- Returns:
centroids, labels
- btQuant.ml.knn(XTrain, yTrain, XTest, k=3)[source]
K-nearest neighbors classifier.
- Parameters:
XTrain – training features
yTrain – training labels
XTest – test features
k – number of neighbors
- Returns:
predicted labels
- btQuant.ml.lda(X, y, nComponents=None)[source]
Linear discriminant analysis.
- Parameters:
X – features
y – class labels
nComponents – number of components
- Returns:
transformed data, eigenvalues, eigenvectors
- btQuant.ml.logisticRegression(X, y, learningRate=0.01, nIters=1000)[source]
Logistic regression classifier.
- Parameters:
X – features
y – binary labels (0/1)
learningRate – learning rate
nIters – number of iterations
- Returns:
weights, bias, predict function
- btQuant.ml.naiveBayes(XTrain, yTrain, XTest)[source]
Gaussian naive Bayes classifier.
- Parameters:
XTrain – training features
yTrain – training labels
XTest – test features
- Returns:
predicted labels
- btQuant.ml.pca(X, nComponents=None)[source]
Principal component analysis.
- Parameters:
X – features (n_samples, n_features)
nComponents – number of components to keep
- Returns:
transformed data, eigenvalues, eigenvectors
- btQuant.ml.predictTree(tree, X)[source]
Predict using a regression or decision tree.
- Parameters:
tree – tree structure from regressionTree or decisionTree
X – features to predict (n_samples, n_features)
- Returns:
predictions array
btQuant.options module
- btQuant.options.asian(S, K, T, r, sigma, q=0.0, nSteps=100, optType='call', avgType='geometric')[source]
Asian option pricing (option on average price).
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
q – dividend yield
nSteps – number of averaging steps
optType – ‘call’ or ‘put’
avgType – ‘geometric’ or ‘arithmetic’
- Returns:
price, delta, gamma, vega, rho, theta (or price, stderr for arithmetic)
- Return type:
dict
- btQuant.options.barrier(S, K, T, r, sigma, barrierLevel, q=0.0, optType='call', barrierType='down-and-out', rebate=0.0)[source]
Barrier option pricing (option that activates or deactivates at a barrier level).
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
barrierLevel – barrier price level
q – dividend yield
optType – ‘call’ or ‘put’
barrierType – ‘down-and-out’, ‘down-and-in’, ‘up-and-out’, ‘up-and-in’
rebate – rebate payment if barrier is hit
- Returns:
price, delta, gamma, vega
- Return type:
dict
- btQuant.options.binary(S, K, T, r, sigma, q=0.0, optType='call')[source]
Binary (digital) option pricing with Greeks.
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
q – dividend yield
optType – ‘call’ or ‘put’
- Returns:
price, delta, gamma, vega, rho, theta
- Return type:
dict
- btQuant.options.binomial(S, K, T, r, sigma, q=0.0, N=100, optType='call', american=False)[source]
Binomial tree option pricing model.
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
q – dividend yield
N – number of time steps
optType – ‘call’ or ‘put’
american – True for American options, False for European
- Returns:
price, delta, gamma, theta
- Return type:
dict
- btQuant.options.blackScholes(S, K, T, r, sigma, q=0.0, optType='call')[source]
Black-Scholes option pricing model with Greeks.
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
q – dividend yield
optType – ‘call’ or ‘put’
- Returns:
price, delta, gamma, vega, rho, theta
- Return type:
dict
- btQuant.options.bootstrapCurve(spotPrice, futuresPrices, tenors, assumedRate=0.05)[source]
Bootstrap convenience yields from futures prices.
- Parameters:
spotPrice – current spot price
futuresPrices – observed futures prices array
tenors – time to maturity array (years)
assumedRate – assumed risk-free rate
- Returns:
convenience_yields, storage_costs
- Return type:
dict
- btQuant.options.buildForwardCurve(spotPrice, tenors, rates, storageCosts=None, convenienceYields=None)[source]
Build forward curve for commodities or other assets.
- Parameters:
spotPrice – current spot price
tenors – time to maturity array (years)
rates – risk-free rates array
storageCosts – storage cost rates array
convenienceYields – convenience yield rates array
- Returns:
forward prices
- Return type:
array
- btQuant.options.impliedVol(price, S, K, T, r, optType='call', q=0.0, tol=1e-06, maxIter=100)[source]
Calculate implied volatility using Newton-Raphson method.
- Parameters:
price – observed option price
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
optType – ‘call’ or ‘put’
q – dividend yield
tol – convergence tolerance
maxIter – maximum iterations
- Returns:
implied volatility (or np.nan if not converged)
- Return type:
float
- btQuant.options.simulate(pricingModel, paths, r, T, **modelParams)[source]
Monte Carlo simulation wrapper for option pricing.
- Parameters:
pricingModel – pricing function to use
paths – simulated price paths (nSims x nSteps)
r – risk-free rate
T – time to maturity (years)
**modelParams – additional parameters for pricing model
- Returns:
price, stderr
- Return type:
dict
- btQuant.options.spread(S1, S2, K, T, r, sigma1, sigma2, rho, q1=0.0, q2=0.0, optType='call')[source]
Spread option pricing (option on the difference between two assets).
- Parameters:
S1 – current price of asset 1
S2 – current price of asset 2
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma1 – volatility of asset 1
sigma2 – volatility of asset 2
rho – correlation between assets
q1 – dividend yield of asset 1
q2 – dividend yield of asset 2
optType – ‘call’ or ‘put’
- Returns:
price, delta1, delta2, gamma1, gamma2, vega1, vega2
- Return type:
dict
- btQuant.options.trinomial(S, K, T, r, sigma, q=0.0, N=50, optType='call', american=False)[source]
Trinomial tree option pricing model.
- Parameters:
S – current stock price
K – strike price
T – time to maturity (years)
r – risk-free rate
sigma – volatility
q – dividend yield
N – number of time steps
optType – ‘call’ or ‘put’
american – True for American options, False for European
- Returns:
price, delta, gamma, theta
- Return type:
dict
btQuant.portfolio module
- btQuant.portfolio.blackLitterman(covMatrix, pi, P, Q, tau=0.05)[source]
Black-Litterman model for portfolio optimization.
- Parameters:
covMatrix – covariance matrix of returns
pi – equilibrium (market-implied) returns
P – views matrix (rows=views, cols=assets)
Q – view returns vector
tau – prior uncertainty (default 0.05)
- Returns:
adjusted expected returns
- btQuant.portfolio.efficientFrontier(expectedReturns, covMatrix, nPoints=50)[source]
Compute efficient frontier.
- Parameters:
expectedReturns – expected returns
covMatrix – covariance matrix
nPoints – number of points on frontier
- Returns:
list of dicts with returns, volatility, weights
- btQuant.portfolio.equalWeight(nAssets)[source]
Equal weight portfolio.
- Parameters:
nAssets – number of assets
- Returns:
equal weight portfolio weights
- btQuant.portfolio.hierarchicalRiskParity(covMatrix, returns)[source]
Hierarchical risk parity portfolio allocation.
- Parameters:
covMatrix – covariance matrix
returns – historical returns (for correlation)
- Returns:
HRP portfolio weights
- btQuant.portfolio.maxDiversification(covMatrix)[source]
Maximum diversification portfolio.
- Parameters:
covMatrix – covariance matrix
- Returns:
maximum diversification portfolio weights
- btQuant.portfolio.maxReturn(expectedReturns)[source]
Maximum return portfolio (100% in highest expected return asset).
- Parameters:
expectedReturns – expected returns
- Returns:
maximum return portfolio weights
- btQuant.portfolio.maxSharpe(expectedReturns, covMatrix, riskFreeRate=0)[source]
Maximum Sharpe ratio portfolio (alias for tangency).
- Parameters:
expectedReturns – expected returns
covMatrix – covariance matrix
riskFreeRate – risk-free rate
- Returns:
maximum Sharpe portfolio weights
- btQuant.portfolio.meanVariance(expectedReturns, covMatrix, riskAversion=0.5)[source]
Mean-variance optimization.
- Parameters:
expectedReturns – expected returns for each asset
covMatrix – covariance matrix
riskAversion – risk aversion parameter (higher = more risk averse)
- Returns:
optimal portfolio weights
- btQuant.portfolio.minCvar(expectedReturns, returns, alpha=0.95)[source]
Minimum CVaR (Conditional Value at Risk) portfolio.
- Parameters:
expectedReturns – expected returns
returns – historical returns matrix (nSamples x nAssets)
alpha – confidence level
- Returns:
minimum CVaR portfolio weights
- btQuant.portfolio.minVariance(covMatrix)[source]
Minimum variance portfolio.
- Parameters:
covMatrix – covariance matrix
- Returns:
minimum variance portfolio weights
btQuant.risk module
- btQuant.risk.beta(assetReturns, marketReturns)[source]
Beta coefficient (systematic risk).
- Parameters:
assetReturns – asset returns
marketReturns – market returns
- Returns:
beta
- btQuant.risk.calmarRatio(returns, riskFreeRate=0)[source]
Calmar ratio: annualized return / max drawdown.
- Parameters:
returns – array of returns
riskFreeRate – risk-free rate
- Returns:
Calmar ratio
- btQuant.risk.capturRatio(returns, marketReturns)[source]
Upside and downside capture ratios.
- Parameters:
returns – portfolio returns
marketReturns – market returns
- Returns:
dict with upsideCapture, downsideCapture, captureRatio
- btQuant.risk.conditionalValueAtRisk(returns, confidence=0.95, method='historical')[source]
Conditional Value at Risk with method selection.
- Parameters:
returns – array of returns
confidence – confidence level
method – ‘historical’ or ‘parametric’
- Returns:
CVaR estimate
- btQuant.risk.downsideDeviation(returns, target=0)[source]
Downside deviation.
- Parameters:
returns – array of returns
target – target return
- Returns:
downside deviation
- btQuant.risk.drawdown(returns)[source]
Maximum drawdown.
- Parameters:
returns – array of returns
- Returns:
maximum drawdown (negative value)
- btQuant.risk.excessKurtosis(returns)[source]
Excess kurtosis.
- Parameters:
returns – array of returns
- Returns:
excess kurtosis
- btQuant.risk.expectedShortfall(returns, confidence=0.95)[source]
Expected shortfall (ES), same as historical CVaR.
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
ES estimate
- btQuant.risk.hillTailIndex(returns, k=50)[source]
Hill estimator for tail index (heavy tails).
- Parameters:
returns – array of returns
k – number of extreme values
- Returns:
tail index (lower = heavier tail)
- btQuant.risk.historicalCvar(returns, confidence=0.95)[source]
Historical simulation Conditional Value at Risk.
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
CVaR estimate
- btQuant.risk.historicalVar(returns, confidence=0.95)[source]
Historical simulation Value at Risk.
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
VaR estimate
- btQuant.risk.informationRatio(returns, benchmarkReturns)[source]
Information ratio: active return / tracking error.
- Parameters:
returns – portfolio returns
benchmarkReturns – benchmark returns
- Returns:
information ratio
- btQuant.risk.maxDrawdownDuration(returns)[source]
Maximum drawdown duration in periods.
- Parameters:
returns – array of returns
- Returns:
maximum drawdown duration
- btQuant.risk.modifiedVar(returns, confidence=0.95)[source]
Modified VaR using Cornish-Fisher expansion for skewness and kurtosis.
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
modified VaR
- btQuant.risk.omegaRatio(returns, threshold=0.0)[source]
Omega ratio: ratio of gains to losses.
- Parameters:
returns – array of returns
threshold – threshold return
- Returns:
Omega ratio
- btQuant.risk.painIndex(returns)[source]
Pain index (average squared drawdown).
- Parameters:
returns – array of returns
- Returns:
pain index
- btQuant.risk.parametricCvar(returns, confidence=0.95)[source]
Parametric Conditional Value at Risk (assumes normal).
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
CVaR estimate
- btQuant.risk.parametricVar(returns, confidence=0.95)[source]
Parametric Value at Risk (assumes normal distribution).
- Parameters:
returns – array of returns
confidence – confidence level (default 0.95)
- Returns:
VaR estimate
- btQuant.risk.sharpeRatio(returns, riskFreeRate=0)[source]
Sharpe ratio.
- Parameters:
returns – array of returns
riskFreeRate – risk-free rate per period
- Returns:
Sharpe ratio
- btQuant.risk.sortinoRatio(returns, riskFreeRate=0, target=0)[source]
Sortino ratio (uses downside deviation).
- Parameters:
returns – array of returns
riskFreeRate – risk-free rate
target – target return (default 0)
- Returns:
Sortino ratio
- btQuant.risk.stabilityRatio(returns)[source]
Stability of returns (R-squared of linear regression).
- Parameters:
returns – array of returns
- Returns:
stability ratio (0-1, higher = more stable)
- btQuant.risk.tailRatio(returns, confidence=0.95)[source]
Tail ratio: right tail / left tail.
- Parameters:
returns – array of returns
confidence – confidence level
- Returns:
tail ratio (>1 means right tail heavier)
- btQuant.risk.trackingError(returns, benchmarkReturns)[source]
Tracking error (standard deviation of active returns).
- Parameters:
returns – portfolio returns
benchmarkReturns – benchmark returns
- Returns:
tracking error
- btQuant.risk.treynorRatio(returns, marketReturns, riskFreeRate=0)[source]
Treynor ratio: excess return / beta.
- Parameters:
returns – portfolio returns
marketReturns – market returns
riskFreeRate – risk-free rate
- Returns:
Treynor ratio
btQuant.sim module
- btQuant.sim.ar1(phi, intercept, sigma, nSteps, nSims, x0=0.0)[source]
AR(1) process simulation.
- Parameters:
phi – autoregressive coefficient
intercept – constant term
sigma – error variance
nSteps – number of time steps
nSims – number of simulations
x0 – initial value
- Returns:
array (nSims x nSteps)
- btQuant.sim.arch(alpha0, alpha1, nSteps, nSims)[source]
ARCH(1) process simulation.
- Parameters:
alpha0 – constant term
alpha1 – ARCH coefficient
nSteps – number of time steps
nSims – number of simulations
- Returns:
array (nSims x nSteps)
- btQuant.sim.arma(arCoefs, maCoefs, sigma, nSteps, nSims, x0=0.0)[source]
ARMA process simulation.
- Parameters:
arCoefs – AR coefficients (list)
maCoefs – MA coefficients (list)
sigma – error std deviation
nSteps – number of time steps
nSims – number of simulations
x0 – initial value
- Returns:
array (nSims x nSteps)
- btQuant.sim.cir(kappa, theta, sigma, nSteps, nSims, r0=0.05, dt=0.003968253968253968)[source]
Cox-Ingersoll-Ross (CIR) interest rate model simulation.
- Parameters:
kappa – mean reversion rate
theta – long-term mean
sigma – volatility
nSteps – number of time steps
nSims – number of simulations
r0 – initial rate
dt – time step
- Returns:
array (nSims x nSteps)
- btQuant.sim.compoundPoisson(lambdaRate, jumpMu, jumpSigma, nSteps, nSims, s0=100, dt=0.003968253968253968)[source]
Compound Poisson process simulation (jumps with sizes).
- Parameters:
lambdaRate – jump intensity
jumpMu – mean jump size
jumpSigma – jump size std dev
nSteps – number of time steps
nSims – number of simulations
s0 – initial value
dt – time step
- Returns:
array (nSims x nSteps)
- btQuant.sim.garch(omega, alpha1, beta1, nSteps, nSims)[source]
GARCH(1,1) process simulation.
- Parameters:
omega – constant term
alpha1 – ARCH coefficient
beta1 – GARCH coefficient
nSteps – number of time steps
nSims – number of simulations
- Returns:
array (nSims x nSteps)
- btQuant.sim.gbm(mu, sigma, nSteps, nSims, s0=1.0, dt=0.003968253968253968)[source]
Geometric Brownian Motion simulation.
- Parameters:
mu – drift
sigma – volatility
nSteps – number of time steps
nSims – number of simulations
s0 – initial value
dt – time step
- Returns:
array (nSims x nSteps)
- btQuant.sim.heston(mu, kappa, theta, sigma, rho, s0=100, v0=0.04, nSteps=252, nSims=1000, dt=0.003968253968253968)[source]
Heston stochastic volatility model simulation.
- Parameters:
mu – drift of stock price
kappa – mean reversion rate of variance
theta – long-term variance
sigma – volatility of variance
rho – correlation between stock and variance
s0 – initial stock price
v0 – initial variance
nSteps – number of time steps
nSims – number of simulations
dt – time step
- Returns:
dict with ‘prices’ and ‘variances’ arrays (nSims x nSteps)
- btQuant.sim.levyOu(theta, mu, sigma, jumpLambda, jumpMu, jumpSigma, nSteps, nSims, x0=0.0, dt=0.003968253968253968)[source]
Lévy OU process (OU with jumps) simulation.
- Parameters:
theta – mean reversion rate
mu – long-term mean
sigma – diffusion volatility
jumpLambda – jump intensity
jumpMu – jump mean
jumpSigma – jump volatility
nSteps – number of time steps
nSims – number of simulations
x0 – initial value
dt – time step
- Returns:
array (nSims x nSteps)
- btQuant.sim.markovSwitching(mu1, sigma1, mu2, sigma2, p11, p22, nSteps, nSims, x0=0.0)[source]
Markov regime switching model simulation.
- Parameters:
mu1 – mean in regime 1
sigma1 – std dev in regime 1
mu2 – mean in regime 2
sigma2 – std dev in regime 2
p11 – probability of staying in regime 1
p22 – probability of staying in regime 2
nSteps – number of time steps
nSims – number of simulations
x0 – initial value
- Returns:
array (nSims x nSteps)
- btQuant.sim.ou(theta, mu, sigma, nSteps, nSims, x0=0.0, dt=0.003968253968253968)[source]
Ornstein-Uhlenbeck process simulation.
- Parameters:
theta – mean reversion rate
mu – long-term mean
sigma – volatility
nSteps – number of time steps
nSims – number of simulations
x0 – initial value
dt – time step
- Returns:
array (nSims x nSteps)
- btQuant.sim.poisson(lambdaRate, nSteps, nSims)[source]
Poisson process simulation (jump counts).
- Parameters:
lambdaRate – jump intensity (jumps per period)
nSteps – number of time steps
nSims – number of simulations
- Returns:
array (nSims x nSteps)
- btQuant.sim.simulate(model, params, nSteps, nSims)[source]
General simulation dispatcher.
- Parameters:
model – model name (str)
params – dict of model parameters
nSteps – number of time steps
nSims – number of simulations
- Returns:
array of simulated paths
- btQuant.sim.vasicek(kappa, theta, sigma, nSteps, nSims, r0=0.05, dt=0.003968253968253968)[source]
Vasicek interest rate model simulation.
- Parameters:
kappa – mean reversion rate
theta – long-term mean
sigma – volatility
nSteps – number of time steps
nSims – number of simulations
r0 – initial rate
dt – time step
- Returns:
array (nSims x nSteps)