canli-mcp 0.17.1 / Every tool

Every canli-mcp tool

388 finance tools in 7 packs, listed from the index that ships with this release. You do not pick from this list: the model is shown 5 tools, searches the rest with find_tool and runs what it finds. This page is for seeing what is there.

235 tools

Quant finance

canli-quant-mcp, also its own server.

Performance and risk ratios

23
  • return_statsReturn statistics

    Summarize a return series: periods, annualized geometric return (CAGR) and volatility, Sharpe, max drawdown, skew, excess kurtosis, best and worst period, share positive.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, risk_free?: number

  • sharpe_ratioSharpe ratio with standard error

    Compute the annualized Sharpe ratio with its standard error and 95% interval, under iid normal returns (Lo 2002) and allowing skew and fat tails (Mertens 2002). For the probability it beats luck across many trials, use canli-validation-mcp.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, risk_free?: number

  • sortino_ratioSortino ratio

    Compute the annualized Sortino ratio: mean return above a target over downside deviation below it, with the downside deviation itself.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, target?: number

  • max_drawdownDrawdowns

    Find the maximum drawdown and the worst drawdown episodes: depth, peak, trough, recovery and length in periods, plus time under water.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, top?: integer, dates?: string[]

  • calmar_ratioCalmar ratio

    Compute the Calmar ratio: annualized geometric return over the absolute maximum drawdown of the whole series.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number

  • omega_ratioOmega ratio

    Compute the Omega ratio at a threshold: the sum of gains above it over the sum of losses below it.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, threshold?: number

  • value_at_riskValue at risk

    Estimate value at risk as a positive loss fraction: historical, Gaussian and Cornish-Fisher (skew and kurtosis adjusted), over one or more periods.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, confidence?: number, horizon?: integer

  • expected_shortfallExpected shortfall (CVaR)

    Estimate expected shortfall (CVaR): the average loss beyond value at risk, historical and Gaussian, as a positive loss fraction.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, confidence?: number, horizon?: integer

  • capm_regressionAlpha and beta (CAPM)

    Regress excess returns on benchmark excess returns: beta, alpha (annualized), their t-stats and p-values, R-squared, correlation and residual (idiosyncratic) volatility.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, benchmark: number[], risk_free?: number

  • information_ratioInformation ratio and tracking error

    Compute active return, tracking error and the information ratio of a strategy against its benchmark, annualized.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, benchmark: number[]

  • treynor_ratioTreynor ratio

    Compute the Treynor ratio: annualized excess return per unit of beta to the benchmark.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, benchmark: number[], risk_free?: number

  • m2_measureModigliani M-squared

    Compute Modigliani's M-squared: the return the strategy would have earned levered to the benchmark's volatility, and its difference from the benchmark.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, benchmark: number[], risk_free?: number

  • capture_ratiosUp and down capture

    Compute up-market and down-market capture: the strategy's annualized return in benchmark up periods and down periods, relative to the benchmark's.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, benchmark: number[]

  • ulcer_indexUlcer index and Martin ratio

    Compute the Ulcer index (root-mean-square drawdown), the Martin (ulcer performance) ratio, and the pain index and pain ratio (mean drawdown).

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, risk_free?: number

  • drawdown_at_riskConditional drawdown at risk

    Estimate drawdown at risk (a drawdown quantile across periods) and conditional drawdown at risk (the mean drawdown beyond it), as positive fractions.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, confidence?: number

  • tail_ratioTail and Rachev ratios

    Compute the tail ratio (95th percentile return over the absolute 5th) and the Rachev ratio (mean of the best tail over the mean loss of the worst tail).

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, tail?: number

  • gain_to_painGain-to-pain ratio

    Compute Schwager's gain-to-pain ratio: the sum of returns over the absolute sum of losing returns.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number

  • trade_statsTrade statistics

    Summarize closed-trade results: win rate, profit factor, payoff ratio, expectancy, largest win and loss, and longest winning and losing streaks.

    Arguments: pnl: number[]

  • kelly_fractionKelly fraction

    Compute the growth-optimal (Kelly) fraction: from a return series (continuous, (mean - rf) / variance), or from a win probability and payoff odds. Also gives half Kelly.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, risk_free?: number, win_probability?: number, payoff?: number

  • autocorrelationAutocorrelation and Ljung-Box

    Test a return series for serial correlation: autocorrelations at each lag and the Ljung-Box Q statistic with its p-value.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, lags?: integer

  • normality_testNormality (Jarque-Bera)

    Test whether returns are normal with the Jarque-Bera test, with skew and excess kurtosis.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number

  • autocorrelation_adjusted_sharpeSharpe adjusted for autocorrelation

    Annualize a Sharpe ratio allowing for serial correlation (Lo 2002): smoothed or autocorrelated returns overstate the usual sqrt(time) Sharpe.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, risk_free?: number, max_lag?: integer

  • rolling_sharpeRolling Sharpe summary

    Summarize the rolling Sharpe ratio over a window: latest, min, max, median and the share of windows below zero; shows whether performance is stable or decaying.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, window?: integer, risk_free?: number

Options

12
  • black_scholesBlack-Scholes price and Greeks

    Price a European option under Black-Scholes-Merton with a dividend yield, with delta, gamma, vega, theta, rho, vanna, volga, charm, speed and the risk-neutral probability of finishing in the money.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, volatility: number

  • implied_volatilityImplied volatility

    Solve for the Black-Scholes-Merton implied volatility of a European option from its price, refusing prices outside no-arbitrage bounds.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, price: number

  • black76Black-76 (options on futures)

    Price a European option on a futures or forward with Black-76, with delta, gamma and vega; also used for caps, floors and swaptions on a forward rate.

    Arguments: type: call|put, forward: number, strike: number, years: number, rate?: number, volatility: number

  • bachelierBachelier (normal model)

    Price a European option under the Bachelier normal model, which allows negative forwards (rates, spreads), with delta, gamma and vega.

    Arguments: type: call|put, forward: number, strike: number, years: number, rate?: number, normal_volatility: number

  • american_optionAmerican option (binomial tree)

    Price an American option with a dividend yield (binomial Black-Scholes with Richardson extrapolation), with the European price and the early-exercise premium.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, volatility: number, steps?: integer

  • digital_optionDigital (binary) option

    Price a European cash-or-nothing or asset-or-nothing digital option under Black-Scholes-Merton, with delta.

    Arguments: type: call|put, payout?: cash|asset, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, volatility: number

  • put_call_parityPut-call parity check

    Check put-call parity for a European pair: the parity gap, the implied forward and the implied rate-minus-yield, to spot mispricing or stale quotes.

    Arguments: call: number, put: number, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number

  • option_strategy_payoffMulti-leg strategy payoff

    Evaluate a multi-leg options position at expiry (calls, puts, underlying): net premium, payoff and profit at chosen prices, breakevens, and maximum profit and loss.

    Arguments: legs: {type,strike,quantity,premium}[], prices?: number[]

  • option_portfolio_greeksPortfolio Greeks

    Aggregate Black-Scholes-Merton Greeks across many option positions on one underlying: net delta, gamma, vega, theta, rho and the dollar delta and gamma.

    Arguments: spot: number, rate?: number, dividend_yield?: number, positions: {type,strike,years,volatility,quantity,multiplier}[]

  • volatility_conversionsVolatility conversions

    Convert volatility between periods and forms: annual to daily, weekly or monthly, the expected move over a horizon, and lognormal to approximate normal (basis point) volatility.

    Arguments: annual_volatility: number, level?: number, days?: number, trading_days?: number

  • vix_style_indexModel-free implied volatility (VIX method)

    Compute a VIX-style model-free implied volatility from option chains with the CBOE method: forward from put-call parity, out-of-the-money strips with the two-zero-bid cutoff, per-expiry variance, and interpolation to a constant maturity (30 days by default).

    Arguments: near: {minutes_to_expiry,rate,options}, next?: {minutes_to_expiry,rate,options}, days?: number

  • risk_neutral_densityRisk-neutral density from option prices

    Recover the market's risk-neutral distribution from call prices across strikes (Breeden-Litzenberger): density and cumulative probability at each strike, its mean, volatility, skewness and kurtosis, probabilities beyond chosen levels, and strikes where the density is negative (butterfly arbitrage).

    Arguments: strikes: number[], call_prices: number[], years: number, rate?: number, levels?: number[]

Technical indicators

30
  • smaSimple moving average

    Compute the simple moving average of closing prices over a lookback.

    Arguments: close: number[], period?: integer, tail?: integer

  • emaExponential moving average

    Compute the exponential moving average (seeded with the simple average, as TA-Lib does).

    Arguments: close: number[], period?: integer, tail?: integer

  • wmaWeighted moving average

    Compute the linearly weighted moving average (latest price weighted most).

    Arguments: close: number[], period?: integer, tail?: integer

  • demaDouble exponential moving average

    Compute the double exponential moving average (2 EMA - EMA of EMA), which lags less than an EMA.

    Arguments: close: number[], period?: integer, tail?: integer

  • temaTriple exponential moving average

    Compute the triple exponential moving average (3 EMA - 3 EMA2 + EMA3).

    Arguments: close: number[], period?: integer, tail?: integer

  • hull_moving_averageHull moving average

    Compute the Hull moving average, WMA(2 WMA(n/2) - WMA(n), sqrt n), a fast, smooth trend line.

    Arguments: close: number[], period?: integer, tail?: integer

  • kamaKaufman adaptive moving average

    Compute Kaufman's adaptive moving average, which speeds up in trends and slows in noise (efficiency ratio, fast 2, slow 30).

    Arguments: close: number[], period?: integer, tail?: integer

  • rsiRelative strength index

    Compute Wilder's relative strength index (0-100): above 70 often read as overbought, below 30 as oversold.

    Arguments: close: number[], period?: integer, tail?: integer

  • macdMACD

    Compute MACD (fast EMA - slow EMA), its signal line and histogram, as TA-Lib does.

    Arguments: close: number[], fast?: integer, slow?: integer, signal?: integer, tail?: integer

  • bollinger_bandsBollinger Bands

    Compute Bollinger Bands: a moving average with bands k population standard deviations above and below, plus %B and bandwidth.

    Arguments: close: number[], period?: integer, deviations?: number, tail?: integer

  • stochasticStochastic oscillator

    Compute the slow stochastic oscillator: %K (smoothed position of the close in the high-low range) and %D.

    Arguments: high: number[], low: number[], close: number[], k_period?: integer, k_smooth?: integer, d_period?: integer, tail?: integer

  • williams_rWilliams %R

    Compute Williams %R (-100 to 0): where the close sits in the recent high-low range.

    Arguments: high: number[], low: number[], close: number[], period?: integer, tail?: integer

  • cciCommodity channel index

    Compute the commodity channel index: typical price's distance from its average in units of mean absolute deviation.

    Arguments: high: number[], low: number[], close: number[], period?: integer, tail?: integer

  • atrAverage true range

    Compute Wilder's average true range and its percent of price (NATR), the standard volatility measure for stops and sizing.

    Arguments: high: number[], low: number[], close: number[], period?: integer, tail?: integer

  • adxAverage directional index

    Compute Wilder's ADX trend strength with +DI and -DI (TA-Lib's smoothing): ADX above 25 is usually read as trending.

    Arguments: high: number[], low: number[], close: number[], period?: integer, tail?: integer

  • obvOn-balance volume

    Compute on-balance volume, the running sum of volume signed by the close's direction.

    Arguments: close: number[], volume: number[], tail?: integer

  • money_flow_indexMoney flow index

    Compute the money flow index (volume-weighted RSI, 0-100) from typical price and volume.

    Arguments: high: number[], low: number[], close: number[], volume: number[], period?: integer, tail?: integer

  • rate_of_changeRate of change and momentum

    Compute rate of change (percent change over n bars) and momentum (price difference over n bars).

    Arguments: close: number[], period?: integer, tail?: integer

  • trixTRIX

    Compute TRIX, the one-bar percent change of a triple-smoothed EMA, a filtered momentum oscillator.

    Arguments: close: number[], period?: integer, tail?: integer

  • aroonAroon indicator

    Compute Aroon up and down (0-100: how recently the highest high and lowest low occurred) and the Aroon oscillator.

    Arguments: high: number[], low: number[], period?: integer, tail?: integer

  • chande_momentumChande momentum oscillator

    Compute the Chande momentum oscillator (-100 to 100) with Wilder smoothing, as TA-Lib does.

    Arguments: close: number[], period?: integer, tail?: integer

  • ultimate_oscillatorUltimate oscillator

    Compute Williams' ultimate oscillator, blending buying pressure over three horizons (7, 14, 28 by default).

    Arguments: high: number[], low: number[], close: number[], short?: integer, medium?: integer, long?: integer, tail?: integer

  • accumulation_distributionAccumulation/distribution and Chaikin oscillator

    Compute the Chaikin accumulation/distribution line and the Chaikin oscillator (fast EMA - slow EMA of the line).

    Arguments: high: number[], low: number[], close: number[], volume: number[], fast?: integer, slow?: integer, tail?: integer

  • donchian_channelsDonchian channels

    Compute Donchian channels: the highest high and lowest low over a lookback and their midpoint (breakout systems).

    Arguments: high: number[], low: number[], period?: integer, tail?: integer

  • keltner_channelsKeltner channels

    Compute Keltner channels: an EMA of the close with bands a multiple of ATR above and below.

    Arguments: high: number[], low: number[], close: number[], period?: integer, atr_period?: integer, multiplier?: number, tail?: integer

  • vwapVolume-weighted average price

    Compute the cumulative volume-weighted average price from typical price, or a rolling VWAP over a window.

    Arguments: high: number[], low: number[], close: number[], volume: number[], window?: integer, tail?: integer

  • ichimoku_cloudIchimoku cloud

    Compute the Ichimoku lines: conversion (tenkan), base (kijun), leading spans A and B (shown at the bar they are computed, not shifted forward) and lagging span.

    Arguments: high: number[], low: number[], close: number[], conversion?: integer, base?: integer, span_b?: integer, tail?: integer

  • rolling_zscoreRolling z-score

    Compute each price's z-score against its rolling mean and sample standard deviation, the basic mean-reversion signal.

    Arguments: close: number[], period?: integer, tail?: integer

  • stochastic_rsiStochastic RSI

    Compute the stochastic RSI: where RSI sits in its own recent range (%K, unsmoothed by default as in TA-Lib) and its moving average %D.

    Arguments: close: number[], period?: integer, stoch_period?: integer, k_smooth?: integer, d_period?: integer, tail?: integer

  • parabolic_sarParabolic SAR

    Compute Wilder's parabolic stop-and-reverse trailing stop with its trend direction (acceleration 0.02 step, 0.2 max by default).

    Arguments: high: number[], low: number[], step?: number, max_step?: number, tail?: integer

Econometrics and tests

27
  • linear_regressionLinear regression with robust errors

    Fit ordinary least squares of y on several regressors with classical, heteroskedasticity-robust (HC1) or Newey-West HAC standard errors, R-squared, F-test and AIC.

    Arguments: y: number[], x: number[][], names?: string[], constant?: boolean, standard_errors?: classical|hc1|hac, lags?: integer

  • factor_regressionFactor model regression (alpha and betas)

    Regress a strategy's excess returns on factor returns (e.g. Fama-French market, size, value, momentum) with Newey-West errors: annualized alpha, its t-stat, factor betas and R-squared.

    Arguments: returns: number[], factors: number[][], factor_names?: string[], periods_per_year?: number, lags?: integer

  • adf_testAugmented Dickey-Fuller unit root test

    Test a price, spread or rate series for a unit root (non-stationarity) with the Augmented Dickey-Fuller test: statistic, MacKinnon p-value, critical values and the AIC-chosen lag.

    Arguments: series: number[], regression?: c|ct|n, max_lag?: integer, autolag?: boolean

  • kpss_testKPSS stationarity test

    Test the null that a series is level- or trend-stationary with the KPSS test (Hobijn lag rule), complementing ADF; p-values are table-interpolated within 0.01-0.10.

    Arguments: series: number[], regression?: c|ct, lags?: integer

  • variance_ratio_testLo-MacKinlay variance ratio test

    Test the random-walk hypothesis on prices with the Lo-MacKinlay variance ratio at one or more horizons (overlapping, de-biased, heteroskedasticity-robust): above 1 means trending, below 1 mean-reverting.

    Arguments: prices: number[], horizons?: integer[], robust?: boolean

  • cointegration_testEngle-Granger cointegration test

    Test whether two or more price series are cointegrated (Engle-Granger): hedge ratios, ADF on the residual spread with MacKinnon p-value and critical values, and the spread's half-life.

    Arguments: y: number[], x: number[][], trend?: c|ct, max_lag?: integer

  • mean_reversion_fitMean reversion (Ornstein-Uhlenbeck) fit

    Fit an AR(1) / Ornstein-Uhlenbeck model to a spread or price series: half-life, mean, speed of reversion, equilibrium volatility and the current z-score.

    Arguments: series: number[], dt?: number

  • garch_volatilityGARCH(1,1) volatility model

    Fit a GARCH(1,1) model with constant mean by maximum likelihood: omega, alpha, beta, persistence, long-run volatility, volatility half-life and the next-period volatility forecast.

    Arguments: returns: number[], periods_per_year?: number, horizon?: integer

  • ewma_volatilityEWMA (RiskMetrics) volatility

    Compute exponentially weighted volatility (RiskMetrics, lambda 0.94 by default): the current annualized estimate and optionally the full series.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, lambda?: number, include_series?: boolean

  • range_volatilityRange-based volatility (OHLC)

    Estimate volatility from open, high, low and close prices with close-to-close, Parkinson, Garman-Klass, Rogers-Satchell and Yang-Zhang estimators, annualized.

    Arguments: open: number[], high: number[], low: number[], close: number[], periods_per_year?: number

  • probabilistic_sharpe_ratioProbabilistic Sharpe ratio

    Compute the probability that the true Sharpe ratio exceeds a benchmark given the track record's length, skewness and kurtosis (Bailey and López de Prado), and the minimum track record length needed. Takes returns or prices, or just the observed Sharpe and the number of observations.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, sharpe_annual?: number, observations?: integer, skew?: number, kurtosis?: number, benchmark_sharpe?: number, confidence?: number

  • deflated_sharpe_ratioDeflated Sharpe ratio

    Deflate a backtest's Sharpe ratio for the number of strategies tried (Bailey and López de Prado 2014): the expected maximum Sharpe under the null and the probability the result beats it. Takes returns or prices, or just the observed Sharpe and the number of observations, with the trials' Sharpe variance or Sharpes.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, sharpe_annual?: number, observations?: integer, skew?: number, kurtosis?: number, trials: integer, trial_sharpes?: number[], trial_sharpe_variance?: number

  • pca_factorsPrincipal components of returns

    Run principal component analysis on asset returns (correlation or covariance): explained variance per component, cumulative share and each component's loadings.

    Arguments: returns: number[][], use_covariance?: boolean, components?: integer

  • rolling_betaRolling beta

    Compute a rolling-window beta (and correlation) of returns against a benchmark: latest, average, minimum and maximum, optionally the full series.

    Arguments: returns: number[], benchmark: number[], window: integer, include_series?: boolean

  • granger_causalityGranger causality test

    Test whether past values of x help predict y beyond y's own past (Granger causality), with the F-test at each lag up to a maximum.

    Arguments: y: number[], x: number[], max_lag: integer

  • arch_effects_testARCH effects (Engle LM) test

    Test demeaned returns for volatility clustering with Engle's ARCH Lagrange multiplier test: LM statistic, chi-squared p-value, and the F version.

    Arguments: returns: number[], lags?: integer

  • mean_return_testTest that mean return is zero

    Test whether a strategy's mean return differs from zero (or a target) with a one-sample t-test and a Newey-West t-statistic robust to autocorrelation.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, target?: number, lags?: integer

  • compare_sharpe_ratiosCompare two Sharpe ratios

    Test whether two strategies' Sharpe ratios differ (Jobson-Korkie with Memmel's correction) using their returns over the same periods.

    Arguments: returns_a: number[], returns_b: number[], periods_per_year?: number

  • welch_t_testWelch two-sample t-test

    Test whether two samples (e.g. returns in two regimes, before and after a change) have different means, without assuming equal variances (Welch).

    Arguments: sample_a: number[], sample_b: number[]

  • markov_regime_switchingMarkov regime-switching model

    Fit a Hamilton Markov-switching model with a mean and volatility per regime (2 or 3 regimes) by maximum likelihood: regime means and volatilities, transition probabilities, expected durations, the current regime probabilities and how much time was spent in each.

    Arguments: returns: number[], regimes?: integer, periods_per_year?: number, include_probabilities?: boolean

  • johansen_cointegrationJohansen cointegration test

    Test how many cointegrating relationships tie several price series together (Johansen trace and maximum-eigenvalue tests with Osterwald-Lenum critical values), with the rank chosen at 5% and the normalized cointegrating vectors.

    Arguments: prices: number[][], log_prices?: boolean, det_order?: integer, lags?: integer

  • recursive_stability_testParameter stability (CUSUM)

    Check whether a regression's coefficients stayed stable over time: recursive least squares coefficient paths, and the CUSUM and CUSUM-of-squares tests of Brown, Durbin and Evans with 5% bounds and the first period each one crosses.

    Arguments: y: number[], x?: number[][], add_constant?: boolean

  • chow_break_testStructural break (Chow) test

    Test for a structural break in a regression at a known period (Chow F-test), or scan every candidate break inside a trimmed range for the largest F statistic and where it falls.

    Arguments: y: number[], x?: number[][], break_period?: integer, trim?: number

  • har_rv_forecastHAR realized-volatility forecast

    Fit Corsi's heterogeneous autoregressive (HAR) model of realized variance on its daily, weekly and monthly averages, with Newey-West errors, and forecast variance and volatility over the next horizon.

    Arguments: realized_variance: number[], horizon?: integer, log?: boolean, hac_lags?: integer, periods_per_year?: number

  • realized_volatility_measuresRealized volatility and jumps

    From intraday returns per day, compute realized variance, bipower variation, the jump component and the Barndorff-Nielsen-Shephard jump test (tripower quarticity), realized semivariances, realized skewness and kurtosis, and the daily series for HAR forecasts.

    Arguments: intraday_returns: number[][], jump_level?: number, periods_per_year?: number, include_series?: boolean

  • dependence_measuresDependence beyond correlation

    Measure how two series move together: Pearson, Spearman and Kendall correlations with p-values, distance correlation (catches nonlinear dependence), and empirical lower and upper tail dependence (do they crash together?).

    Arguments: x: number[], y: number[], tail_quantile?: number

  • bootstrap_confidence_intervalBlock-bootstrap confidence interval

    Put a confidence interval on a performance statistic (Sharpe, Sortino, CAGR, volatility, max drawdown, Calmar, mean) with the stationary block bootstrap, which keeps autocorrelation and volatility clustering; also gives the bootstrap standard error and the share of resamples at or below zero.

    Arguments: returns: number[], statistic?: sharpe|sortino|cagr|volatility|..., confidence?: number, reps?: integer, block?: integer, seed?: integer, periods_per_year?: number

Exotic options

9
  • barrier_optionBarrier option (knock-in, knock-out)

    Price a continuously monitored single-barrier option (down/up, in/out, call/put, with rebate) in closed form (Reiner-Rubinstein), with the vanilla price and the barrier discount.

    Arguments: type: call|put, barrier_type: down_in|down_out|up_in|up_out, spot: number, strike: number, barrier: number, rebate?: number, years: number, rate?: number, dividend_yield?: number, volatility: number

  • asian_option_geometricGeometric average Asian option

    Price a continuously averaged geometric-average-price Asian option in closed form (Kemna-Vorst); a lower bound and control variate for the arithmetic Asian.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, volatility: number

  • heston_optionHeston stochastic volatility option

    Price a European option under the Heston stochastic-volatility model by Fourier integration of its characteristic function, with delta, in-the-money probability and the Feller condition.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, v0: number, kappa: number, theta: number, sigma: number, rho: number

  • sabr_volatilitySABR implied volatility

    Compute the Black implied volatility of a strike under the SABR model (Hagan et al. 2002) from alpha, beta, nu and rho, optionally across several strikes for a smile.

    Arguments: forward: number, strikes: number[], years: number, alpha: number, beta: number, nu: number, rho: number

  • spread_optionSpread option (Kirk)

    Price a European option on the spread between two futures (F1 - F2 - K) with Kirk's approximation, as used for crack and spark spreads.

    Arguments: type: call|put, forward1: number, forward2: number, strike: number, years: number, rate?: number, volatility1: number, volatility2: number, correlation: number

  • exchange_optionExchange option (Margrabe)

    Price the option to exchange one asset for another, max(Q1 S1 - Q2 S2, 0), in closed form (Margrabe), with dividend yields on both.

    Arguments: spot1: number, spot2: number, quantity1?: number, quantity2?: number, years: number, dividend_yield1?: number, dividend_yield2?: number, volatility1: number, volatility2: number, correlation: number

  • lookback_optionFloating-strike lookback option

    Price a continuously monitored floating-strike lookback option (Goldman-Sosin-Gatto): a call pays the final price minus the minimum, a put the maximum minus the final price.

    Arguments: type: call|put, spot: number, extreme?: number, years: number, rate?: number, dividend_yield?: number, volatility: number

  • chooser_optionSimple chooser option

    Price a simple chooser option, which lets the holder decide at a choice date whether it is a call or a put with the same strike and expiry (Rubinstein).

    Arguments: spot: number, strike: number, years: number, choice_years: number, rate?: number, dividend_yield?: number, volatility: number

  • jump_diffusion_optionMerton jump-diffusion option

    Price a European option under Merton's jump-diffusion model (lognormal jumps) as a Poisson-weighted sum of Black-Scholes prices.

    Arguments: type: call|put, spot: number, strike: number, years: number, rate?: number, dividend_yield?: number, volatility: number, jump_intensity: number, jump_mean: number, jump_volatility: number

Bonds and rates

15
  • bond_priceBond price, duration and convexity

    Price a fixed-rate bond from its yield on real dates and a day count: clean and dirty price, accrued interest, Macaulay and modified duration, convexity and DV01.

    Arguments: settlement: string, maturity: string, coupon_rate: number, frequency?: number|number|number|number, day_count?: 30/360|ACT/360|ACT/365F|ACT/ACT, face?: number, yield: number

  • bond_yieldBond yield to maturity

    Solve a fixed-rate bond's yield to maturity from its clean price, with duration, convexity and DV01 at that yield.

    Arguments: settlement: string, maturity: string, coupon_rate: number, frequency?: number|number|number|number, day_count?: 30/360|ACT/360|ACT/365F|ACT/ACT, face?: number, clean_price: number

  • zero_coupon_bondZero-coupon bond price and yield

    Price a zero-coupon bond from its yield or solve the yield from its price, under annual, periodic or continuous compounding, with duration and convexity.

    Arguments: years: number, face?: number, yield?: number, price?: number, compounding?: number|number|number|number|string

  • bootstrap_zero_curveBootstrap a zero curve from par yields

    Bootstrap discount factors, zero rates (continuous and periodic) and period forward rates from par yields, interpolating par yields linearly onto the coupon grid.

    Arguments: years: number[], par_yields: number[], frequency?: number|number|number|number

  • forward_rateForward rate between two dates

    Compute the forward rate between two maturities implied by their zero rates, under continuous, periodic or simple compounding, with the forward discount factor.

    Arguments: t1: number, t2: number, zero_rate_1: number, zero_rate_2: number, compounding?: number|number|number|number|string|string

  • nelson_siegel_fitNelson-Siegel yield curve fit

    Fit a Nelson-Siegel curve (level, slope, curvature, decay tau) to observed yields by least squares, with fitted yields and RMSE; tau is searched when not given.

    Arguments: years: number[], yields: number[], tau?: number

  • interest_rate_swapInterest rate swap value and par rate

    Value a spot-starting fixed-for-floating swap on a zero curve (single curve): par swap rate, value to the fixed payer, fixed-leg annuity and DV01s.

    Arguments: curve: {years,zero_rates}, years: number, fixed_rate: number, notional?: number, fixed_frequency?: number|number|number|number

  • forward_rate_agreementForward rate agreement value

    Value a forward rate agreement on a zero curve: the simple forward rate for the period and the value to the party that pays the fixed rate.

    Arguments: curve: {years,zero_rates}, start: number, end: number, fixed_rate: number, notional?: number

  • z_spreadZ-spread over a zero curve

    Solve a fixed-rate bond's z-spread: the constant spread over a continuously compounded zero curve that reprices its cash flows to the market dirty price.

    Arguments: settlement: string, maturity: string, coupon_rate: number, frequency?: number|number|number|number, day_count?: 30/360|ACT/360|ACT/365F|ACT/ACT, face?: number, clean_price: number, curve: {years,zero_rates}

  • credit_hazard_rateHazard rate and default probability from a spread

    Convert a credit spread and recovery rate into a constant hazard rate (credit triangle), survival and default probabilities over a horizon, and the reverse.

    Arguments: spread?: number, hazard_rate?: number, recovery?: number, years?: number

  • short_rate_bond_priceVasicek or CIR zero-coupon bond

    Price a zero-coupon bond and its yield under the Vasicek or Cox-Ingersoll-Ross short-rate model in closed form.

    Arguments: model: vasicek|cir, short_rate: number, mean_reversion: number, long_run_rate: number, volatility: number, years: number

  • treasury_bill_yieldsTreasury bill yields

    Convert a T-bill's price or bank discount rate into the discount yield, bond-equivalent (investment) yield, money-market yield and effective annual yield.

    Arguments: days: integer, price?: number, discount_rate?: number

  • key_rate_durationsKey rate durations

    Measure a fixed-rate bond's sensitivity to each pillar of a zero curve: bump one pillar by 1 bp (triangular bump, linear in between) and reprice, giving key rate DV01s and durations that sum to the parallel figure.

    Arguments: settlement: string, maturity: string, coupon_rate: number, frequency?: number|number|number|number, day_count?: 30/360|ACT/360|ACT/365F|ACT/ACT, face?: number, curve: {years,zero_rates}, spread?: number

  • breakeven_inflationBreakeven inflation

    Compute breakeven inflation from a nominal and a real (inflation-linked) yield of the same maturity, exactly (Fisher) and approximately, and the real yield implied by an inflation view.

    Arguments: nominal_yield: number, real_yield: number, expected_inflation?: number

  • merton_credit_riskMerton structural credit risk

    Back out a firm's asset value and asset volatility from its equity value and equity volatility with Merton's model (equity as a call on assets), then the distance to default, default probability, the implied credit spread and the value of the debt.

    Arguments: equity_value: number, equity_volatility: number, debt: number, years?: number, rate?: number, asset_drift?: number

Portfolio risk

7
  • portfolio_varPortfolio VaR and expected shortfall

    Compute a positions portfolio's historical and parametric (normal) value at risk and expected shortfall from asset return history, with each position's contribution and the diversification benefit.

    Arguments: positions: number[], returns: number[][], confidence?: number, horizon?: integer, names?: string[]

  • stress_testScenario stress test

    Apply named scenarios (a return shock per position, or a market shock passed through each position's beta) to a portfolio and report the P&L of each scenario and the worst position.

    Arguments: positions: number[], names?: string[], betas?: number[], scenarios: {name,shocks,market_shock}[]

  • option_scenario_gridOption book scenario grid

    Revalue a book of European options and stock under a grid of spot moves and volatility shifts (full Black-Scholes revaluation), with P&L per cell and the book's current Greeks.

    Arguments: spot: number, rate?: number, dividend_yield?: number, legs: {type,quantity,strike,years,volatility}[], spot_moves?: number[], vol_shifts?: number[], days_forward?: number

  • exposure_and_hedgeGross, net and beta-adjusted exposure

    Summarize a long/short book's gross, net and beta-adjusted exposure and size an index hedge (futures contracts or ETF shares) that neutralizes the beta.

    Arguments: positions: number[], betas: number[], equity?: number, hedge_price?: number, hedge_multiplier?: number, hedge_beta?: number

  • concentration_metricsConcentration metrics

    Measure how concentrated a portfolio is: Herfindahl index, effective number of positions, largest and top-k shares, and the Gini coefficient of weights.

    Arguments: weights: number[], top_k?: integer

  • liquidation_horizonLiquidation horizon

    Estimate how many days each position takes to exit at a maximum share of average daily volume, and how much of the book can be liquidated within 1, 5 and 20 days.

    Arguments: shares: number[], prices: number[], adv: number[], participation?: number, names?: string[]

  • extreme_value_tailExtreme value tail risk (EVT)

    Model the loss tail with extreme value theory: fit a generalized Pareto distribution to losses beyond a high threshold (peaks over threshold) and estimate value at risk and expected shortfall far into the tail, with the Hill tail index.

    Arguments: returns: number[], threshold_quantile?: number, confidence?: number[]

Return series

4
  • convert_returnsConvert prices and returns

    Convert between prices, simple returns and log returns, or rebase a price series to start at 100; returns the converted series.

    Arguments: values: number[], from: prices|simple|log, to: prices|simple|log|rebased, start_value?: number

  • resample_returnsResample returns to weeks, months or years

    Compound periodic returns into calendar weeks (ISO), months, quarters or years using their dates.

    Arguments: returns: number[], dates: string[], to: week|month|quarter|year

  • monthly_returns_tableCalendar monthly returns table

    Build the year-by-month return table from periodic returns and dates, with each year's compounded total, the best and worst months and the share of positive months.

    Arguments: returns: number[], dates: string[]

  • brinson_attributionBrinson-Fachler performance attribution

    Attribute active return to allocation, selection and interaction effects by segment (Brinson-Fachler) from portfolio and benchmark weights and returns.

    Arguments: segments: string[], portfolio_weights: number[], benchmark_weights: number[], portfolio_returns: number[], benchmark_returns: number[]

Portfolio construction

15
  • portfolio_riskPortfolio risk decomposition

    Decompose a portfolio's volatility into each asset's risk contribution, with marginal risk, diversification ratio, effective number of assets, parametric VaR and ex-ante tracking error to a benchmark.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], weights: number[], benchmark_weights?: number[], confidence?: number

  • min_variance_portfolioMinimum variance portfolio

    Find the fully invested minimum-variance portfolio, long-only with an optional weight cap (exact active-set solution) or unconstrained (closed form).

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], long_only?: boolean, max_weight?: number

  • max_sharpe_portfolioMaximum Sharpe (tangency) portfolio

    Find the portfolio with the highest Sharpe ratio, long-only (exact) or unconstrained (closed form tangency), with its expected return, volatility and Sharpe.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], risk_free?: number, long_only?: boolean

  • mean_variance_portfolioMean-variance portfolio for a target

    Find the minimum-variance portfolio that reaches a target expected return, or the utility-maximizing portfolio for a risk aversion, long-only or unconstrained.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], target_return?: number, risk_aversion?: number, long_only?: boolean, max_weight?: number

  • risk_parity_portfolioRisk parity (equal risk contribution)

    Find long-only weights where every asset contributes equally (or by a given budget) to portfolio volatility, solved by Newton's method.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], risk_budgets?: number[]

  • inverse_volatility_weightsInverse volatility weights

    Weight assets in proportion to the inverse of their volatility (or variance), the simple risk-balancing heuristic.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], use_variance?: boolean

  • hierarchical_risk_parityHierarchical risk parity

    Allocate with López de Prado's hierarchical risk parity: single-linkage clustering on correlation distance, quasi-diagonal ordering and recursive bisection.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[]

  • efficient_frontierEfficient frontier

    Trace the efficient frontier: minimum volatility at evenly spaced target returns from the minimum-variance portfolio to the highest-return asset, with weights.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], points?: integer, long_only?: boolean, max_weight?: number

  • black_littermanBlack-Litterman posterior returns

    Blend market-implied equilibrium returns with your views (absolute or relative, with confidence) into Black-Litterman posterior returns and the unconstrained optimal weights.

    Arguments: covariance: number[][], market_weights: number[], risk_aversion?: number, tau?: number, views: {weights,expected_return,variance}[], assets?: string[]

  • covariance_shrinkageLedoit-Wolf covariance shrinkage

    Estimate a well-conditioned covariance matrix by Ledoit-Wolf shrinkage toward a scaled identity, with the shrinkage intensity and condition numbers before and after.

    Arguments: returns: number[][], periods_per_year?: number

  • correlation_matrixCorrelation matrix

    Compute Pearson or Spearman rank correlations between assets, with the average pairwise correlation and the largest eigenvalue's share (how much one factor drives everything).

    Arguments: returns: number[][], method?: pearson|spearman, assets?: string[]

  • rebalance_tradesRebalancing trades

    Turn current holdings and target weights into the share trades that rebalance the portfolio, with turnover, optional no-trade bands, and cash left over.

    Arguments: holdings: number[], prices: number[], target_weights: number[], cash?: number, band?: number, whole_shares?: boolean, assets?: string[]

  • kelly_portfolioMulti-asset Kelly weights

    Compute growth-optimal (Kelly) weights across assets, inverse covariance times excess returns, with half-Kelly and the implied leverage and growth rate.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], risk_free?: number, fraction?: number

  • max_diversification_portfolioMaximum diversification portfolio

    Find the long-only portfolio with the highest diversification ratio (weighted average volatility over portfolio volatility), Choueifaty and Coignard's most-diversified portfolio.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[]

  • index_tracking_portfolioIndex tracking portfolio

    Find long-only weights in a subset of assets that minimize ex-ante tracking error to a benchmark's weights, with an optional per-asset cap.

    Arguments: returns?: number[][], covariance?: number[][], expected_returns?: number[], periods_per_year?: number, assets?: string[], benchmark_weights: number[], allowed?: boolean[], max_weight?: number

Execution

7
  • almgren_chriss_scheduleAlmgren-Chriss optimal execution

    Compute the Almgren-Chriss optimal liquidation schedule for a block: holdings and trades per period, expected impact cost and its standard deviation for a given risk aversion.

    Arguments: shares: number, periods: integer, period_length?: number, volatility: number, temporary_impact: number, permanent_impact?: number, fixed_cost?: number, risk_aversion: number

  • market_impact_estimateSquare-root market impact

    Estimate the cost of an order with the square-root impact law (cost = Y x volatility x sqrt(order / daily volume)) plus half the spread, in basis points and currency.

    Arguments: order_shares: number, daily_volume: number, daily_volatility: number, price: number, spread_bps?: number, coefficient?: number

  • implementation_shortfallImplementation shortfall

    Measure an executed order's implementation shortfall against the decision price, split into delay, execution (impact), opportunity cost of unfilled shares and fees.

    Arguments: side: buy|sell, order_shares: number, decision_price: number, arrival_price: number, fills: any[][], final_price: number, fees?: number

  • execution_scheduleTWAP / VWAP order schedule

    Split an order across time buckets evenly (TWAP) or by an expected volume profile (VWAP), capped at a maximum participation rate, with what cannot be done within the horizon.

    Arguments: order_shares: number, bucket_volumes: number[], max_participation?: number, method?: vwap|twap

  • spread_estimatorsBid-ask spread from prices (Roll, Corwin-Schultz)

    Estimate the effective bid-ask spread from trade prices alone (Roll 1984) and from daily highs and lows (Corwin-Schultz 2012) when quotes are not available.

    Arguments: close: number[], high?: number[], low?: number[]

  • liquidity_measuresAmihud illiquidity and Kyle's lambda

    Measure price impact per unit of trading: Amihud illiquidity (|return| per currency traded) and Kyle's lambda (price change per signed volume, by regression).

    Arguments: returns: number[], dollar_volume: number[], price_changes?: number[], signed_volume?: number[]

  • order_book_analysisOrder book walk and microprice

    Analyze an order book snapshot: mid, spread, microprice, depth imbalance, and the average fill price and slippage of a market order of a given size walking the book.

    Arguments: bids: any[][], asks: any[][], order_size?: number, side?: buy|sell

Position sizing

7
  • position_size_from_stopPosition size from a stop loss

    Size a trade so that hitting the stop loses a fixed fraction of equity: shares, notional, capital at risk and leverage, optionally capped by a maximum position weight.

    Arguments: equity: number, risk_fraction: number, entry: number, stop: number, max_weight?: number, lot_size?: integer

  • volatility_target_sizeVolatility-targeted position

    Scale a position so its expected volatility matches a target: the weight (leverage) from the asset's volatility, shares for a given equity, optionally capped.

    Arguments: returns?: number[], prices?: number[], periods_per_year?: number, asset_volatility?: number, target_volatility: number, equity?: number, price?: number, max_leverage?: number

  • optimal_fOptimal f (Ralph Vince)

    Find the fraction f of the largest loss to risk per trade that maximizes terminal wealth over a list of trade results (Vince's optimal f), with the geometric mean and the f-based position size.

    Arguments: trades: number[], equity?: number

  • trade_expectancyTrade expectancy and break-even win rate

    Compute a trading rule's expectancy per trade after costs, the break-even win rate for its payoff, and the payoff needed at its win rate.

    Arguments: win_rate: number, average_win: number, average_loss: number, cost_per_trade?: number

  • drawdown_probabilityProbability of a drawdown

    Estimate the probability that a strategy with a given return and volatility ever falls a given fraction below its starting equity (drifted Brownian motion, continuous), and within a horizon.

    Arguments: annual_return: number, annual_volatility: number, drawdown: number, years?: number

  • leverage_and_marginLeverage, margin and liquidation distance

    Compute leverage, initial and maintenance margin, free margin, and the adverse price move that triggers a margin call for a leveraged position.

    Arguments: notional: number, equity: number, initial_margin_rate: number, maintenance_margin_rate: number

  • var_position_limitPosition limit from a VaR budget

    Find the largest position whose one-day (or n-day) parametric value at risk stays within a budget, given the asset's volatility.

    Arguments: var_budget: number, annual_volatility: number, confidence?: number, days?: number, price?: number

Crypto and currencies

9
  • funding_rate_carryPerpetual funding rate carry

    Annualize perpetual-futures funding rates (simple APR and compounded APY) and compute the funding a position pays or earns over a holding period; accepts one rate or a history.

    Arguments: funding_rates: number[], interval_hours?: number, notional?: number, side?: long|short, days?: number

  • futures_basisFutures basis and implied rate

    Compute a dated future's basis to spot, its annualized carry (simple and compounded) and the implied financing rate, for cash-and-carry trades.

    Arguments: spot: number, future: number, days: number, funding_rate?: number

  • liquidation_priceIsolated-margin liquidation price

    Estimate a leveraged position's liquidation price under isolated margin: initial margin = 1/leverage, liquidated when equity falls to the maintenance rate (exchange formulas add fees and tiers).

    Arguments: entry: number, leverage: number, side: long|short, maintenance_margin_rate?: number

  • fx_forwardFX forward by covered interest parity

    Price an FX forward from spot and the two currencies' money-market rates (covered interest parity, ACT/360 or ACT/365), with forward points in pips, or back out the implied rate from a quoted forward.

    Arguments: spot: number, base_rate: number, quote_rate?: number, days: number, forward?: number, basis_days?: number|number, pip?: number

  • fx_cross_rateFX cross rate with bid and ask

    Derive a cross rate's bid and ask from two quotes against a common currency (e.g. EURJPY from EURUSD and USDJPY), handling which side each leg is quoted on.

    Arguments: leg1: {bid,ask}, leg1_pair: string, leg2: {bid,ask}, leg2_pair: string, target: string

  • triangular_arbitrageTriangular arbitrage check

    Check three currency (or crypto) quotes for triangular arbitrage after spreads and fees: the return of each direction around the triangle.

    Arguments: pairs: {pair,bid,ask}[], fee_rate?: number

  • pip_valueFX pip value and position size

    Compute the value of one pip for a lot size in the account currency, and the lot size that risks a given amount over a stop distance in pips.

    Arguments: price: number, units?: number, pip?: number, quote_to_account?: number, risk_amount?: number, stop_pips?: number

  • carry_trade_returnCurrency carry trade return

    Decompose a carry trade's return into the interest differential and the spot move, and find the break-even depreciation of the high-yield currency.

    Arguments: funding_rate: number, investment_rate: number, spot_start: number, spot_end: number, days: number

  • impermanent_lossAMM impermanent loss

    Compute impermanent (divergence) loss of a liquidity position versus holding, for a constant-product pool or a concentrated range (Uniswap v3 style), given the price change.

    Arguments: price_ratio: number, range_lower?: number, range_upper?: number, fees_earned?: number

Strategy backtests

20
  • backtest_ma_crossoverBacktest a moving-average crossover

    Backtest a fast/slow moving-average crossover on your prices with costs and no lookahead: CAGR, Sharpe, drawdown, turnover, cost drag and buy-and-hold for comparison.

    Arguments: prices: number[], fast?: integer, slow?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_time_series_momentumBacktest time-series momentum

    Backtest time-series (absolute) momentum: hold the asset when its trailing return is positive, optionally volatility-targeted, with costs and no lookahead.

    Arguments: prices: number[], lookback?: integer, vol_target?: number, vol_lookback?: integer, max_leverage?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_breakoutBacktest a channel breakout

    Backtest a Donchian channel breakout (turtle-style entries on new highs, exits on shorter lows) with costs and no lookahead.

    Arguments: prices: number[], entry?: integer, exit?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_zscore_reversionBacktest z-score mean reversion

    Backtest mean reversion on a rolling z-score of price: buy stretched lows (and short stretched highs), exit near the mean, with costs.

    Arguments: prices: number[], window?: integer, entry_z?: number, exit_z?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_rsi_reversionBacktest RSI mean reversion

    Backtest a classic RSI oversold strategy: buy when RSI is below a threshold, sell when it recovers, with costs and no lookahead.

    Arguments: prices: number[], period?: integer, lower?: number, exit_level?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_volatility_targetBacktest volatility targeting

    Backtest holding an asset scaled to a constant volatility target with trailing realized volatility, leverage cap and rebalance frequency.

    Arguments: prices: number[], target?: number, lookback?: integer, max_leverage?: number, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_cross_sectional_momentumBacktest cross-sectional momentum

    Backtest cross-sectional (relative) momentum across a universe: periodically hold the top assets by trailing return (skipping the latest month), optionally short the bottom.

    Arguments: prices: number[][], lookback?: integer, skip?: integer, top?: integer, top_fraction?: number, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_dual_momentumBacktest dual momentum

    Backtest dual momentum (Antonacci): hold the best-performing risky asset when it beats cash or a safe asset, otherwise move to safety.

    Arguments: prices: number[][], lookback?: integer, rebalance_every?: integer, safe_asset?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_risk_parity_rebalanceBacktest inverse-volatility risk parity

    Backtest a multi-asset inverse-volatility (naive risk parity) portfolio rebalanced periodically, optionally scaled to a volatility target.

    Arguments: prices: number[][], lookback?: integer, rebalance_every?: integer, target_volatility?: number, max_leverage?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_trend_ensembleBacktest a trend ensemble

    Backtest a multi-horizon trend signal: the average of time-series momentum signs over several lookbacks, optionally volatility-targeted, with costs and no lookahead.

    Arguments: prices: number[], lookbacks?: integer[], vol_target?: number, vol_lookback?: integer, max_leverage?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_macd_trendBacktest MACD trend following

    Backtest the MACD line against its signal line (long above, flat or short below) with costs and no lookahead.

    Arguments: prices: number[], fast?: integer, slow?: integer, signal?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_equal_weight_rebalanceBacktest an equal-weight portfolio

    Backtest equal weights across a universe rebalanced on a fixed schedule; the 1/N benchmark that optimized portfolios must beat.

    Arguments: prices: number[][], rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_min_variance_rebalanceBacktest minimum variance

    Backtest the long-only minimum-variance portfolio re-estimated from trailing sample covariance on a fixed schedule, with costs.

    Arguments: prices: number[][], lookback?: integer, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_low_volatilityBacktest the low-volatility anomaly

    Backtest holding the lowest-volatility fraction of a universe, re-ranked on a schedule, with costs and no lookahead.

    Arguments: prices: number[][], lookback?: integer, top_fraction?: number, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_short_term_reversalBacktest short-term reversal

    Backtest buying the recent biggest losers in a universe (and optionally shorting the winners), re-ranked on a schedule, with costs.

    Arguments: prices: number[][], lookback?: integer, top_fraction?: number, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_trend_filter_allocationBacktest a trend-filtered allocation

    Backtest tactical asset allocation where each asset is held only while above its moving average (Faber-style), equal or inverse-volatility weighted.

    Arguments: prices: number[][], sma?: integer, rebalance_every?: integer, weighting?: equal|inverse_vol, vol_lookback?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_high_proximityBacktest 52-week-high momentum

    Backtest holding the assets trading closest to their trailing high (George-Hwang 52-week-high momentum), re-ranked on a schedule.

    Arguments: prices: number[][], window?: integer, top_fraction?: number, rebalance_every?: integer, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_pairs_tradingBacktest pairs trading

    Backtest a pairs trade on two price series: rolling hedge ratio, z-score of the residual spread, market-neutral entries and exits, with costs.

    Arguments: prices: any[][], window?: integer, entry_z?: number, exit_z?: number, curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • backtest_weightsBacktest your own target weights

    Backtest any strategy from your own target weights per period (decided at each close, applied to the next period) with the same costed, drift-aware engine; null rows mean hold.

    Arguments: prices: number[][], weights: (number[]|null)[], curve?: boolean, dates?: string[], cost_bps?: number, periods_per_year?: number, risk_free?: number, long_only?: boolean

  • strategy_sweepParameter sweep with deflated Sharpe

    Run one strategy recipe over a parameter grid (up to 400 variants), rank the variants by Sharpe, and deflate the best one for the number tried, so tuning cannot pass off luck as skill.

    Arguments: recipe: ma_crossover|time_series_momentum|breakout|zscore_reversion|..., arguments: object, grid: object

Strategy sleeve library

8
  • list_sleevesList strategy sleeves

    Browse the library of 399 pre-defined strategy sleeves (18 families: trend, momentum, reversion, volatility, allocation, pairs). Each is a fixed rule with a spec hash; filter by family, data shape or words.

    Arguments: query?: string, family?: ma_crossover|time_series_momentum|trend_ensemble|breakout|..., data?: single|universe|pair, limit?: integer, offset?: integer

  • describe_sleeveDescribe a sleeve

    One sleeve's exact rule, parameters, warm-up, rationale, published references, known risks and spec SHA-256.

    Arguments: id: string

  • run_sleeveRun a sleeve on your prices

    Backtest one library sleeve on your prices with costs and no lookahead: CAGR, Sharpe, drawdown, turnover, cost drag, and the target weights as of the latest close (ready for a paper rebalance).

    Arguments: id: string, prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[]

  • sleeve_tournamentRun every sleeve, corrected for multiple testing

    Run all library sleeves that fit your prices (up to 399) on a common window and rank them, then correct for the search: deflated Sharpe (raw and effective number of trials), White's Reality Check, re-studentized Hansen SPA and Romano-Wolf StepM against a benchmark, and the probability of backtest overfitting (CSCV).

    Arguments: prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[], families?: (ma_crossover|time_series_momentum|trend_ensemble|breakout|...)[], ids?: string[], min_evaluation?: integer, benchmark?: buy_and_hold|cash, reps?: integer, block?: integer, seed?: integer, splits?: integer, top?: integer

  • sleeve_walk_forwardWalk-forward sleeve selection

    Test the selection process itself: at each refit pick the top sleeves by trailing Sharpe, hold them for the next window, repeat. Compares the out-of-sample result with what the picks showed in sample, with holding every sleeve, and with the benchmark.

    Arguments: prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[], families?: (ma_crossover|time_series_momentum|trend_ensemble|breakout|...)[], ids?: string[], min_evaluation?: integer, train?: integer, refit?: integer, top_k?: integer, benchmark?: buy_and_hold|cash

  • combine_sleevesCombine sleeves into one book

    Blend chosen sleeves (equal or trailing inverse-volatility weights, no lookahead) into one book: its statistics, each sleeve's, their correlations, the diversification ratio, and the book's combined asset target weights as of the latest close.

    Arguments: ids: string[], prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[], weighting?: equal|inverse_vol, vol_lookback?: integer, rebalance_every?: integer

  • sleeve_clustersCluster sleeves by behavior

    Group the sleeves that ran on your prices by return correlation (average linkage on sqrt((1 - rho) / 2)), to see how many genuinely different bets the library makes on this data and the best sleeve of each group.

    Arguments: prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[], families?: (ma_crossover|time_series_momentum|trend_ensemble|breakout|...)[], ids?: string[], min_evaluation?: integer, threshold?: number

  • sleeve_regime_mapSleeve performance by market regime

    Score every sleeve that fits your prices in each regime of the benchmark: calm, normal and turbulent volatility (terciles of trailing volatility) and up or down trend (above or below its moving average). Finds sleeves that held up in every regime.

    Arguments: prices: number[]|number[][], cost_bps?: number, periods_per_year?: number, risk_free?: number, asset?: integer, pair?: any[], symbols?: string[], families?: (ma_crossover|time_series_momentum|trend_ensemble|breakout|...)[], ids?: string[], min_evaluation?: integer, vol_lookback?: integer, trend_lookback?: integer, top?: integer

Data checks

10
  • check_price_seriesCheck a price series

    Check a price series for errors before using it: non-positive or missing values, unadjusted splits, outlier returns, stale runs, duplicate, unsorted or gapped timestamps.

    Arguments: prices: number[], dates?: (string|number)[], outlier_z?: number, stale_run?: integer

  • check_ohlc_barsCheck OHLC bars

    Check open-high-low-close-volume bars for impossible values: high below open/close, low above them, negative volume, zero-range bars, and extreme overnight gaps.

    Arguments: open: number[], high: number[], low: number[], close: number[], volume?: number[]

  • check_option_chainCheck an option chain for arbitrage and bad quotes

    Check one expiry of an option chain: crossed or negative quotes, prices outside no-arbitrage bounds, non-monotone or non-convex prices across strikes, put-call parity breaks, and quotes with no implied volatility.

    Arguments: spot: number, years: number, rate?: number, dividend_yield?: number, quotes: {strike,type,bid,ask}[], tolerance?: number

  • check_yield_curveCheck a yield curve

    Check a zero curve for problems: unsorted tenors, discount factors that rise with maturity, negative or jumpy implied forward rates, and kinks far from neighbouring points.

    Arguments: years: number[], zero_rates: number[], max_forward_jump?: number

  • check_funding_ratesCheck perpetual funding data

    Check a perpetual-futures funding history: irregular intervals, rates beyond the venue's cap, outliers, and long one-sided runs, with the annualized range.

    Arguments: funding_rates: number[], timestamps?: (string|number)[], cap?: number, interval_hours?: number

  • check_cross_venue_pricesCheck prices across venues

    Compare the same instrument's prices across venues at the same times: deviation of each venue from the cross-venue median, venues that stop updating, and the worst divergences.

    Arguments: venues: string[], prices: ((number|null)[])[], threshold_bps?: number

  • check_timestampsCheck timestamps

    Check a column of timestamps: unparseable values, duplicates, out-of-order rows, mixed time-zone offsets, dates in the future and weekend entries, with the spacing distribution.

    Arguments: timestamps: (string|number)[], flag_weekends?: boolean, now?: string

  • check_returns_seriesCheck a returns series

    Check a returns series for the usual mistakes: percents instead of fractions, impossible simple returns below -100%, constant or zero-filled stretches, extreme values and smoothing (high lag-1 autocorrelation).

    Arguments: returns: number[]

  • check_fundamentalsCheck financial statement identities

    Check reported fundamentals against accounting identities: assets = liabilities + equity, current within total, gross profit = revenue - cost of revenue, cash-flow sections summing to the change in cash, and EPS x shares close to net income.

    Arguments: total_assets?: number, total_liabilities?: number, total_equity?: number, current_assets?: number, current_liabilities?: number, revenue?: number, cost_of_revenue?: number, gross_profit?: number, net_income?: number, eps?: number, shares?: number, operating_cash_flow?: number, investing_cash_flow?: number, financing_cash_flow?: number, change_in_cash?: number, tolerance?: number

  • check_corporate_actionsDetect corporate actions from raw and adjusted prices

    Detect splits and dividends by comparing raw and adjusted close series: each change in the adjustment factor, classified as a split (ratio) or a dividend (percent), with mismatches flagged.

    Arguments: close: number[], adjusted_close: number[], dates?: string[]

Machine-learning labels

7
  • cusum_filter_eventsSample events with a CUSUM filter

    Sample the periods worth labeling with the symmetric CUSUM filter on log prices: an event fires when the cumulative up or down move since the last event exceeds a threshold (fixed, or a multiple of recent volatility), so labels concentrate on meaningful moves instead of every bar.

    Arguments: prices: number[], threshold?: number, volatility_multiple?: number, vol_span?: integer

  • triple_barrier_labelsTriple-barrier labels

    Label events with the triple-barrier method: a profit-take and a stop-loss set as multiples of recent volatility, and a time limit; each label is which barrier was touched first (+1, -1, or the sign at the time limit), with the touch period so overlapping labels can be purged. With a side per period it produces meta-labels (1 = the bet paid).

    Arguments: prices: number[], events?: integer[], profit_take?: number, stop_loss?: number, max_holding?: integer, vol_span?: integer, min_return?: number, side?: integer[], vertical_label?: sign|zero, include_rows?: boolean

  • fixed_horizon_labelsFixed-horizon labels

    Label each period by its forward return over a fixed horizon: +1 above a threshold, -1 below minus the threshold, 0 between; the threshold can be fixed or scaled by recent volatility. Includes the class balance and the forward span each label covers.

    Arguments: prices: number[], horizon?: integer, threshold?: number, volatility_multiple?: number, vol_span?: integer, include_labels?: boolean

  • trend_scanning_labelsTrend-scanning labels

    Label each period by the strongest forward trend: regress prices on time over every forward window in a range, keep the window with the largest |t-statistic| of the slope, and label by its sign with the t-statistic as confidence (Lopez de Prado's trend scanning).

    Arguments: prices: number[], min_window?: integer, max_window?: integer, step?: integer, include_rows?: boolean

  • sample_weightsWeights for overlapping labels

    Weight labels whose spans overlap so a model does not over-count the same information: concurrency per period, each label's average uniqueness, return-attribution weights, and optional time decay (Lopez de Prado, chapter 4).

    Arguments: prices: number[], spans: any[][], decay?: number

  • purged_cv_splitsPurged, embargoed cross-validation

    Build k-fold cross-validation splits for labels that span time without leakage: training labels whose spans overlap a test fold are purged, and labels starting just after a test fold are embargoed. Reports what each fold removed, and optionally the indices.

    Arguments: spans: any[][], folds?: integer, embargo_periods?: integer, include_indices?: boolean

  • annotate_price_seriesAnnotate a price series

    Annotate every period of a price series and list the notable ones: robust-z outlier moves, stale (repeated) prices, gaps (jumps across a period), drawdown episodes with peak, trough and recovery, new all-time highs, and the causal volatility regime (calm, normal, turbulent). Gives per-period tags for joining onto your own data.

    Arguments: prices: number[], outlier_z?: number, stale_run?: integer, vol_lookback?: integer, min_drawdown?: number, include_tags?: boolean

Time value of money

15
  • net_present_valueNet present value

    Compute the NPV of periodic cash flows (first at time 0), with the profitability index, discounted payback and the IRR when one exists.

    Arguments: rate: number, cashflows: number[]

  • internal_rate_of_returnInternal rate of return

    Solve the IRR of periodic cash flows, warning when sign changes allow several IRRs, with the NPV profile at a few rates.

    Arguments: cashflows: number[], guess?: number

  • modified_irrModified internal rate of return

    Compute the MIRR: negative flows discounted at a finance rate, positive flows compounded at a reinvestment rate, one unambiguous return.

    Arguments: cashflows: number[], finance_rate: number, reinvest_rate: number

  • xnpv_xirrDated NPV and IRR (XNPV, XIRR)

    Compute NPV and IRR for cash flows on irregular dates (ACT/365 from the first date), as spreadsheet XNPV and XIRR do.

    Arguments: cashflows: number[], dates: string[], rate?: number

  • time_value_solverTime value of money solver

    Solve for any one of rate, number of periods, payment, present value or future value given the other four (loans, savings, annuities), payments at period end or start.

    Arguments: rate?: number, nper?: number, pmt?: number, pv?: number, fv?: number, when?: end|begin

  • amortization_scheduleLoan amortization schedule

    Build a level-payment loan schedule: payment, interest and principal per period, remaining balance, and total interest.

    Arguments: principal: number, annual_rate: number, years: number, payments_per_year?: integer, extra_payment?: number

  • rate_conversionInterest rate conversion

    Convert a nominal rate between compounding frequencies, to effective annual and continuous rates, and remove inflation (exact Fisher real rate).

    Arguments: rate: number, from: number|number|number|number|number|number|string, inflation?: number

  • growing_annuityGrowing annuity and perpetuity

    Value a growing annuity (present and future value) or a growing perpetuity whose first payment arrives in one period.

    Arguments: payment: number, rate: number, growth?: number, periods?: integer

  • payback_periodPayback and discounted payback

    Compute simple and discounted payback periods, interpolated within the period that recovers the investment.

    Arguments: cashflows: number[], rate?: number

  • equivalent_annual_annuityEquivalent annual annuity

    Convert a project's NPV into an equivalent level annual amount, to compare projects with different lives.

    Arguments: rate: number, cashflows: number[]

  • waccWeighted average cost of capital

    Compute WACC from market values and costs of equity, debt and preferred, with after-tax cost of debt; cost of equity can come from CAPM.

    Arguments: equity_value: number, debt_value: number, preferred_value?: number, cost_of_equity?: number, beta?: number, risk_free?: number, market_premium?: number, cost_of_debt: number, cost_of_preferred?: number, tax_rate: number

  • levered_betaUnlever and relever beta

    Unlever an observed equity beta to an asset beta and relever it at a target debt-to-equity ratio (Hamada), for comparable-company cost of equity.

    Arguments: beta: number, debt_to_equity: number, tax_rate: number, target_debt_to_equity?: number, debt_beta?: number

  • break_evenBreak-even and operating leverage

    Compute break-even units and revenue, contribution margin, margin of safety and degree of operating leverage from price, variable cost and fixed costs.

    Arguments: price: number, variable_cost: number, fixed_costs: number, units?: number, target_profit?: number

  • loan_true_costLoan APR with fees

    Find a loan's true annual cost when upfront fees reduce the cash received: the payment, the nominal APR and effective annual rate implied by the fees, and the total cost.

    Arguments: principal: number, annual_rate: number, years: number, upfront_fees: number, payments_per_year?: integer

  • retirement_projectionSavings and withdrawal projection

    Project a savings balance with yearly contributions growing with salary, then sustainable inflation-adjusted withdrawals; reports the balance at retirement, how long withdrawals last and the safe level spending.

    Arguments: balance: number, annual_contribution: number, contribution_growth?: number, years_to_retirement: integer, return_rate: number, inflation?: number, annual_withdrawal?: number, years_in_retirement?: integer

Company valuation

10
  • dcf_valuationDiscounted cash flow valuation

    Value a business from forecast free cash flows with a Gordon-growth or exit-multiple terminal value: enterprise and equity value, per-share value and a discount-rate by growth sensitivity grid.

    Arguments: free_cash_flows: number[], discount_rate: number, terminal_growth?: number, terminal_multiple?: number, terminal_metric?: number, mid_year?: boolean, net_debt?: number, shares?: number

  • reverse_dcfReverse DCF (implied growth)

    Solve the free-cash-flow growth rate the current share price implies over a forecast horizon, given a discount rate and terminal growth.

    Arguments: price: number, shares: number, net_debt?: number, base_free_cash_flow: number, discount_rate: number, terminal_growth: number, years?: integer

  • dividend_discount_modelDividend discount models

    Value a share with the Gordon growth, two-stage or H-model dividend discount model, or back out the required return the price implies (Gordon).

    Arguments: model: gordon|two_stage|h_model, dividend: number, required_return?: number, growth: number, high_growth?: number, years?: number, price?: number

  • residual_income_valuationResidual income valuation

    Value equity as book value plus discounted residual income (earnings above the cost of equity on opening book), with clean-surplus book values and a terminal value.

    Arguments: book_value: number, earnings: number[], dividends: number[], cost_of_equity: number, terminal_growth?: number, shares?: number

  • enterprise_value_multiplesEnterprise value bridge and multiples

    Build enterprise value from market cap, debt, preferred, minority interest and cash, then EV/EBITDA, EV/EBIT, EV/sales, P/E, P/B, earnings yield and FCF yield.

    Arguments: market_cap: number, total_debt?: number, cash?: number, preferred?: number, minority_interest?: number, ebitda?: number, ebit?: number, revenue?: number, net_income?: number, book_equity?: number, free_cash_flow?: number

  • altman_z_scoreAltman Z-score

    Compute the Altman Z-score bankruptcy predictor (public manufacturing, private-firm Z', or non-manufacturing Z'') with its five ratios and zone.

    Arguments: variant?: public_manufacturing|private|non_manufacturing, working_capital: number, retained_earnings: number, ebit: number, equity_value: number, total_liabilities: number, revenue: number, total_assets: number

  • piotroski_f_scorePiotroski F-score

    Score a company's financial strength 0-9 from two years of statements: profitability, leverage and liquidity, and operating efficiency signals, each shown.

    Arguments: current: {net_income,operating_cash_flow,total_assets,total_assets_begin,long_term_debt,current_assets,current_liabilities,shares_outstanding,revenue,gross_profit}, prior: {net_income,operating_cash_flow,total_assets,total_assets_begin,long_term_debt,current_assets,current_liabilities,shares_outstanding,revenue,gross_profit}

  • beneish_m_scoreBeneish M-score

    Compute the eight-variable Beneish M-score earnings-manipulation screen from two years of statements, with every index; above -1.78 flags likely manipulation.

    Arguments: current: {receivables,revenue,cost_of_goods_sold,current_assets,ppe,securities,total_assets,depreciation,sga,current_liabilities,long_term_debt,net_income,operating_cash_flow}, prior: {receivables,revenue,cost_of_goods_sold,current_assets,ppe,securities,total_assets,depreciation,sga,current_liabilities,long_term_debt,net_income,operating_cash_flow}

  • dupont_analysisDuPont ROE decomposition

    Decompose return on equity into margin, asset turnover and leverage (three-step), and into tax burden, interest burden, operating margin, turnover and leverage (five-step).

    Arguments: net_income: number, revenue: number, total_assets: number, equity: number, pretax_income?: number, ebit?: number

  • graham_valuationGraham number and growth formula

    Compute Benjamin Graham's number (sqrt 22.5 x EPS x book value per share) and his revised growth formula value, with margin of safety against a price.

    Arguments: eps: number, book_value_per_share?: number, growth_percent?: number, aaa_yield_percent?: number, price?: number

17 tools

Backtest validation

canli-validation-mcp, also its own server.

  • validate_deflated_sharpeValidate deflated Sharpe

    Deflated Sharpe ratio: the probability (0 to 1) that the selected strategy's Sharpe beats the best that luck gives across the variants tried, with the probabilistic Sharpe and that luck benchmark. Send the seven statistics or a return series. With every variant's returns use validate_overfitting; luck as a trial count, validate_luck_trials; a multiple-testing haircut, validate_haircut_sharpe. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: observed_sharpe_annualized?: number, observations?: integer, periods_per_year?: number, skew?: number, non_excess_kurtosis?: number, effective_independent_trials?: integer, cross_trial_sharpe_sd_annualized?: number, returns?: number[]

  • validate_overfittingValidate overfitting (CSCV)

    Probability of backtest overfitting (0 to 1) by CSCV: how often the in-sample best variant falls below the out-of-sample median. Needs every variant's returns (periods by variants); with summary statistics only, use validate_deflated_sharpe. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: matrix: number[][], n_splits?: integer, max_combinations?: integer, seed?: number

  • validate_reality_checkData-snooping tests (SPA, Reality Check, StepM)

    Data-snooping tests on every variant a search tried: Hansen's SPA p-value that the best beat the benchmark only by luck, White's Reality Check, and the variants Romano-Wolf StepM finds better. Send all variants tried, not only the winners. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: matrix?: number[][], matrix_file?: string, benchmark?: number[], block_length?: integer, reps?: integer, seed?: integer, alpha?: number

  • validate_paper_evidenceValidate paper evidence

    Checks paper-evidence.v0 structure and disclosures. With CANLI_LOCAL=1, record_file reads an export bundle and journal_file verifies signatures, source hashes and recomputed claims. Without a journal, source facts and signatures are unchecked. Local files are never uploaded. This verdict is about the series exactly as submitted. The service never saw the data source, its costs, survivorship, or any lookahead in how the series was built.

    Arguments: record?: object, record_file?: string, journal_file?: string, signature?: {scheme,public_key,signature}

  • validate_breadthValidate breadth ceiling

    Book Sharpe ceiling from adding sleeves of this quality and correlation, the Sharpe at a sleeve count, and the sleeves a target needs. For portfolio construction; it validates no single strategy. This verdict is about the series exactly as submitted. The service never saw the data source, its costs, survivorship, or any lookahead in how the series was built.

    Arguments: sleeve_sharpe: number, average_pairwise_correlation: number, sleeves?: integer, target?: number

  • validate_track_recordMinimum track record length

    Minimum track record length (observations and years) for an observed Sharpe to beat a benchmark at a confidence level; with observations, the record's probabilistic Sharpe so far. For live or paper records; to size a backtest for its trials, use validate_backtest_length. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: observed_sharpe_annualized: number, periods_per_year: number, skew: number, non_excess_kurtosis: number, benchmark_sharpe_annualized?: number, confidence?: number, observations?: integer

  • validate_backtest_lengthMinimum backtest length

    Minimum backtest length (years) before the best of N independent trials is not expected to reach a target Sharpe by luck; with backtest_years, the most trials those years allow. For planning a search; once it has a result, use validate_deflated_sharpe. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: effective_independent_trials?: integer, backtest_years?: number, target_sharpe_annualized?: number

  • validate_haircut_sharpeHaircut Sharpe ratio

    Haircut Sharpe for multiple testing (Harvey and Liu 2015): the Sharpe a single test would have needed, by Bonferroni and independent tests, and with the other tests' Sharpes, Holm and BHY. For the probability the Sharpe is real, use validate_deflated_sharpe. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: observed_sharpe_annualized: number, periods_per_year: number, observations: integer, tests?: integer, autocorrelation?: number, other_sharpe_ratios_annualized?: number[]

  • validate_luck_trialsLuck-equivalent trials

    How many skill-less strategies a search would need for its best to reach this Sharpe by luck (Monte Carlo), and with a trial count, the chance it did. States luck as the best of N random tries; for the probability the Sharpe is real, use validate_deflated_sharpe. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: observed_sharpe_annualized: number, periods_per_year: number, observations: integer, effective_independent_trials?: integer, skew?: number, autocorrelation?: number

  • audit_backtestAudit a backtest

    One-call audit of a strategy's returns. Headline: one test whose false-positive rate was measured on nine return shapes (White's Reality Check with variants, luck trials with Lo's correction without). Then deflated Sharpe, minimum track record and, with variants, overfitting and out-of-sample decay, each with its receipt, plus fix_next. Send every variant tried (variants_file) so trials are counted; point returns_file at a CSV instead of pasting. A deflated Sharpe or overfitting probability above or below any threshold is not admission to anything and is not a forecast.

    Arguments: returns?: number[], returns_file?: string, returns_column?: string|integer, periods_per_year: number, effective_independent_trials?: integer, cross_trial_sharpe_sd_annualized?: number, benchmark_sharpe_annualized?: number, confidence?: number, variants?: number[][], variants_file?: string, n_splits?: integer

  • verify_receiptVerify a receipt

    Verify a receipt offline: its Ed25519 signature against the bundled canlicapital.com key, its output hash and its id. Send an id to fetch it first, or the receipt itself. The receipt is content-hashed, reproducible from the open-source core it names, and signed with Ed25519 by a key published at https://canlicapital.com/.well-known/canli-receipt-keys.json.

    Arguments: id?: string, receipt?: object, include_receipt?: boolean

  • backtest_strategyBacktest a rule over a parameter grid, validated

    Backtest a rule on your prices over a whole parameter grid, then validate the best with the count of variants actually run: deflated Sharpe, overfitting probability, minimum track record, vs buy and hold, after costs. A backtest, deflated or not, is not a forecast and not advice.

    Arguments: family: buy_and_hold|sma_cross|momentum|mean_reversion|breakout, grid?: object, prices?: number[], prices_file?: string, prices_column?: string|integer, dates?: string[], periods_per_year?: number, cost_bps?: number, allow_short?: boolean

  • summarize_seriesSummarize a price or return series

    A long price or return series in about 100 words plus fields: growth, risk, dated drawdowns, trend, volatility regime, tails, jumps, stale data. Use instead of reading raw bars. Nothing here is a forecast or advice.

    Arguments: prices?: number[], returns?: number[], series_file?: string, series_column?: string|integer, series_kind?: prices|returns, dates?: string[], periods_per_year?: number, benchmark_returns?: number[], name?: string

  • strategy_stress_testStress-test a strategy's returns

    Stress a strategy's returns: bootstrap histories (how often the drawdown limit breaks or Sharpe turns negative) and named crash, volatility, repeat and stuck-position scenarios, with a fragility share. Frequencies over resampled histories are not forecasts of the future.

    Arguments: returns?: number[], returns_file?: string, returns_column?: string|integer, periods_per_year?: number, paths?: integer, block?: number, seed?: integer, drawdown_limit?: number, crash?: number, volatility_multiplier?: number, outage_periods?: integer

  • check_feasibilityCheck a plan against broker limits and impact

    Check a trading plan before it trades: broker order-rate and minimum-order limits, 2026 US day-trading rules, square-root market impact with crowding, and the capital where costs eat the return. Checks the plan as described against published broker limits and a market-impact model; it never contacts a broker or sees an account.

    Arguments: broker?: alpaca|ibkr|other, asset_class?: us_equity|crypto|futures|fx|options, account?: cash|margin, capital_usd: number, orders_per_rebalance: integer, rebalances_per_year: number, turnover_per_year: number, adv_usd: number, daily_volatility: number, copies?: integer, expected_gross_return?: number, spread_and_fees_bps?: number, impact_coefficient?: number, minutes_per_rebalance?: number, orders_per_minute_limit?: number

  • check_leakageCheck a signal for lookahead

    Does a signal look ahead? plan gives cuts; rerun your code on the first cut rows for each, then compare. Rows that changed used later rows; the result names the pattern and horizon. No code is sent. A pass covers only these cuts: the columns are the caller's, and survivorship, vendor revisions or a leak no cut reaches leave no trace.

    Arguments: action: plan|compare, observations?: integer, prefixes?: integer, seed?: integer, cuts?: integer[], columns?: object, columns_file?: string, timestamps?: string[], tolerance?: number

  • placebo_testTest a research pipeline on placebo data

    Does your pipeline find edges in noise? plan writes placebo files (your data's returns in random orders, so nothing is predictable); run the whole pipeline on real.csv and on each, then compare for a p-value that counts every choice it makes. Beating the placebos shows the pipeline finds more in the real order of the returns than in random orders of the same returns; it does not show the edge survives costs, capacity or the future.

    Arguments: action: plan|compare, data_file?: string, columns?: object, kind?: prices|returns, placebos?: integer, method?: permute|block_permute|stationary_bootstrap, seed?: integer, real?: number, placebo_results?: number[], lower_is_better?: boolean

86 tools

Markets

canli-markets-mcp, also its own server.

Filings and what they say

10
  • european_filingsEuropean filings (ESEF)

    A European company's annual financial report as it filed it in the European Single Electronic Format (ESEF): revenue, operating and net profit, EPS, assets, equity, cash, cash flows and dividends as the company tagged them (IFRS concepts, its currency, full scale), with the comparatives, the report's viewer link and the other years on file. Issuers on EU and EEA regulated markets, found by name or LEI; words find any other tagged figure.

    Arguments: company: string, year?: integer, words?: string

  • filing_tablesTables in filings

    The table in a filing that holds a figure, found by words ("paid members", "revenue by region", "guidance"): XBRL statement and detail reports and the tables in the document itself (MD&A figures such as members, stores or ARPU), or an 8-K press release's tables. With filings above one, the same words in each earlier filing, to follow a figure over the years. Without words, lists the tables.

    Arguments: company: string, find?: string, form?: string, filings?: integer, accession?: string, filed_before?: string, document?: string, max_tables?: integer

  • list_filingsList filings

    A company's SEC filings, newest first, filtered by form type (10-K, 10-Q, 8-K, DEF 14A, S-1, 4, 13F-HR...) and dates, with links. Use read_filing to read one.

    Arguments: company: string, forms?: string[], form?: string, since?: string, until?: string, limit?: integer

  • read_filingRead a filing

    The text of an SEC filing: the latest of a form, or one by accession. For a 10-K or 10-Q, section returns one item ("risk factors", "md&a", "business", "market risk", "legal proceedings", or a number such as "1A"); without it the result lists the items and their lengths. document reads an exhibit, such as an 8-K's press release ("EX-99.1"). find returns only the passages with given words ("employees", "buyback"), the fastest way to a fact in a long filing; otherwise long text pages with offset.

    Arguments: company?: string, accession?: string, form?: string, filed_before?: string, section?: string, document?: string, find?: string, offset?: integer, max_chars?: integer

  • search_filingsSearch filings

    Full-text search across all SEC filings since 2001 (EDGAR full-text search): which companies mention a phrase, filtered by form, filer and dates. Quote phrases.

    Arguments: query: string, forms?: string[], company?: string, since?: string, until?: string, limit?: integer

  • company_eventsCompany events (8-K)

    Company news from the source: the events companies must report on Form 8-K (earnings, deals, executive changes, restatements, auditor changes, bankruptcies, cyber incidents, layoffs, delisting notices), for one company or, by event, across the whole market, each with the headline of the press release it attached and the opening of what the filing says.

    Arguments: company?: string, event?: string, since?: string, until?: string, limit?: integer, excerpts?: boolean

  • latest_filingsLatest filings (EDGAR feed)

    What has just been filed with the SEC, across every company: EDGAR's latest-filings feed, newest first by acceptance time, filtered by form (8-K, 10-K, 4, SC 13D, S-1...), 8-K event (earnings, executive change, restatement, bankruptcy), words in the filer's name and time. For watching what comes in today and over the last few business days; list_filings and company_events reach further back.

    Arguments: forms?: string[], event?: string, company?: string, since?: string, limit?: integer

  • filing_diffWhat changed in a filing

    What changed in a company's 10-K (or 10-Q) against the one before, section by section (risk factors by default, MD&A, business, legal proceedings): new and dropped paragraphs, the sentences changed in the rest, and the words whose use rose or fell most.

    Arguments: company: string, section?: string, form?: 10-K|10-Q, accession?: string, against?: string, threshold?: number, max_items?: integer

  • comment_lettersSEC comment letters

    What the SEC's staff questioned in a company's filings and how it answered: comment letters (UPLOAD) and replies (CORRESP) grouped into reviews, with the topics of the newest (non-GAAP, revenue recognition, segments...) and excerpts.

    Arguments: company: string, years?: integer, read?: integer

  • filing_driftLanguage drift across filings

    How a 10-K section's language drifts over several years: each year's change from the year before (the Lazy Prices measure), hedging and adverse words, readability, and how much it says about a theme you name and how that wording moves, with flags for the years and themes that moved most.

    Arguments: company: string, section?: string, years?: integer, theme?: string

Results and valuation

16
  • dividend_historyDividend history

    A security's dividends and splits: each payment by ex-date, totals by year, the trailing 12-month yield, five-year growth and the streak of rising annual totals. Works for foreign listings.

    Arguments: symbol: string, years?: integer

  • verify_claimsVerify claims against filings

    Check a draft answer's figures against the company's own filings before using them: revenue, net income, EPS, operating income, margins, growth, cash flow, assets, debt and more, for a fiscal year or quarter as the company labels it. US and foreign filers (20-F, IFRS), in their own currency. Each claim comes back confirmed, contradicted (with the filed figure and what the claimed one matches instead: another year, a quarter, a unit slip), not reported or not checkable.

    Arguments: company: string, claims?: {measure,period,value,unit,growth,basis}[], text?: string

  • financial_statementsFinancial statements as filed

    A company's financial statements exactly as filed: income statement, balance sheet, cash flow and equity statement from its 10-K (or 10-Q), with its own line labels, each line's XBRL concept and the values as the filing shows them (units say the scale). Joins several filings by period; a line a later filing restated, or that a stock split changed, is shown beside its first-reported figure, never mixed in.

    Arguments: company: string, statement?: core|income|balance_sheet|cash_flow|..., period?: annual|quarterly, filings?: integer, fiscal_year?: integer, filed_before?: string, accession?: string

  • earnings_releaseEarnings release and guidance

    A quarter's results press release (8-K Item 2.02): the headline, the results it states (each with the part of the business it belongs to and what a change is measured against), its guidance parsed into ranges (low, high, midpoint, unit, measure, basis, period, and the sentence or table row), and the previous release's guidance for this quarter set against the company's results: above, within or below the range, in basis points for rates.

    Arguments: company: string, accession?: string, filed_before?: string, compare?: boolean, max_lines?: integer

  • screen_companiesScreen companies

    Screen every US-listed company (thousands, from SEC XBRL frames) on fundamentals: revenue, growth, margins, ROE, ROA, free cash flow, R&D intensity, leverage and more, for a calendar year or each company's fiscal year ending in a date window, with filters, ranking and optional valuation (price, market cap, P/E, P/S, FCF yield). Implausible figures (tagging slips) are held out and listed apart.

    Arguments: period?: string, fiscal_year_end?: any[], filters?: {metric,op,value}[], sort_by?: string, order?: desc|asc, columns?: string[], exchanges?: (NYSE|Nasdaq|CBOE|OTC|...)[], limit?: integer, valuation?: boolean, include_suspect?: boolean

  • company_reportCompany report

    One company in one call: profile, five fiscal years of financials (revenue, growth, margins, net income, EPS, cash flow, ROE, leverage), price and risk over a year (return, volatility, drawdown, beta), valuation (market cap, P/E, P/S, FCF yield), insider buying and selling, and recent filings, each from its source.

    Arguments: company: string, years?: integer

  • company_profileCompany profile

    A company's or fund's SEC profile by ticker, CIK or name: tickers, exchange, industry (SIC), fiscal year end, state, address, former names, and its latest 10-K, 10-Q, 8-K and 13F.

    Arguments: company: string

  • segment_revenueRevenue by segment

    Where a company's revenue comes from, read from the XBRL of its latest 10-K (or 10-Q): revenue and operating income by business segment, revenue by product or service and by region, for up to three years, with the company's own labels and each breakdown checked against total revenue.

    Arguments: company: string, form?: 10-K|10-Q

  • executive_payExecutive pay vs performance

    What a company's executives are paid against how it did, from the pay-versus-performance table in its proxy: the CEO's reported pay and the pay actually earned, the other executives' averages, shareholder return against peers, net income and the company's chosen measure, five years; or every company's CEO pay ranked, with mis-scaled filings held out.

    Arguments: company?: string, year?: integer, rank_by?: ceo_reported_pay|ceo_pay_actually_paid|tsr, limit?: integer

  • compsComparable companies

    A comparable-companies table: the company beside its NYSE- and Nasdaq-listed peers in the same SEC industry code, the nearest in revenue, on revenue, growth, margins, ROE, R&D intensity and FCF margin (or measures you pick), with the peers' median and the company's rank on each.

    Arguments: company: string, metrics?: string[], companies?: string[], peers?: integer, period?: string, fiscal_year_end?: any[]

  • debt_profileDebt profile

    A company's debt from its annual reports' XBRL: total and net debt, the maturity ladder from the debt note (next 12 months to after five years), lease payments, interest expense, the implied interest rate, interest coverage and debt to EBITDA, with five years of debt and cash.

    Arguments: company: string, years?: integer

  • forensic_scoresForensic accounting screens

    Three accounting screens in one call from the company's own annual XBRL for its last two years: Beneish's M-score (earnings manipulation), Piotroski's F-score (financial strength) and Altman's Z-score (distress), every input with its tag.

    Arguments: company: string

  • shareholder_returnsDividends and buybacks

    What a company has paid its shareholders, year by year from its annual XBRL: dividends per share (split-adjusted record: years raised in a row, 5- and 10-year growth) and in total, buybacks and shares issued for cash, the diluted share count and its change, the payout ratio and the share of free cash flow paid out, and at the last close the dividend yield and shareholder yield.

    Arguments: company: string, years?: integer, price?: boolean

  • company_reverse_dcfReverse DCF (implied growth)

    The free-cash-flow growth a share price implies: solves a discounted cash flow model for the growth that reaches the market's enterprise value, from the company's annual XBRL and the last close, with a sensitivity table and the company's own history beside it.

    Arguments: company: string, ticker?: string, discount_rate?: number, terminal_growth?: number, years?: integer, base?: latest|average_3y

  • bank_financialsBank financials (FDIC call reports)

    A US bank's condition quarter by quarter from its call reports (FDIC, no key): assets, deposits and the share uninsured, loans and the share noncurrent, equity, earnings, ROA, ROE, net interest margin and capital ratios. With no bank, failures since 1934 and their cost, by year or state.

    Arguments: company?: string, cert?: integer, quarters?: integer, failures?: integer, failures_year?: integer, failures_state?: string

  • earnings_calendarEarnings calendar

    Earnings dates from the companies' own 8-Ks (Item 2.02, results of operations). For a company: its recent results releases with the quarter each covered and whether it came before the open or after the close (EDGAR's acceptance time), and the next release estimated from the same quarter a year earlier, with a window. Across the market: who is due to report in a window, from when they reported in the same weeks last year, marked once they have. Estimates, not announcements.

    Arguments: company?: string, quarters?: integer, since?: string, until?: string, limit?: integer

Ownership and insiders

8
  • insider_tradesInsider trades

    Insider transactions at a company from its Form 4 filings: who (officers, directors, 10% owners), what (open-market buys and sales, option exercises, tax withholding, gifts), shares, price, value, holdings after, and 10b5-1 plan flags, with a buy/sell summary. Default: the last 90 days.

    Arguments: company: string, since?: string, until?: string, codes?: string[], max_filings?: integer

  • fund_holdingsFund holdings (13F)

    A fund manager's 13F holdings for a quarter (latest by default): positions by value with portfolio weights, the total checked against the filing's cover page, and what changed since the previous quarter (new, exited, added, reduced).

    Arguments: manager: string, period?: string, top?: integer, compare?: boolean

  • private_offeringsPrivate offerings (Form D)

    Private markets from Form D, filed when startups and funds sell securities without registering: amount offered and sold, number of investors, minimum investment, exemption (Rule 506(b) or 506(c)), industry, fund type and the people behind it, for one issuer or across the market (newest first, filtered by industry or amount sold).

    Arguments: company?: string, industry?: string, min_sold?: number, since?: string, limit?: integer

  • ownership_breadthBreadth of institutional ownership (13F)

    How many institutions hold a stock, quarter by quarter: 13F filers whose holdings tables list its CUSIP (EDGAR full-text search), with the change and a sample of holders. A fall in breadth predicted lower returns (Chen, Hong and Stein 2002).

    Arguments: company?: string, cusip?: string, quarters?: integer, holders?: integer

  • planned_insider_salesPlanned insider sales (Form 144)

    Insiders' planned sales from Form 144, filed before they sell: seller, role, shares, market value, share of the company, approximate sale date, how the shares were acquired and any 10b5-1 plan date, with totals by seller.

    Arguments: company: string, days?: integer, limit?: integer

  • ipo_pipelineIPO pipeline (S-1, F-1, 424B4)

    The IPO pipeline from EDGAR: companies that filed or amended a registration (S-1, F-1) in a window, labelled IPO candidate, SPAC, fund or already listed, and offerings priced (424B4) with price, shares and proceeds from the prospectus cover.

    Arguments: days?: integer, kind?: ipo|spac|fund|all, priced?: integer

  • large_holdersLarge holders (13D/13G)

    Who owns more than 5 percent of a company, from Schedules 13D and 13G: each holder's latest stake (shares, percent of class, voting power), whether it is passive (13G) or may seek to influence control (13D, with its stated purpose); or, with no company, the newest 13D stakes across the whole market.

    Arguments: company?: string, schedule?: 13D|13G|both, since?: string, limit?: integer

  • investment_advisersInvestment advisers (Form ADV)

    Investment advisers from the SEC's Form ADV database (IAPD) by name or CRD: matching firms with SEC file numbers, status, whether they report disclosure events, offices and branch counts, then the best match in full: registration and since when, other names and relying advisers, its latest ADV date, and links to its Form ADV and brochures.

    Arguments: query: string, limit?: integer

Prices and trading

14
  • prediction_marketsPrediction markets

    What traders on Polymarket and Kalshi are paying for an outcome, found by words (a Fed decision, a recession, an election, a price level): each market's probability (the middle of bid and ask, else the last trade), bid, ask, volume and closing date, with the event's resolution rules.

    Arguments: query: string, venue?: both|polymarket|kalshi, limit?: integer

  • event_studyEvent study

    How a stock's price reacted to events: earnings releases (8-K item 2.02), insider purchases or sales (Form 4), any 8-K, or given dates. Abnormal returns against a market model, cumulative abnormal return per event and on average, with a t test across events. For filings use event_type (with last for the most recent few), not filing dates: it starts day 0 at the first session after the SEC accepted the filing.

    Arguments: symbol: string, events?: string[], event_type?: earnings|insider_buys|insider_sales|8k, since?: string, last?: integer, window?: any[], estimation_days?: integer, benchmark?: string, model?: market|market_adjusted|mean_adjusted

  • price_historyPrice history

    Price bars (open, high, low, close, volume), daily to hourly, for US stocks and ETFs, stocks listed abroad (SAP.DE, 7203.T), currency pairs (EUR/USD), futures (crude oil, gold), indices and yields (S&P 500, VIX, 10 year yield) and crypto (bitcoin), by symbol or plain name. Stocks adjust for splits and dividends by default, with dividends, splits and the total return; returns: true adds daily returns. No key needed; uses the user's Alpaca or Tiingo key for US stocks when set.

    Arguments: symbol: string, start?: string, end?: string, interval?: 1Day|1Week|1Month|1Hour, adjusted?: boolean, returns?: boolean

  • options_chainOptions chain (Cboe)

    An option chain from Cboe's delayed data for a stock, ETF or index (AAPL, SPY, SPX, VIX): bids, asks, implied volatility, greeks, open interest and volume by strike for one expiration, every expiration with its open interest, put/call ratios, max pain and the move the at-the-money straddle prices in.

    Arguments: symbol: string, expiration?: string, window?: number, type?: calls|puts|both, min_open_interest?: integer

  • volatility_surfaceVolatility surface (Cboe)

    The implied volatility surface from Cboe's delayed option data: at-the-money IV by expiration (term structure), 25-delta put and call IV with the risk reversal and butterfly (skew), and IV at fixed moneyness from 80 to 120 percent of the price (smile).

    Arguments: symbol: string, expirations?: integer

  • futures_curveFutures curve (Cboe)

    A Cboe futures curve from its daily settlements: VIX futures by expiration with the VIX index, contango or backwardation and the front month's premium; also mini VIX, variance, bitcoin and iBoxx bond index futures.

    Arguments: product?: string

  • index_constituentsIndex constituents

    The members of a stock index (S&P 500, Nasdaq 100, Russell 2000, S&P 400, MSCI EAFE) with their weights, read from the N-PORT of an ETF that tracks it, with the report date, the number of members and how concentrated the top ten are.

    Arguments: index: string, limit?: integer

  • short_interestShort interest (FINRA)

    Short interest in US stocks from FINRA, twice a month: shares short, the change, average daily volume and days to cover over several reports, and the share of shares outstanding from the company's latest SEC cover page; or, with no stock, the market ranked by days to cover, change or size.

    Arguments: symbol?: string, periods?: integer, rank_by?: days_to_cover|change_pct|short_position, min_volume?: number, limit?: integer

  • off_exchange_volumeDark pool and OTC volume (FINRA)

    How much of a US stock trades away from the exchanges, from FINRA's OTC transparency data: weekly shares and trades in dark pools (ATSs) and with other off-exchange dealers, and the largest dark pools and dealers in the latest week.

    Arguments: symbol: string, weeks?: integer

  • fails_to_deliverFails to deliver (SEC)

    Shares that failed to settle, from the SEC's fails-to-deliver data (NSCC): a stock's outstanding fail balance on each settlement date over the latest half-month files, with prices and dollar values, or the securities with the largest fails across the market.

    Arguments: symbol?: string, files?: integer, limit?: integer

  • futures_positioningFutures positioning (CFTC COT)

    Who holds what in a futures market, from the CFTC's weekly Commitments of Traders: long, short and net positions of producers, swap dealers, managed money and others (or dealers, asset managers and leveraged funds for financial futures), with weekly changes and where the speculators sit in their range, by market name (gold, crude oil, 10 year note, euro, bitcoin).

    Arguments: market: string, weeks?: integer

  • explain_moveExplain a stock move

    Why a stock moved on a day, in one call: its return against the market and how rare it was for this stock (a market model fitted on the year before, with a z-score), the company's SEC filings around the day (8-K items named), and the press's headlines from those days.

    Arguments: symbol: string, date: string, benchmark?: string, window_days?: integer, news?: boolean

  • portfolio_xrayPortfolio X-ray (look-through)

    A portfolio seen through its funds: each ETF or mutual fund opened into the positions of its latest SEC N-PORT and added to the stocks held directly, giving the real exposure to each company, the overlap between funds and the effective number of positions.

    Arguments: holdings: {symbol,weight}[], top?: integer

  • market_overviewMarket overview

    The market at a glance, no key: the S&P 500, Nasdaq, Dow, Russell 2000 and VIX, the eleven S&P sectors (SPDR funds) ranked by the month, Treasury yields from 13 weeks to 30 years, the dollar and major currencies, oil, gas, gold, silver and copper, bitcoin and ether, and the main markets in Europe and Asia, each with its last close and its change over a day, a week, a month, three months, the year to date and a year.

    Arguments: groups?: (us|sectors|rates|currencies|...)[]

Funds

1
  • fund_portfolioFund or ETF portfolio (N-PORT)

    What a US mutual fund or ETF holds, from its own SEC Form N-PORT (VOO, IVV, QQQ, AGG, FXAIX): every position with value and weight, exposure by asset type, issuer, country and currency, a bond fund's coupon and maturity profile, its monthly returns, the money that came in and went out each month, and what changed since the previous quarter.

    Arguments: fund: string, period?: string, top?: integer, compare?: boolean

Rates and the economy

11
  • world_yieldsWorld government yields

    Government bond yields side by side: U.S. Treasury, euro area (ECB, AAA), UK (Bank of England), Japan (Ministry of Finance) and Canada (Bank of Canada), by maturity, with the date and basis of each curve, 10Y-2Y slopes and 10-year spreads to the U.S.

    Arguments: countries?: (us|euro|uk|japan|canada)[]

  • credit_cycleCredit cycle (BIS)

    The BIS credit cycle by country: private credit as a share of GDP, its long-run trend and the credit-to-GDP gap, an early-warning measure regulators use for banking stress. Up to 40 quarters.

    Arguments: countries: string[], quarters?: integer

  • reference_ratesReference and policy rates

    Money-market and policy rates and the ECB's euro exchange reference rates (fx:GBP) from the central banks themselves: SOFR, TGCR, BGCR, EFFR and OBFR from the New York Fed (with percentiles and volume), the euro short-term rate and the ECB's policy rates, SONIA and Bank Rate from the Bank of England, and about forty central banks' policy rates as the BIS collects them (policy:JP, policy:Brazil). Dates and rates, oldest first.

    Arguments: rate: string, start?: string, end?: string

  • treasury_yieldsTreasury yields

    US Treasury daily yields from the Treasury itself: the par yield curve (1 month to 30 years), real (TIPS) yields or bill rates, for the latest day, a date, or a date range. In percent.

    Arguments: curve?: nominal|real|bills, date?: string, start?: string, end?: string

  • economic_seriesEconomic series (FRED)

    Any FRED economic series (inflation, unemployment, GDP, payrolls, rates, credit spreads, oil, FX, money supply, recession indicators) by id or plain words, as dates and values, optionally as changes or year-over-year rates. Feed values straight into analysis tools.

    Arguments: series: string, start?: string, end?: string, transform?: level|change|pct_change|yoy, last?: integer

  • fomcFed rate decisions (FOMC)

    The Federal Reserve's rate decisions from its own record: each FOMC meeting of a year (held and scheduled), the action, change and target range, the vote with dissenters and their reasons, links to statements and minutes, the latest statement, and the median projections (dot plot) for GDP, unemployment, inflation and the federal funds rate.

    Arguments: year?: integer

  • economic_calendarEconomic calendar

    The US economic calendar from the agencies' own schedules: when BLS (jobs, CPI, PPI, JOLTS), BEA (GDP, personal income and PCE, trade), the Census Bureau (retail sales, housing starts, durable goods) and the Fed (FOMC decisions) release, with times in US Eastern and the market-moving releases flagged.

    Arguments: since?: string, until?: string, key_only?: boolean

  • world_economyWorld economy (World Bank)

    Any country's or region's economy from the World Bank's World Development Indicators (200+ countries, the euro area, the world, income groups): GDP and growth, inflation, unemployment, government debt and deficits, the current account, trade, reserves, interest rates, population and more, by plain words or indicator code, as a year-by-country table with each country's latest value.

    Arguments: indicator: string, countries: string[], start?: integer, end?: integer

  • economic_outlookEconomic outlook (OECD projections)

    The OECD's projections for the next two years from its Economic Outlook, for 50+ economies, the euro area, the OECD and the world: GDP growth, inflation (harmonised for the euro area), core inflation, unemployment, budget balance, government debt, current account and short- and long-term interest rates, beside its estimates for the two years before.

    Arguments: countries: string[], measures?: string[]

  • treasury_auctionsTreasury auctions

    US Treasury auction results, or the auctions announced next, from the Treasury itself: bills, notes, bonds, TIPS and FRNs by term ("10-year", "13-week bill"), with the rate each cleared at, coupon, bid-to-cover, size and the shares taken by indirect bidders (foreign and other), direct bidders and primary dealers, plus averages to compare the latest auction with recent ones.

    Arguments: security?: string, upcoming?: boolean, since?: string, until?: string, limit?: integer

  • federal_debtUS federal debt

    The US federal debt each business day from the Treasury's Debt to the Penny (total, held by the public, intragovernmental) over any window since 1993, its change over the window, and the average interest rate the Treasury pays on each type of security.

    Arguments: start?: string, end?: string, frequency?: daily|monthly

News and public records

9
  • enforcement_actionsSEC enforcement actions

    The SEC's latest enforcement: litigation releases and administrative proceedings, with who was named, the number and the document, across the market or filtered to a company or person (every word of the name must match). The feeds hold the latest actions only, so an empty answer is limited to what they reach.

    Arguments: company?: string, limit?: integer

  • consumer_complaintsConsumer complaints (CFPB)

    Complaints consumers sent the CFPB about a bank, lender, card issuer or credit bureau: totals, the last 12 months, top products and issues, and how often the company answered in time. Complaints are unverified and not adjusted for size.

    Arguments: company: string

  • product_recallsProduct recalls (FDA, NHTSA)

    Recalls: a firm's FDA recalls of drugs, devices and food with class, reason and status, and a vehicle's NHTSA safety recalls by make, model and year.

    Arguments: company?: string, vehicle?: {make,model,year}, limit?: integer

  • sanctions_checkSanctions list (OFAC SDN)

    Search the U.S. Treasury's Specially Designated Nationals list and its aliases for a person, company, bank or vessel, by whole words. Not a compliance screening: no match is not clearance, and a match needs checking against the entry.

    Arguments: name: string, limit?: integer

  • federal_rulesFederal Register rules

    Federal Register documents: final and proposed rules, notices and presidential documents by words and agency (SEC, CFTC, Fed, Treasury, CFPB, FDA and more), with comment deadlines, effective dates and abstracts. Can list only rules still open for comment.

    Arguments: query?: string, agency?: string, type?: rule|proposed_rule|notice|presidential, since?: string, open_for_comment?: boolean, limit?: integer

  • mentions_trendMentions over time

    How often a word or phrase appears in SEC filings over time (by month, quarter or year), across all filers or one company, from EDGAR full-text search: for themes such as "tariffs", "agentic AI" or "going concern".

    Arguments: query: string, forms?: string[], start?: string, end?: string, by?: month|quarter|year, company?: string

  • newsNews and tone (GDELT)

    News about a company or a topic from the world's press (the GDELT Project's open index, no key): articles newest first with outlet and country, and the daily average tone of the coverage.

    Arguments: query?: string, company?: string, days?: integer, start?: string, end?: string, limit?: integer, language?: string, tone?: boolean

  • federal_contractsFederal contracts (USAspending)

    What the US government obligated to a company in a fiscal year, no key: the total, by agency and industry code, its recipient entities, and its largest contracts with links, from USAspending.gov.

    Arguments: company?: string, recipients?: string[], fiscal_year?: integer, limit?: integer

  • drug_pipelineDrug pipeline and FDA approvals

    A drug company's pipeline, no key: active clinical trials by phase, the readouts (primary completions) due in the coming months, late-stage trials, and its FDA approvals, from ClinicalTrials.gov and Drugs@FDA.

    Arguments: company?: string, sponsor?: string, months?: integer

Who is who

2
  • security_identifiersSecurity identifiers (OpenFIGI)

    Map a ticker, ISIN, CUSIP, SEDOL or FIGI to one security through OpenFIGI: its name, FIGIs, listings, exchange and type. Check digits are tested first, so a mistyped ISIN or CUSIP is refused.

    Arguments: id: string, exchange?: string, limit?: integer

Crypto and compute

3
  • crypto_fundamentalsCrypto fundamentals (DefiLlama)

    A DeFi protocol's total value locked (now, by chain, and its history), the fees users pay it and the revenue it keeps (24 hours to all time); a chain's total value locked; or a stablecoin's supply in circulation and its change, by chain. From DefiLlama's open data.

    Arguments: protocol?: string, chain?: string, stablecoin?: string, days?: integer

  • funding_ratesCrypto funding rates (OKX)

    Crypto perpetual funding on OKX's USDT perpetuals, no key: each coin's latest eight-hour rate, the window's mean and its annualized carry (short the perpetual against long spot), the last week's, and the share of positive periods.

    Arguments: coins?: string[], days?: integer, series?: boolean

  • compute_pricesGPU compute prices (Cirrun index)

    Compute as a market, no key: the on-demand hourly price of each data-centre GPU (B200, H200, H100, A100, L40S...) across the clouds and GPU marketplaces, the cheapest, median and dearest offer with who offers it, every provider's offer for one model, recent list-price changes, and the Cirrun GPU Index (a daily chained index of those prices). Each price is the provider's own list price with the date it was confirmed.

    Arguments: gpu?: string, provider?: string, changes?: integer

Other

12
  • technical_indicatorsTechnical indicators

    The common technical indicators for a symbol in one call, from its daily prices: moving averages (SMA and EMA), RSI, MACD, Bollinger Bands and ATR, with where the close sits against its 50- and 200-day averages. Standard definitions; describes past prices, not a forecast.

    Arguments: symbol: string, as_of?: string

  • stock_snapshotAnalyst targets, valuation and short interest

    What a quote page shows and no primary source publishes, from Yahoo Finance: analysts' mean, median, high and low price targets, how many analysts, the recommendation and ratings, EPS and revenue estimates by quarter and year, market cap, trailing and forward P/E and other ratios, 52-week range, dividend rate, short interest, institutional and insider percentages, next earnings date. Vendor aggregates, labeled as such; for reported figures use the filings.

    Arguments: symbol: string

  • exposure_mapWho depends on this company

    Who depends on a company, from what others say in their annual reports: every filer that names it, with the passage, and whether it reads as a supplier, customer or competitor. For supply chains no fund report shows. Read by rules, so check the passage.

    Arguments: name: string, also?: string[], forms?: string[], since?: string, limit?: integer

  • guidance_recordManagement's record against its own guidance

    A management team's record against its own word: each quarter it gave guidance in its press release, what it said and what then happened, how often results came in above, within and below its own range, and which quarters fell short.

    Arguments: company: string, quarters?: integer, measure?: string, filed_before?: string

  • what_happened_nextWhat happened next, every past time

    Every past time a market or stock fell, rose or sat this far below its high: each case, what followed a month, a quarter and a year later, the worst and best, and how that compares with an ordinary day. A record, not a forecast or advice.

    Arguments: symbol?: string, condition: fell|rose|below_high|new_high, percent?: number, days?: integer, horizons?: integer[], since?: string, gap_days?: integer

  • filing_memorySearch all of a company's annual reports

    Everything one company has said about a subject across every annual report it has on EDGAR, back to the 1990s where they exist: the best passages with links, how often it came up each year, and optionally how that moved with a margin, tested against chance. Reads the reports on this machine; no key. Supply the company's likely words in also and all_of, since a company rarely uses yours.

    Arguments: company: string, query: string, also?: string[], all_of?: string[][], years?: integer, form?: 10-K|20-F|40-F, section?: string, limit?: integer, per_year?: integer, filed_before?: string, correlate_with?: gross_margin|operating_margin|net_margin, semantic?: boolean

  • filing_sentimentFiling tone (local FinBERT)

    The tone of a filing or any text, sentence by sentence, from FinBERT run on this machine: an 8-K's press release by default, or a 10-K section. Needs the optional local models (canli-mcp models install). Tone, not truth, and no evidence it predicts a price; the model is licensed for non-commercial use.

    Arguments: text?: string, company?: string, accession?: string, form?: string, document?: string, section?: string, max_sentences?: integer

  • shipping_activityShipping activity (IMF PortWatch)

    Ships moving through the world's straits and canals (Suez, Panama, Malacca, Hormuz and others) and ports, from the IMF's PortWatch, which estimates them from satellite tracking of ships. All chokepoints against a year ago, one chokepoint by week, or one port. No key.

    Arguments: chokepoint?: string, port?: string, start?: string, end?: string

  • page_attentionPublic attention (Wikipedia)

    Daily Wikipedia page views for a company or subject: a plain measure of public attention, with how the last week compares with normal. No key.

    Arguments: topic: string, days?: integer

  • latest_priceLatest price

    The latest price of a stock, ETF, index, currency or crypto pair, with the previous close and the time of the price. No key; can run late, by 15 minutes or more on some markets.

    Arguments: symbol: string

  • figure_tracefigure_trace

    How a reported figure is built, from the filing itself: the lines the company's own XBRL calculation adds up to it, each line's value, every sum recomputed and checked, what the figure feeds into, and how the filing splits it by segment, product or region. It shows the filing agrees with itself, not that the figures are right.

    Arguments: company: string, measure: string, form?: 10-K|10-Q, year?: integer

  • token_checktoken_check

    What an ERC-20 token's contract can do and how much of it exists, read from the chain: mint, pause, blacklist and upgrade powers, owner, proxy, source verification, supply, and an unlock schedule you give set against it. It names what the code allows. A clean reading never means safe, and it cannot detect a rug pull.

    Arguments: address: string, chain?: ethereum|base|arbitrum|optimism|..., announced_max_supply?: number, schedule?: {date,amount,note}[]

7 tools

SEC fundamentals

canli-fundamentals-mcp, also its own server.

  • known_as_ofKnown as of a date

    Get what a company had reported as of a date: per measure, the latest period filed by then, its value, and whether it was later restated; optionally ratios from those filings. For point-in-time backtests.

    Arguments: company: string, as_of: string, concepts?: string[], periods?: annual|quarterly, ratios?: boolean

  • historyMeasure history

    Get a measure (or several, with concepts) over time, newest first: latest (default), first reported, or as known on a filing date, with its filing, other version and yearly change.

    Arguments: company: string, concept?: string, concepts?: string[], basis?: first_reported|latest|as_of, as_of?: string, periods?: annual|quarterly|all, unit?: string, limit?: integer

  • restatementsRestated periods

    List periods whose value changed in a later filing, with first and latest values, % change and cause (stock splits left out by default). Omit concept to scan everything.

    Arguments: company: string, concept?: string, periods?: annual|quarterly|all, since?: string, min_change_pct?: number, include_splits?: boolean, limit?: integer, offset?: integer

  • vintagesFiling vintages

    List every filing that reported one period of one measure, oldest first: the revision history behind a number.

    Arguments: company: string, concept: string, end: string, start?: string, unit?: string

  • list_conceptsList concepts

    List the XBRL concepts a company reports and the plain names it supports, with units, periods, date range and restated-period counts.

    Arguments: company: string, search?: string, limit?: integer, offset?: integer

  • find_companyFind a company

    Find a company's SEC CIK and tickers by name, ticker or CIK. The other tools also take a name as company.

    Arguments: query: string, limit?: integer

  • cross_sectionCross-section as of a date

    Get one measure for up to 50 companies as filed by a date: each one's latest period, its value then, and whether it was later restated. For point-in-time peer and factor work.

    Arguments: companies: string[], concept: string, as_of: string, periods?: annual|quarterly

6 tools

Research record

canli-research-mcp, also its own server.

  • search_researchSearch research

    Find Canli Capital research papers (strategy tests, killed candidates, literature reviews, feasibility protocols) by words in their titles and summaries. Use it to find a paper's slug, then read it with get_paper; to browse by subject instead, use list_topics.

    Arguments: query: string, limit?: integer

  • list_topicsResearch topics

    The research topics, with how many papers each holds and what it covers.

  • get_paperRead a paper

    A research paper's text as published, by slug, with its headings; send section for one part, and max_chars to cap the length. Find the slug with search_research or list_topics first.

    Arguments: slug: string, section?: string, max_chars?: integer

  • trial_ledgerTrial ledger

    How many distinct hypotheses Canli Capital has tried against its declared budget, and how many were killed or survived. Use it to judge any published result against the size of the search behind it.

  • live_recordLive paper record

    The live paper-trading record (returns, costs, risk, corrections, provenance) and each sleeve's paper equity, with their limits. Use it for how the strategies are doing now; for why they exist, read the papers.

  • chain_headVerification chain head

    The head of the tamper-evident chain that shows the published record was not rewritten after publication, with where to verify it. Use it to check that a figure you read was not changed later.

5 tools

Paper trading

canli-paper-trading-mcp, also its own server.

  • paper_accountPaper account

    Read your Alpaca paper account: equity, cash, buying power, positions, open orders, the market clock, the kill switch and the local order log's verified head.

  • preview_paper_ordersPreview paper orders

    Check orders against your paper account, live quotes, the market clock, your limits file and the kill switch; when every order passes, return a five-minute confirmation token for exactly these orders.

    Arguments: orders: {symbol,side,qty,type,limit_price,tif}[], fees?: {commission_bps,per_share_usd,as_of}, limits?: object

  • rebalance_to_weightsRebalance to weights

    Turn target portfolio weights into the whole-share orders that move your paper account there (sells first), check them, and return a confirmation token when all pass.

    Arguments: target_weights: object, cash_buffer?: number, min_trade_usd?: number, liquidate_others?: boolean, allow_short?: boolean, allow_leverage?: boolean, fees?: {commission_bps,per_share_usd,as_of}, limits?: object

  • verify_attestationVerify an attestation

    Check an attestation a pre-trade check or send returned: that it was signed by the trader's keys (Ed25519 and, where present, post-quantum ML-DSA-65; both must hold) and not altered, and, given openings from the trader's commitments file, that committed account figures are what they claim. Offline; reads nothing from Alpaca.

    Arguments: attestation: {}, public_key_pem?: string, pq_public_key_pem?: string, openings?: {label,commitment,salt,value}[]

  • send_paper_ordersSend paper orders

    Send previewed orders to your Alpaca paper account with their confirmation token (the kill switch is read again first), or cancel open paper orders by id. Every send is logged, hash-chained.

    Arguments: token?: string, cancel_order_ids?: string[]

32 tools

Factor backtests

canli-backtest-mcp, also its own server.

  • list_factorsPoint-in-time factors

    The point-in-time factors pit_factor builds from SEC filings, and what each measures.

  • pit_factorBuild a point-in-time factor

    Build a factor from SEC filings for a list of tickers, monthly from start to end, using only what had been filed by each date (restatements invisible until filed). Writes a signal CSV for backtest_signal. Values are what companies reported to the SEC in XBRL, as filed by each date; a company that files late, files outside XBRL or changes its tags can be missing.

    Arguments: factor: string, tickers: string[], start: string, end: string, out_file?: string

  • backtest_signalBacktest a signal without lookahead

    Backtest a signal against your prices: rank, long and short quantiles, rebalance, trading only on what was known lag_days earlier, costs on actual trades. Every reply holds the result against the crises its dates cover and lists the ones it does not. With capital_usd and dollar_volume_file, orders fill only as far as the market traded, pay square-root impact, and the reply shows the Sharpe at each size the market can take. Pass ledger to judge the best of a search against all of it. A backtest measures one path of history under these costs; it does not establish that the signal will keep working.

    Arguments: prices_file: string, signal_file: string, rebalance?: weekly|monthly|quarterly|integer, lag_days?: integer, side?: long_short|long_only, quantile?: number, cost_bps?: number, min_names?: integer, periods_per_year?: number, capital_usd?: number, dollar_volume_file?: string, max_participation?: number, impact_coefficient?: number, crisis_drawdown_limit?: number, ledger?: string, label?: string

  • proof_filingsAdd company filings to a proof ledger

    Add what companies filed to a signed, append-only ledger: each figure with its filing, and a restatement line whenever a later filing changes one. Re-running adds only what is new. It shows the lines were not altered afterwards, not that a figure is right.

    Arguments: ledger_file: string, companies: string[], key_file?: string

  • proof_fileRecord a file in a proof ledger

    Record a file's hash in a signed, append-only ledger, a backtest result or a returns file, so anyone can later check this exact file existed by then. Nothing else about the file is claimed.

    Arguments: ledger_file: string, file: string, label: string, kind?: backtest|returns|league_entry|other, key_file?: string

  • proof_verifyVerify a proof ledger

    Check a proof ledger from the file alone: every hash, order and signature, and any heads published elsewhere. Says which line first fails.

    Arguments: ledger_file: string, anchors?: {seq,hash}[]

  • proof_findLook up a proof ledger

    Look up a file, company or concept in a proof ledger. No record means only that this ledger holds none, not that anything is wrong.

    Arguments: ledger_file: string, sha256?: string, file?: string, company?: string, concept?: string, kind?: figure|restatement|file, limit?: integer

  • league_newStart a paper league

    Start a paper league: a schedule of rounds and rules with a hash to publish. No prizes, no stakes and nobody's money.

    Arguments: league_dir: string, name: string, first_close: string, rounds: integer, days_per_round?: integer, min_names?: integer

  • league_commitCommit a league entry

    Commit a league entry before its round closes: only the hash of its CSV of ticker,score goes in the ledger, and the file is shown after the round. Only the latest commit counts, so revealing whichever of several did best is refused.

    Arguments: league_dir: string, round: string, entrant: string, file: string, entrant_key_file: string, key_file?: string

  • league_scoreScore a paper league

    Score a paper league from its files and prices, repeatable by anyone: each entrant's rank correlation with what followed, set against the best luck gives across that many entrants, how different each is from the rest, and a paper book of the top entrants chosen on earlier rounds only.

    Arguments: league_dir: string, prices_file: string, book_size?: integer

  • exchange_newStart a paper exchange

    Start a paper exchange where different AI agents and scripted traders (market makers, momentum, value, deleveragers, stop-losses, levered longs) trade in limit order books, with margin rules and forced selling, plus shocks at set steps. Made-up assets and money, reproducible from a seed.

    Arguments: exchange_file: string, seed?: integer, assets?: integer, personas?: {market_maker,value,momentum,noise,deleverager,stop_loss,levered_long}, starting_cash?: number, maintenance_margin?: number, leverage?: number, shocks?: {step,kind,asset,percent,steps,quantity}[]

  • exchange_joinJoin a paper exchange

    Join a paper exchange as an agent. Returns the token its other calls need, so no agent can act as another.

    Arguments: exchange_file: string, agent: string, about?: string

  • exchange_viewSee a paper exchange

    What an agent in a paper exchange can see: the books, recent trades and its own account. No other agent's positions.

    Arguments: exchange_file: string, agent: string, token: string, depth?: integer

  • exchange_ordersSend orders to a paper exchange

    Send an agent's limit orders, market orders and cancels for the coming step of a paper exchange. An empty list passes.

    Arguments: exchange_file: string, agent: string, token: string, orders: object[]

  • exchange_stepMove a paper exchange on

    Move a paper exchange on. Waits for every joined agent to act, so nobody moves time on the others.

    Arguments: exchange_file: string, steps?: integer, force?: boolean

  • exchange_reportReport a paper exchange

    What happened in a paper exchange: each asset's worst fall and recovery, spreads and depth, who gained and lost, forced selling and the longest chain of it, and a hash anyone can check by replaying.

    Arguments: exchange_file: string

  • exchange_runRun a whole paper exchange

    Run a whole paper exchange of scripted traders in one call and report it: for comparing set-ups, such as how much leverage turns a shock into a cascade. A simulation, not a forecast.

    Arguments: seed?: integer, assets?: integer, personas?: {market_maker,value,momentum,noise,deleverager,stop_loss,levered_long}, starting_cash?: number, maintenance_margin?: number, leverage?: number, shocks?: {step,kind,asset,percent,steps,quantity}[], steps: integer

  • agent_consensusCombine agents' forecasts and count independent views

    Combine several AI agents' probabilities, and count how many independent views they really hold, from how their errors move together: five models that share their mistakes are not five votes. Weights each by its record on settled questions.

    Arguments: agents: {name,forecasts}[], outcomes?: {question,happened}[]

  • find_diversifiersFind what diversifies a book

    Rank candidate strategies by what they add to a book: independent bets added first, then how they behave on the book's worst days, with return shown last and never used to rank. Correlation first.

    Arguments: book_file: string, candidates_file: string, limit?: integer, min_days?: integer

  • arena_newStart a paper arena

    Start a paper market for AI agents to trade in: made-up assets and made-up money, with scripted traders, reproducible from a seed. Nothing here represents or reaches a real security, token or currency.

    Arguments: arena_file: string, seed?: integer, assets?: integer, starting_cash?: number, bots?: integer

  • arena_ordersSend paper orders to an arena

    Send paper orders for an agent in an arena, for the coming auction. No short selling and no borrowing.

    Arguments: arena_file: string, agent: string, orders: {asset,side,quantity,limit}[]

  • arena_stepClear a paper arena

    Clear a paper arena's next call auctions at one price per asset, and show prices and standings. Paper only.

    Arguments: arena_file: string, steps?: integer

  • crisis_replayReplay strategies through named crises

    Hold any strategy's daily returns against named market crises (2000-02 dot-com bust, 2008-09 bank crisis, 2011 US downgrade and euro debt scare, 2013 taper tantrum in bonds and others): its return, drawdown and worst day in each one its dates fully cover, and the crises it was not there for, listed as untested and never as passed.

    Arguments: returns_file: string, drawdown_limit?: number

  • cpcvCombinatorial purged cross-validation

    Combinatorial purged cross-validation of a search: choose the best trial on training days, score it on held-out blocks, with purge and embargo at the edges, for every choice of blocks, stitched into whole paths. Returns the spread of out-of-sample Sharpes against the in-sample one. Splits can run as shards on other machines and merge back. Paths share days and data, so their spread is not a confidence interval and they are not independent tests.

    Arguments: returns_file?: string, groups?: integer, test_groups?: integer, purge_days?: integer, embargo_days?: integer, periods_per_year?: number, shard?: {index,of}, out_file?: string, merge_files?: string[]

  • price_panelBuild a price panel

    Build a price panel from free sources for breadth_book or backtest_signal: the tickers you name or an index fund's current holdings, daily adjusted closes and dollar volume, and each company's Fama-French industry from its SEC SIC code, written as CSV files.

    Arguments: tickers?: string[], index_fund?: string, max_names?: integer, start: string, end?: string, out_dir?: string

  • breadth_signalsBreadth lab signals

    The cross-sectional signals breadth_book builds sleeves from: momentum, reversal, low volatility and beta, idiosyncratic risk, lottery demand, skewness, price delay, seasonality and liquidity, each with its formula's source and the data it needs.

  • breadth_bookBreadth book of sleeves

    Build many weakly correlated sleeves (every signal inside every group of names) from your price panel and trade them as one netted account, ALPHAC's breadth lab: rank-weighted within each group, overlapping portfolios, hedged and scaled to a volatility target, costs on actual trades. Returns the book netted and standalone, the netting ratio, effective independent bets and ideas, and writes every sleeve's returns as a training dataset. A sleeve built on many signals and groups is a search: report the number of sleeves, keep a period untouched for the test, and judge the book there, not on the years used to choose it.

    Arguments: prices_file: string, groups_file?: string, dollar_volume_file?: string, signals?: string[], min_names?: integer, smoothing?: integer, cost_bps?: number, target_vol?: number, split_date?: string, out_file?: string, ledger?: string

  • breadth_sweepParallel sweep of breadth settings

    Run a grid of breadth-book settings (signal sets, smoothing, target volatility, costs, minimum names) in parallel on every core of this machine, or as shards other machines run and merge_files joins. Every combination counts as a trial: the best Sharpe is set against what the best of that many trials reaches by luck, and with split_date the chosen settings are scored after the split.

    Arguments: prices_file?: string, groups_file?: string, dollar_volume_file?: string, grid?: {smoothing,target_vol,cost_bps,min_names,signals}, split_date?: string, workers?: integer, shard?: {index,of}, out_file?: string, merge_files?: string[]

  • effective_betsEffective independent bets

    How many independent bets a set of return series holds: the participation ratio of their weekly correlations (n for unrelated series, 1 for copies), and with families, the families' bets and the ideas they cluster into.

    Arguments: returns_file: string, family_separator?: string, threshold?: number

  • annotation_packetAnnotation packets

    Start a labelled dataset: figures (company, measure, period, value) are checked by machine against the SEC filings and written as blind CSV packets for two or more people to label, with guidelines and a key holding the machine labels.

    Arguments: task: string, items?: {company,measure,period,value,unit,note}[], items_file?: string, text?: string, company?: string, annotators?: integer, assisted?: boolean, out_dir?: string

  • annotation_agreementAnnotation agreement

    Read filled annotation packets: how often the people agree (Cohen's kappa), how often they agree with the machine, and every disagreement.

    Arguments: task_dir: string

  • annotation_goldAnnotation gold set

    Merge filled annotation packets and a reviewer's decisions into a gold dataset (JSONL: each item's label, who decided it, the machine label and source) with a datasheet of agreement and hashes.

    Arguments: task_dir: string, reviews?: {item_id,label,correct_value,note}[]