Skip to main content

mts1b-quantkit

The canonical quantitative library. One implementation of each pattern, not five.

Repo: github.com/MTS1B/mts1b-quantkit Layer: 2 Depends on: foundation, platform, numpy, scipy, pandas, optional cupy Audience: research, GPUbacktester, portfolio, riskengine

What it is

The single home for the quantitative primitives the rest of MTS1B uses. Every function here was consolidated from 3-6 copies across the source monorepo. CI ensures no other repo redefines these names.

CategoryFunctions
Allocatorshrp_weights, black_litterman, markowitz, ledoit_wolf, risk_parity
Cross-validationwalk_forward, purged_kfold, combinatorial_cv
Metricssharpe_from_moments, sharpe, calmar, max_drawdown, cagr, omega, sortino
Statisticsinformation_coefficient, bootstrap_sharpe_ci, decay_curve
Greeksblack_scholes, bs_greeks, implied_vol
Risk metricsvar_historical, var_parametric, expected_shortfall, cvar
Cost modelscompute_fee, compute_slippage, venue_cost_model
Universe filterspasses_adv_filter, passes_market_cap, passes_price_filter
Regime classifiersclassify_regime, vix_regime, trend_regime
Factor primitiveszscore_cross_sectional, winsorize, ewma_std, rolling_corr

Top APIs

hrp_weights (Hierarchical Risk Parity)

from mts1b_quantkit.allocators import hrp_weights

result = hrp_weights(returns) # pd.DataFrame (T x A)
# HRPResult(weights, linkage, leaves, leaf_order)

print(result.weights)
# AAPL 0.124
# MSFT 0.131
# GOOG 0.105
# ...

López de Prado 2016 algorithm. Source: consolidated from 4 prior implementations into one. The canonical impl uses Ward linkage on the distance matrix sqrt((1 - corr) / 2), recursive bisection for weight assignment.

API source: services/research/src/gpuBT1060/portfolio/hrp.py:hrp_weights.

black_litterman

from mts1b_quantkit.allocators import black_litterman

views = [
{"symbols": ["SPY"], "weights": [1.0], "expected": 0.10, "confidence": 0.6},
{"symbols": ["TLT", "GLD"], "weights": [1.0, -1.0], "expected": 0.02, "confidence": 0.4},
]

result = black_litterman(
returns,
market_caps={"SPY": 4e12, "TLT": 30e9, "GLD": 60e9, ...},
views=views,
risk_aversion=2.5,
tau=0.05,
view_uncertainty_factor=1.0,
)

print(result["weights"])

API source: services/research/src/mts/research/modules/allocators/black_litterman.py:black_litterman.

walk_forward

from mts1b_quantkit.cv import walk_forward

cv = walk_forward(
ret_series=returns, # (T,) of strategy returns
signal_series=signal, # (T,) of signal values
window=252, # train window
step=63, # roll forward by 1 quarter
)

print(cv["agg_sharpe"]) # 1.43
print(cv["fold_sharpes"]) # per-fold sharpes
print(cv["ci95_sharpe"]) # bootstrap CI
print(cv["stability_score"]) # 0-1; 1 = identical across folds

API source: services/research/src/gpuBT1060/eval/statistical.py:walk_forward.

sharpe, calmar, max_drawdown

from mts1b_quantkit.metrics import sharpe, calmar, max_drawdown, sortino

s = sharpe(returns, periods_per_year=252) # annualized
c = calmar(returns, periods_per_year=252) # CAGR / |MaxDD|
dd = max_drawdown(returns) # worst peak-to-trough
so = sortino(returns, periods_per_year=252, mar=0.0)

CPU + GPU bindings share signatures. Pass xp=cupy for GPU.

bs_greeks

from mts1b_quantkit.options import bs_greeks

g = bs_greeks(spot=100, strike=105, t=30/365, r=0.05, vol=0.30, q=0.0, option="call")
# Greeks(delta=0.412, gamma=0.045, theta=-0.018, vega=0.123, rho=0.034)

compute_fee, compute_slippage

from mts1b_quantkit.cost_models import compute_fee, compute_slippage, venue_cost_model

cost = venue_cost_model(
venue="coinbase",
symbol="BTC-USD",
side="buy",
quantity=0.5,
price=95000,
is_taker=True,
)
# CostBreakdown(fee=$23.75, spread=$2.5, slippage=$15.0, total=$41.25)

Source: consolidated from gpuBT1060/core/{cost_model,venue_costs}.py (471 LoC each) + trading/workers/broker_fill_normalizer.py.

passes_adv_filter

from mts1b_quantkit.universe_filters import passes_adv_filter

mask = passes_adv_filter(
universe=["AAPL", "MSFT", "GOOG", "TINY_CORP"],
adv_threshold_usd=10_000_000,
lookback_days=21,
)
# [True, True, True, False]

Pulls from mts1b-datalake; cached for 1h.

zscore_cross_sectional

from mts1b_quantkit.factors import zscore_cross_sectional

z = zscore_cross_sectional(panel.close) # (T, A) z-scored per row

Standard factor primitive: subtract row mean, divide by row std, winsorize at ±3σ.

CPU vs GPU dispatch

Most functions take xp (numpy or cupy):

import numpy as np
import cupy as cp

# CPU path
hrp_weights(returns_pd, xp=np)

# GPU path (10-100x faster for large universes)
returns_cp = cp.asarray(returns_pd.values)
hrp_weights(returns_cp, xp=cp)

If xp is omitted, it's inferred from the input array type.

Type stubs + py.typed

Full type stubs published; py.typed marker so consumers' mypy can leverage them:

# Your code
result: HRPResult = hrp_weights(returns)
weights: pd.Series = result.weights # mypy is happy

Tests

pytest -v # 1500+ unit tests
pytest -m gpu # require CUDA
pytest -m benchmark # perf regression checks
pytest --cov=src --cov-report=html # ~95% coverage target

Each consolidated function has property-based tests via hypothesis confirming behavioral parity with the prior implementations it replaces.

Roadmap

VersionItems
0.1 (Wave 1)17 deduped patterns, CPU + GPU, full tests
0.2 (Wave 2)More allocators: equal-risk-contribution, max-diversification
0.3 (Wave 2)TCA primitives: implementation shortfall, slippage attribution
0.4 (Wave 3)Option pricing: American, Asian, barriers (currently European only)
1.0 (LTS)Frozen API; new functions via plugins

See also