Lab
The math in use
Every equation below is implemented and running somewhere in this platform. Each entry links to the live page or names the module where it works.
Shannon entropy (normalized)
H=−i∑pilog2pi,H^=log2NH Measures how evenly a total is spread across its buckets, from all-in-one to perfectly even.
- Backlog health tooling
caskeycoding-specs _shared/tooling/backlog.py (health: epic distribution)
Exploring
Entropy-weighted digest diversity
H^=−s∑pslogps,scorei∝ui⋅H^S∪{i} Ranks candidate picks higher when adding them would spread the digest across more distinct sections.
Opportunity: Rank Second Mind digest section diversity the way backlog health scores epic concentration.
Probability & Statistics
Isotonic regression (pool-adjacent-violators)
f^=argg nondecreasingmini∑wi(yi−g(xi))2 Fits the best stepwise curve that is only allowed to go up, never down.
- Calibration engine
ai-blog-api src/finance/engine/calibration.py
Brier score + Murphy decomposition
BS=N1i∑(pi−oi)2=REL−RES+UNC,UNC=oˉ(1−oˉ) Scores how far probability forecasts land from what actually happened, split into calibration, skill, and irreducible noise.
- Forecast honesty scoring
ai-blog-api src/finance/engine/calibration.py
Deflated Sharpe Ratio
DSR=Φ(σSRSR−E[maxkSRk]) Judges a strategy’s risk-adjusted return against the best result you would expect from luck alone after many trials.
- Calibration engine + backtest stats
ai-blog-api src/finance/engine/calibration.py + src/finance/backtest/stats.py
Probabilistic Sharpe Ratio + Minimum Track Record Length
PSR=Φ1−γ3SR+4γ4−1SR2(SR−SR∗)n−1,MinTRL=1+(SR−SR∗Zα)2(1−γ3SR+4γ4−1SR2) Says how confident you can be that a true edge beats a benchmark, and how long a track record you would need to prove it.
- Backtest statistics
ai-blog-api src/finance/backtest/stats.py
Probability of Backtest Overfitting (CSCV)
PBO=S1s∑1{ωs<0},ωs=log(1−rsrs) Splits historical data many ways and counts how often the in-sample winner disappoints out of sample.
- Backtest overfitting check
ai-blog-api src/finance/backtest/pbo.py
Harvey-Liu-Zhu multiple-testing hurdle
E[maxt]=(1−γ)Φ−1(1−M1)+γΦ−1(1−Me1) Raises the bar a test statistic must clear the more strategies you have tried before it.
- Calibration engine
ai-blog-api src/finance/engine/calibration.py
Spearman rank information coefficient
IC=corr(rank(x),rank(y)) Measures how well a signal’s ordering of stocks matches the ordering of what they actually returned.
- Factor Monitor
- Signal validation
ai-blog-api src/finance/analysis/signal_validation.py
Stationary block bootstrap (Politis-Romano)
P(L=k)=(1−p)k−1p Resamples a time series in random-length blocks so the shuffled copies keep the original’s rhythm.
- Factor weighting
ai-blog-api src/finance/analysis/scoring/weights_v2.py
Bootstrap percentile confidence bands
CIα=[θ^(α/2)∗,θ^(1−α/2)∗] Brackets an estimate between the low and high percentiles of many resampled copies of the data.
Winsorization, z-score, MAD, rank-normalization
x′=min(max(x,qα),q1−α),z=σx−μ,zMAD=MADx−med,x↦Φ−1(n+1rank(x)) Four ways to put wildly different measurements on one shared scale without letting outliers dominate.
- Seismograph
- Signal normalization
ai-blog-api src/finance/analysis/signals_normalize.py
Cross-sectional dispersion (population std dev)
σxs=N1i∑(ri−rˉ)2 Measures how far apart a group of returns are from each other at a single point in time.
Exploring
Embedding cosine similarity for semantic recall
sim(q,d)=∥q∥∥d∥q⋅d Finds notes that mean the same thing as the query even when they share no words with it.
Opportunity: Second Mind recall is lexical BM25 only; semantic nearest-neighbor over embeddings is the known gap.
Stochastic Processes
Black-Scholes price + Greeks
C=S0N(d1)−Ke−rTN(d2),d1=σTln(S0/K)+(r+σ2/2)T,d2=d1−σT Prices a stock option from the stock price, strike, time, rate, and how jumpy the stock is.
Implied volatility (bracketed root-find)
σ^=argσ∈[σlo,σhi]min∣CBS(σ)−Cmkt∣ Works backwards from an option’s market price to the level of jumpiness the market is pricing in.
- Implied-volatility surface
ai-blog-web src/quant-viz/compute/impliedVol.ts
Geometric Brownian motion Monte Carlo
St+1=Stexp((μ−2σ2)Δt+σΔtZ),Z∼N(0,1) Simulates thousands of possible future price paths by stepping a random walk forward in time.
Realized volatility cone
σh=n1i=1∑nri2horizon h,Pq(h)=quantileq(σh) Shows how volatile the market has historically been at each lookback horizon, as a shaded cone of typical ranges.
Variance risk premium
VRP=σIV2−σRV2 Compares the volatility investors are paying for with the volatility that actually showed up.
Exploring
Newton-Raphson implied vol with analytic vega
σk+1=σk−ν(σk)C(σk)−Cmkt Solves for implied volatility by repeatedly stepping along the slope of the price curve instead of bisecting a bracket.
Opportunity: Faster implied-vol solve than the current bracketed root-find if the surface ever uses a real option chain.
Time Series & Regimes
EWMA + standardized regime shift
μ^t=λμ^t−1+(1−λ)xt,zt=σ^txt−μ^t Tracks a smoothed recent average and flags how unusual today’s value is against its own history.
- Regime shift detection
ai-blog-api src/finance/regime/shift.py
Absorption ratio (eigenvalue variance share)
AR=∑j=1Nλj∑i=1nλi Measures how much of a market’s movement is explained by just its top few common drivers.
- Regime absorption
ai-blog-api src/finance/regime/absorption.py
Nelson-Siegel yield curve
y(τ)=β0+β1τ/λ1−e−τ/λ+β2(τ/λ1−e−τ/λ−e−τ/λ) Draws a smooth curve through interest rates of every maturity using just a level, a slope, and a hump.
CPI year-over-year from index levels
YoYt=CPIt−12CPIt−1 Turns a monthly price index into the familiar annual inflation rate by comparing against the same month a year ago.
- Macro Phase
- Backend twin
ai-blog-web src/quant-viz/compute/macroPhase.ts + ai-blog-api macro exporter (lockstep pair)
Percent above trailing mean (breadth)
Bt=N1i∑1{pi,t>pˉi} Counts what share of stocks are trading above their own recent average.
Simplified TRIMP training load
TRIMP=duration×intensity Scores a workout by multiplying how long it lasted by how hard it was.
- Coach metrics engine
ai-blog-api src/coach/metrics/engine.py
Acute:chronic workload ratio (ACWR)
ACWR=chronic loadacute load Compares this week’s training load against the recent average to flag doing too much too fast.
- Coach metrics engine
ai-blog-api src/coach/metrics/engine.py
Exponential half-life decay
w(d)=2−d/h Weights recent items more than old ones, halving the weight every fixed number of days.
- Digest ranking
second-mind digest/build_digest.py
Exploring
Banister impulse-response (CTL/ATL/TSB)
CTLt=λfCTLt−1+(1−λf)Lt,ATLt=λgATLt−1+(1−λg)Lt,TSBt=CTLt−ATLt Models fitness as a slow-building response to training and fatigue as a fast-fading one, with form as the difference.
Opportunity: Coach has simplified TRIMP + ACWR only; fitness-fatigue modeling is the natural next tier.
Riegel race-time prediction
T2=T1(D1D2)α Predicts a race time at one distance from a known time at another distance.
Opportunity: Coach computes training load but predicts no race outcome.
Linear Algebra & Geometry
PCA via cyclic Jacobi eigendecomposition
A→RTAR,tan2θ=aii−ajj2aij Finds the main axes of variation in a dataset by repeatedly rotating the correlation matrix until its off-diagonal entries vanish.
Cosine similarity + mutual top-K graph + force layout
sij=∥xi∥∥xj∥xi⋅xj,Fi=j∈N(i)∑ks(dij−ℓ)u^ij−j=i∑dij2kru^ij Connects each point to its most similar neighbors and lets springs and repulsion spread them into a readable map.
Linear dynamical system + trace/determinant stability + RK4
x˙=Ax,stable⟺tr(A)<0,det(A)>0,xt+1=xt+6h(k1+2k2+2k3+k4) Classifies whether a simplified economic system settles down or spirals, and traces its path step by step.
OLS residualization / factor orthogonalization
β^=(XTX)−1XTy,r=y−Xβ^ Removes the part of a signal already explained by known factors, keeping only what is new.
- Scoring pipeline
ai-blog-api src/finance/analysis/scoring/pipeline_v2.py
Euclidean projection onto the probability simplex
w^=argw∈Δmin∥w−v∥22,Δ={w:wi≥0,i∑wi=1} Adjusts a set of weights as little as possible so they are all non-negative and sum to one.
- Portfolio benchmarks
ai-blog-api src/finance/backtest/benchmarks.py
One-common-factor PSD correlation model
ρij=βiβj,∣βi∣≤1⟹Σ⪰0 Builds a valid correlation matrix for many assets from each one’s sensitivity to a single shared driver.
Optimization & Learning
Exponentiated-gradient multiplicative weights (Helmbold)
wt+1,i=∑jwt,jeηz^t,jwt,ieηz^t,i Rebalances a portfolio each period by multiplying each holding’s weight by a reward for its recent return.
- Portfolio benchmarks
ai-blog-api src/finance/backtest/benchmarks.py
OLMAR + best constant-rebalanced portfolio
x^t+1=xˉt+ϵmax(0,xˉt−xt),w∗=argw∈Δmaxt∏(w⋅rt) Buys what fell below its recent average expecting a snap back, judged against the best fixed mix in hindsight.
- Portfolio benchmarks
ai-blog-api src/finance/backtest/benchmarks.py
Kelly criterion
f∗=p−b1−p Sizes a bet to grow wealth fastest over the long run given your edge and the payoff odds.
- Position sizing
ai-blog-api src/finance/engine/sizing.py
Volatility targeting + drawdown throttle
wt=σ^tσ∗,wt↦wt⋅g(DDt) Scales exposure down when risk runs hot and eases off further after losses pile up.
- Position sizing
ai-blog-api src/finance/engine/sizing.py
ICIR factor weighting with James-Stein shrinkage
wi∝σICiICi,θ^=(1−∥xˉ∥2(k−2)σ2)+xˉ Weights signals by how consistently they have predicted returns, pulled toward zero to avoid over-trusting small samples.
- Factor weighting
ai-blog-api src/finance/analysis/scoring/weights_v2.py
BM25 relevance ranking
score(D,q)=i∑IDF(qi)f(qi,D)+k1(1−b+bavgdl∣D∣)f(qi,D)(k1+1) Ranks documents by how well their words match a query, rewarding rare terms and not over-crediting long documents.
- Second Mind search
second-mind mcp/src/db.js (SQLite FTS5 bm25())
Budgeted greedy selection under byte cost
Smaxi∈S∑uis.t.i∈S∑ci≤B,pick by ui/ci Fills a fixed-size digest by repeatedly taking the item with the most value per byte it costs.
- Digest packing
second-mind digest/build_digest.py
Grade banding with hysteresis
gt=⎩⎨⎧upgradeholddowngradest>θuθd≤st≤θust<θd Changes a grade only when the score crosses a clearly higher or lower band, so borderline scores stop flapping.
- Composite grading
ai-blog-api src/finance/analysis/scoring/composite.py
Numerical Methods
Acklam inverse normal CDF approximation
Φ−1(p)≈1+∑kbktk∑kaktk,t=−2lnp(central region) Converts a probability back into the number of standard deviations from the mean, with a fast rational approximation.
- Calibration engine
ai-blog-api src/finance/engine/calibration.py
Piecewise linear interpolation
f(x)=yi+xi+1−xix−xi(yi+1−yi),x∈[xi,xi+1] Estimates values between known points by connecting them with straight lines.
- Today
- Interpolation utilities
ai-blog-api src/finance/utils/interpolation.py
Equal-width histogram binning
b(x)=min(⌊wx−xmin⌋,K−1),w=Kxmax−xmin Sorts values into equal-width buckets to draw the shape of a distribution.
Seeded PRNG discipline (mulberry32, hash jitter)
seed↦{un},un∈[0,1) Makes every random-looking picture come out identical every time from a fixed starting seed.
- All stochastic visualizations
ai-blog-web src/quant-viz/compute (all stochastic paths)