Skip to content

FinanceToolkit v2.4.0

Latest

Choose a tag to compare

@github-actions github-actions released this 27 Nov 06:58
cdaa8c6

This release brings the formulas known from the established technical analysis, performance, risk, portfolio and fundamental analysis libraries and their literature into the Finance Toolkit, so they can be applied directly to its financial statements, prices and benchmarks. The credit for these measures goes to their authors and to the libraries that defined or popularised them (TA-Lib, pandas-ta-classic, ta, finta, Riskfolio-Lib, skfolio, PyPortfolioOpt, empyrical, pyfolio, quantstats, ffn and PerformanceAnalytics, among others): each docstring cites the papers and the library it is referenced against, and each measure is checked numerically against that library.

It is a minor release because it changes names: variants of one measure are now one method with method=, and the old names are removed without aliases. Every removed name and its replacement is listed under Methods with variants.

Package

Methods with variants

Variants of one measure are one method with method=, as get_sharpe_ratio already was. The old names are removed:

  • get_jensens_alpha → get_alpha(method="jensen"); get_extended_dupont_analysis → get_dupont_analysis(method="extended"). (#589)

  • get_gjr_garch, get_egarch and their _forecast and _parameters methods → get_garch, get_garch_forecast and get_garch_parameters with method="gjr" or "egarch". (#589)

  • get_edge_spread, get_corwin_schultz_spread and get_abdi_ranaldo_spread → get_bid_ask_spread(method="edge" | "corwin_schultz" | "abdi_ranaldo"). (#589)

  • get_minimum_cvar_weights, get_maximum_cvar_ratio_weights and get_minimum_drawdown_weights → get_mean_risk_weights with risk_measure="cvar", "cdar", "maximum_drawdown" or "average_drawdown" (and objective="maximum_ratio"), with the same weights and one extra <measure> Ratio column. (#589)

  • get_augmented_dickey_fuller, get_phillips_perron_test and get_zivot_andrews_test → get_unit_root_test(method="augmented_dickey_fuller" | "phillips_perron" | "zivot_andrews") (KPSS stays separate, as its null hypothesis is stationarity); get_breusch_pagan_test and get_white_test → get_heteroskedasticity_test(method="breusch_pagan" | "white"); get_logistic_regression and get_probit_regression → get_binary_choice_regression(method="logit" | "probit"); get_rmse and get_mae → get_forecast_error(method="rmse" | "mae"). (#641)

  • get_treynor_mazuy_model and get_henriksson_merton_model → get_market_timing_model(method="treynor_mazuy" | "henriksson_merton"). (#647)

  • Duplicates removed: get_net_income_per_ebt (use get_tax_burden_ratio), get_EBT_to_EBIT (use get_interest_burden_ratio) and get_EBIT_to_revenue (use get_operating_margin), also from the profitability collection. (#647)

  • get_bjerksund_stensland → get_american_option(method="bjerksund_stensland"), with "bjerksund_stensland_1993" for the 1993 version. (#649)

  • get_kaufman_adaptive_moving_average → get_moving_average(method="kaufman_adaptive"), get_stochastic_relative_strength_index → get_stochastic_oscillator(method="rsi"), get_percentage_price_oscillator → get_moving_average_convergence_divergence(method="percentage") and get_negative_volume_index / get_positive_volume_index → get_volume_index(method="negative" | "positive"). The variants this release adds are options of the same methods: get_moving_average takes 24 averages, and the RSI (Connors, Laguerre on 0 to 100, dynamic, intraday), MACD, ATR, ADX, rate of change, Supertrend, Keltner channels, Hilbert sine wave and Chaikin money flow take theirs through method=. (#591, #598)

  • A statistic exists once, for the whole sample and for a rolling window: the model functions get_rolling_variance, get_rolling_volatility, get_rolling_excess_volatility, get_rolling_skewness, get_rolling_kurtosis, get_rolling_tail_ratio, get_rolling_downside_deviation and get_rolling_conditional_drawdown_at_risk (risk), get_rolling_var_historic and get_rolling_cvar_historic, and the 18 get_rolling_* functions of the performance model (beta, alpha, Sharpe, Sortino, autocorrelation penalty, safety first, upside potential, M², tracking error, information ratio, omega, Kelly, appraisal, style analysis, Morningstar risk-adjusted return, Lo's Sharpe, standard deviation, residual standard deviation) → the function without rolling in its name with window=N, with identical values. (#658)

  • risk.get_move_significance → econometrics.get_move_significance, which gives the same values for the Toolkit's tickers (with include_benchmark=True for the benchmark). (#658)

Renamed parameters

One name per meaning across the package. The old names are removed:

  • distribution → method in get_value_at_risk, get_conditional_value_at_risk, get_marginal_value_at_risk, get_component_value_at_risk, get_var_backtest and get_acerbi_szekely_test; window_size → window in get_var_backtest, get_acerbi_szekely_test and get_diebold_mariano_test; random_state → seed (default 0 instead of 42) in get_acerbi_szekely_test and get_copula_simulation, whose n_simulations → simulations. (#650)
  • time_steps → forecast_steps in get_garch_forecast; maxlags → lags in get_ols and get_wls; k_ar_diff → lags in get_johansen_cointegration and get_vecm_forecast; include_constant → add_constant in get_arima_forecast; rolling → window in get_ulcer_index; threshold → minimum_acceptable_return in get_safety_first_ratio. (#650)
  • confidence_level (0.95) → alpha (0.05) in get_risk_contributions and get_portfolio_risk_metrics; svensson → method="svensson"|"nelson_siegel" in get_nelson_siegel_svensson; duration_type → method in get_duration; model → method in get_altman_z_score; paths → simulations in get_short_rate_simulation; timesteps → time_steps in get_binomial_model and get_stock_price_simulation; atr_multiplier → multiplier in get_keltner_channels; get_monte_carlo_option_price defaults to seed=0, so repeated calls give the same price. (#652)
  • window → rolling in get_style_analysis and get_pairs_trading, as in every other method where a number asks for a rolling window and None for the whole sample. (#658)
  • A mistake in a call (an unknown method, option or period, or an alpha outside 0 to 1) raises an InvalidArgumentError that names the valid values, instead of an empty result that reads as missing data; missing data still gives an empty result. A window below its minimum, a rolling window below two, an unknown close column or column and an unknown covariance estimator raise the same way. Standalone use without a Toolkit and a wrong type of tickers also say what to pass. A rolling, trailing or lag longer than the data logs that no period has a complete window instead of returning NaN without a word. (#650, #652, #661, #662, #663, #664, #665, #667, #668)
  • Output labels: "Std. Error" → "Standard Error", "T-Statistic" → "t-Statistic", "P Value" and "p-Value" → "P-Value"; the Johansen critical values are labelled by significance level ("Trace Critical Value 5%", "Max-Eigenvalue Critical Value 5%") like every other test. (#650)

Technicals

  • Directional and simple momentum indicators, referenced against TA-Lib: the directional movement index (+DM, −DM, +DI, −DI, DX), ADXR, the absolute price oscillator, momentum, the accelerator oscillator (get_awesome_oscillator(method="accelerator")), internal bar strength, the intraday momentum index, Qstick, the efficiency ratio and the vertical horizontal filter. TA-Lib's variants as options: the Aroon oscillator, the smoothed CMO, true-range choppiness, the MACD histogram with MACDEXT and MACDFIX, the PPO signal line and histogram, the slow stochastic and KSTEXT. (#544, #641)

  • The factor analysis and the indicator summary use an indicator's main line by default, not its histogram or signal line (the PVO used its histogram). (#544)

  • Moving averages, referenced against TA-Lib, pandas-ta-classic and finta: TEMA, ZLEMA, Wilder's average, sine, Fibonacci and Pascal weighted averages, T3, ALMA, the volume weighted moving average, the McGinley dynamic, VIDYA and FRAMA, all as options of get_moving_average. (#545)

  • Volume indicators, referenced against TA-Lib, pandas-ta-classic and finta: the Klinger volume oscillator, the market facilitation index, Williams' accumulation/distribution, relative volume, the volume flow indicator, finite volume elements, Twiggs money flow, the volume zone oscillator, the cumulative force index (get_force_index(method="cumulative")), price-volume and its rank, buying and selling pressure, Archer's on-balance volume and the volume profile. The percentage volume oscillator with moving_average="simple" is the volume oscillator. (#547, #598, #641)

  • Oscillators, referenced against TA-Lib, pandas-ta-classic and finta: the Fisher transform and the inverse Fisher transform of the RSI, KDJ, the premier stochastic oscillator, the stochastic momentum index, the SMI ergodic indicator (get_true_strength_index(method="ergodic")), the Schaff trend cycle, WaveTrend, the derivative oscillator, the swing index, QQE, the dynamic momentum index and the price zone oscillator. (#549, #641)

  • Candlestick patterns, referenced against TA-Lib: belt-hold, closing marubozu, dragonfly, gravestone and long-legged doji, high-wave, long line, rickshaw man, short line and takuri, and the inside bar, so get_candlestick_patterns covers 26 patterns. Heikin-Ashi candles and Williams' fractals, marked on the bar that confirms them. (#550)

  • Two-candle patterns and doji star variants, referenced against TA-Lib, so get_candlestick_patterns covers 41 patterns: counterattack, doji star, harami cross, homing pigeon, in-neck, on-neck, thrusting, kicking, kicking by length, matching low, separating lines, three inside, three outside, and the morning and evening doji star. (#555)

  • Three-candle patterns described by Nison and Bulkowski, referenced against TA-Lib, so get_candlestick_patterns covers 54 patterns: two crows, three stars in the south, abandoned baby, advance block, side-by-side white lines, identical three crows, stalled pattern, stick sandwich, tasuki gap, tri-star, unique three river, upside gap two crows and the upside/downside gap three methods. (#565)

  • The last candlestick patterns, referenced against TA-Lib, so get_candlestick_patterns covers 62: three-line strike, concealing baby swallow, breakaway, ladder bottom, mat hold, rising/falling three methods and Chesler's hikkake and modified hikkake (±1 for the setup, ±2 for its confirmation). DeMark's TD Sequential (get_td_sequential, setup and countdown), referenced against pandas-ta-classic's td_seq, and the liquidity sweep of the Smart Money Concepts community (get_liquidity_sweep), referenced against pandas-ta-classic's smc_sweep. (#570)

  • The candlestick patterns and Ehlers' cycle indicators are written from their published definitions: each pattern is a short set of conditions on the last candles and get_candle_features gives the candle parts and reference sizes; the values are unchanged. (#566)

  • Overlap indicators and price transforms, referenced against TA-Lib, pandas-ta-classic and finta: the typical, average, median and weighted close price, the midpoint and midprice, the Holt-Winters moving average and channel, the elastic volume weighted and volume adjusted moving averages, Gann HiLo and TA-Lib's confirmed zigzag. Fibonacci, Camarilla, Woodie and DeMark pivots and the central pivot range (get_pivot_points(method=)), a TRIX signal line, TA-Lib's extended parabolic SAR options, the anchored VWAP (anchor=) and any moving average as the middle Bollinger Band (moving_average=). (#551)

  • Volatility indicators, referenced against TA-Lib, pandas-ta-classic, ta and finta: the normalized ATR, the average day range, Chaikin volatility, Dorsey's relative volatility index (original and refined), acceleration bands, the Chande Kroll stop, the adaptive price zone, aberration, the profit maximizer, the price distance, Elder's market thermometer and the TTM squeeze with LazyBear's momentum. Keltner's original channel (get_keltner_channels(method="original")) and the Donchian channel including the current period (include_current=True). (#553)

  • Momentum indicators that combine other indicators, referenced against TA-Lib, pandas-ta-classic and finta: Connors RSI, Dorsey's inertia, the bias, BRAR, the pretty good oscillator, the psychological line, volatility-based momentum, Archer's moving average trends and the TTM trend, and the volume-weighted and elastic volume-weighted MACD (moving_average="volume_weighted" / "elastic_volume_weighted"). (#559)

  • Ehlers' Hilbert transform indicators, referenced against TA-Lib: the dominant cycle period and phase, the phasor components, the sine wave and the trend mode (collect_cycle_indicators, and "cycle" in collect_all_indicators), the MESA adaptive moving average with its following average and the instantaneous trendline. (#556)

  • Ehlers' filters and cycle oscillators, referenced against TA-Lib and pandas-ta-classic: the Swiss Army Knife filter (high-pass, two-pole high-pass, band-pass, Butterworth and Gaussian), the SuperSmoother (two or three poles), the even better sinewave, the detrended synthetic price, the MESA sine wave, the center of gravity oscillator and the Laguerre RSI. (#568, #598)

  • Labeling (López de Prado, AFML ch. 2–4), a new topic: get_event_filter (symmetric CUSUM and z-score), get_triple_barrier_labels (with meta-labels through side=), get_fixed_horizon_labels (absolute or relative to the mean, median or benchmark), get_trend_scanning_labels, get_tail_set_labels, get_matrix_flag_labels, get_label_uniqueness and get_sample_weights (return attribution and time decay); the forward-looking labels say so, and the filters, volatility targets and matrix flags use data up to each date only.. (#616)

  • get_bet_sizes(method="budget"|"reserve"|"probability") sizes the meta-label bets (AFML ch. 10): the reserve method fits the EF3M mixture by solving the five moment equations exactly (the same fit for every seed), and probability sizing uses the hit rate of bets closed before each bet; sizing from classifier probabilities and dynamic sizing from forecast prices are models. (#619)

  • From R's TTR: get_signal_to_noise_ratio (Skeggs and Hill), get_trend_detection_index (Pee), get_dv_intermediate_oscillator (Varadi), price bands (get_bollinger_bands(method="price_bands")) and get_guppy_multiple_moving_averages with the group spreads (Guppy), added to the momentum, overlap and volatility collections; differences from TTR's warm-up and ranks are stated. (#625, #641)

Econometrics

  • The econometrics module works without statsmodels and linearmodels: 47 of its 67 methods (the tests, OLS/WLS/GLS, VAR, the causal methods and the statistics) need neither, and the 20 that use one (unit root tests, cointegration, ARIMA/VECM, Logit/Probit/quantile regression, regime switching, the panel models and IV) name the missing library and pip install financetoolkit[econometrics]. (#592)
  • A statistics topic, referenced against TA-Lib, pandas-ta-classic and finta: the linear regression line, slope, intercept, angle and time series forecast, and the correlation, percentile (the median by default), percent rank, z-score, mean absolute deviation and standard error over the whole sample or a rolling window (rolling=), on the adjusted close with the Econometrics period and include_benchmark options. (#542, #564, #657)
  • The correlation trend indicator and the forecast and projection oscillators are momentum indicators in Technicals, and the standard deviation channel is a volatility indicator. (#542, #564)
  • The Hausman test reports a negative statistic as it is (with a NaN p-value) and takes variance="efficient" or "consistent" to use one residual variance for both covariances, referenced against linearmodels. (#578)
  • Least squares (OLS, WLS and GLS with the nonrobust, HC0-HC3, Newey-West and cluster-robust covariances) and the test statistics (Durbin-Watson, Jarque-Bera, Ljung-Box, Breusch-Pagan, White, ARCH-LM, RESET, VIF, Granger, the t-tests, the F, Wald and likelihood ratio tests and the OLS-CUSUM test) are calculated from their published formulas, referenced against statsmodels; the estimators that need an iterative or likelihood engine stay on statsmodels and linearmodels. The regression result no longer carries statsmodels_result, and Jarque-Bera, VIF and Granger give NaN for a constant series. (#586)
  • Fractional differentiation (get_fractional_difference, fixed-width or expanding window) and the minimum order that makes a series stationary, the SADF and GSADF bubble tests of Phillips, Wu, Shi and Yu with critical values simulated from 2,000 paths, bubble episodes dated by the backward SADF, and the Chow-type Dickey-Fuller break test, after López de Prado; referenced against statsmodels' ADF (3e-13). (#605, #643)
  • get_entropy with sample, approximate, permutation, spectral, SVD, share (pandas-ta-classic's entropy of a window's values as shares of their sum), Shannon, Lempel-Ziv and Kontoyiannis entropy (the last three on encoded returns, after López de Prado), get_lempel_ziv_complexity and get_hjorth_parameters, over the whole sample or a rolling window (rolling=), referenced against antropy and nolds. (#607, #657)
  • Forecast evaluation: get_berkowitz_test (density forecasts through the probability integral transform, with the censored tail variant), get_directional_accuracy_test (Pesaran-Timmermann and Anatolyev-Gerko) and get_model_confidence_set (Hansen, Lunde and Nason, on QLIKE loss across EWMA, rolling, GARCH and GJR volatility forecasts); the confidence set matches arch given the same bootstrap draws. (#612)
  • Breaks and stability: get_cusum_test(method="ols"|"recursive"|"chu_stinchcombe_white") with time_series= for the Chu-Stinchcombe-White statistic per date, weighted=True on get_ljung_box_test and get_arch_lm_test (Fisher and Gallagher), get_sign_bias_test (Engle and Ng) and get_pearson_goodness_of_fit_test (Palm) on GARCH residuals, get_change_points (PELT for the mean, the variance or both) and get_optimal_trading_rule (profit-taking and stop-loss levels on a fitted Ornstein-Uhlenbeck process, AFML ch. 13); within 1e-14 of statsmodels and identical to ruptures. (#622)
  • get_nyblom_test (parameter stability of GARCH fits, p-values from the limiting distribution), get_gmm_moment_test (Hansen's moment conditions on the standardized residuals; the joint test uses the covariance the innovation distribution implies, which keeps its size near 5% where the sample covariance rejects 10 to 20% of the time) and get_hong_li_test (the nonparametric density test of Hong and Li, with p-values from its simulated null distribution, as the normal approximation rejects about 18% of the time). (#632, #643)

Topic folders

  • Calculations and data retrieval that were written inside class methods are module functions in each package's model files and sources/ folders, e.g. financetoolkit.models.sources.peers_model.compare_with_peers or financetoolkit.options.get_variance_swap_terms, so they can be used and tested on their own. (#680, #681)
  • Technicals: breadth, momentum, overlap, volatility, pattern, seasonality and cycle, e.g. from financetoolkit.technicals.momentum import momentum_model. The module paths financetoolkit.technicals.<name>_model are removed. (#531)
  • Model functions are importable from their package, e.g. from financetoolkit.models import get_altman_z_score or from financetoolkit.risk import get_var_historic; a model module is only imported when one of its functions is first used. For this every name is defined once per package: the distress ratios shared by several models keep one definition (get_working_capital_to_total_assets_ratio, get_retained_earnings_to_total_assets_ratio and get_sales_to_total_assets_ratio in altman_model; get_net_income_to_total_assets_ratio and get_total_liabilities_to_total_assets_ratio in ohlson_model; get_ebit_to_total_assets_ratio in grover_model; get_current_liabilities_to_total_assets_ratio in fulmer_model) and the copies in the other model modules are removed, ratios.efficiency_model.get_operating_margin is removed (use profitability_model.get_operating_margin) and constraints_model.get_log_of_total_assets is renamed get_log_of_total_assets_in_millions. (#672)

Performance

  • Ratio variants, referenced against quantstats, empyrical and PerformanceAnalytics: the smart, adjusted and probabilistic Sortino ratio, the smart Sharpe ratio, whole-sample Calmar, Sterling and Active Premium (method="annualized"), the modified Burke and Treynor ratios, the appraisal ratio variants, M² Sortino and M² excess return, the Omega-Sharpe ratio (a threshold on the gain to pain ratio), the Omega excess return, the d ratio and the Prospect ratio. (#540)
  • The probabilistic and deflated Sharpe ratio work with annualize=True, which returns the same probability, where it returned an empty result. (#540)
  • Benchmark-relative and return statistics, referenced against quantstats, empyrical, ffn, pyfolio and PerformanceAnalytics: best and worst return, exposure, the CPC index, profit and outlier ratios, risk of ruin, the mean return with its confidence limits, the outperformance probability, bull and bear beta with the timing ratio, capture ratios (geometric, annualized and arithmetic, also rolling, with the up/down number and percent), the win rate in up and down markets, beta fragility, stability of returns, R², the risk-return ratio, the risk decomposition and the capital and security market lines. (#548)
  • Return tables, simulations and overfitting tests, referenced against quantstats, ffn, pyfolio and PerformanceAnalytics: log and Geltner-unsmoothed returns (get_returns(logarithmic=True), unsmoothed=True), the smoothing index, the Serenity index, the return over any risk measure, probabilistic momentum, trailing and calendar returns, bootstrap statistics and a forecast cone, the probability of backtest overfitting and rolling Fama-French and Carhart regressions. (#552)
  • The factor analysis of every module (get_factor_analysis in ratios, models, technicals, performance and risk) gains group= (sector, industry or a mapping) with IC per group and group-neutral IC, demeaned=, binning= (quantile, equal width, zero aware or per group), IC skewness and kurtosis, the annualized alpha and beta of the factor-weighted long-short portfolio, and detail= views for the IC by month or year, quantile returns by date and their statistics, factor weights, factor and cumulative returns and event returns; within 6e-14 of alphalens-reloaded, where alphalens' halved spread and joint horizon filtering are deliberate differences. (#609)
  • get_variability_weighted_return (VWR with τ = 2 and σ_max = 0.20 as defined, where backtrader's defaults are swapped), get_return_concentration (the HHI of positive and negative returns and over time) and get_strategy_risk (precision, bets per year, the binomial Sharpe ratio, the implied precision and frequency for a target Sharpe and the probability of failure, AFML ch. 15). (#619)
  • get_sharpe_ratio_difference_test against the benchmark, with Memmel's correction of Jobson-Korkie or the HAC test of Ledoit and Wolf (2008). (#631)

Portfolio

  • Estimators, referenced against PyPortfolioOpt, skfolio, Riskfolio-Lib, ffn and PerformanceAnalytics on every optimizer: compounded expected returns, James-Stein and Bodnar-Okhrin-Parolya shrinkage, the shrunk, denoised and Gerber covariance, and distance correlation, mutual information, Gerber, detoned and lower tail codependence, with the hierarchical optimizers clustering on each codependence's own distance. New methods show them on their own: get_expected_returns_estimate, get_covariance_estimate, get_codependence_matrix, get_asset_clusters (also Varadi's FTCA), get_coskewness_matrix, get_cokurtosis_matrix and get_estimation_uncertainty (bootstrapped bounds). (#541)
  • expected_returns="james_stein" is renamed to "bayes_stein", Jorion's estimator it is; "james_stein" is now the James-Stein estimator, which shrinks towards the grand mean. (#541)
  • Factor models, views and attribution, referenced against Riskfolio-Lib, skfolio, empyrical, pyfolio and PerformanceAnalytics: factor loadings by OLS, stepwise selection or principal components and a factor covariance (covariance="factor") for every optimizer, augmented and Bayesian Black-Litterman with factor views, entropy and opinion pooling, risk contributions for twelve more risk measures, factor risk contributions, factor attribution and return contributions per period. The Portfolio module gains turnover, gross leverage and return contributions. (#554, #593)
  • Robust and graph covariance estimators, referenced against scikit-learn, Riskfolio-Lib and skfolio, on every optimizer: the minimum covariance determinant (FastMCD), j-LoGo, geodesic shrinkage and the regime-adjusted exponentially weighted covariance (covariance="minimum_covariance_determinant", "jlogo", "geodesic", "regime_adjusted_ew"). (#558)
  • The minimum covariance determinant, the TMFG and j-LoGo and entropy and opinion pooling are written from their papers: the MCD is the FAST-MCD search of Rousseeuw and Van Driessen (1999) with its own random subsets (its values move by about 1% from the earlier ones), and entropy pooling meets every view to 1e-8. (#569)
  • get_mean_risk_weights minimizes a risk measure or maximizes the return per unit of it, and get_risk_parity_weights(risk_measure=...) budgets it, referenced against skfolio, Riskfolio-Lib and PyPortfolioOpt: the mean absolute deviation, first lower partial moment, worst realization, range, CVaR, CVaR range, CDaR, Gini mean difference, tail Gini, tail Gini range, semideviation and Ulcer Index, solved with SciPy linear programmes (cutting planes for the ordered weighted averages) and SLSQP. (#567)
  • l2_regularization= on the minimum variance, maximum Sharpe and mean-variance optimizers and the efficient frontier pulls the weights towards equal weights (DeMiguel, Garlappi, Nogales and Uppal, 2009), sharing similar logic as PyPortfolioOpt's L2_reg; the backtest also runs "minimum_mad", "minimum_semideviation" and "random" portfolios. (#572)
  • get_critical_line_weights gives the exact corner portfolios of the bounded frontier (Markowitz, 1956), referenced against PyPortfolioOpt's CLA; get_worst_case_mean_variance_weights optimizes for the worst expected returns within a box or ellipsoid (Goldfarb and Iyengar, 2003; Tütüncü and Koenig, 2004), referenced against Riskfolio-Lib and skfolio; and get_distributionally_robust_cvar_weights minimizes the worst CVaR over a Wasserstein ball (Mohajerin Esfahani and Kuhn, 2018), referenced against skfolio. (#574)
  • The hierarchical risk parity, HERC and NCO optimizers take risk_measure= (the mean-risk measures, CVaR and CDaR; Raffinot, 2017 and 2018) and HERC within_clusters="equal" (HERC2), referenced against Riskfolio-Lib and skfolio; cluster_criterion="standardized_silhouette" (López de Prado, 2020) chooses the number of clusters; get_schur_complementary_weights moves between HRP and minimum variance (Cotton, 2024) and get_stacking_weights combines optimizers (Wolpert, 1992), both referenced against skfolio. (#576)
  • linkage_method="dbht" clusters with the Directed Bubble Hierarchical Tree (Song, Di Matteo and Aste, 2012) on the TMFG, in HRP, HERC, NCO, Schur and get_asset_clusters, referenced against Riskfolio-Lib's DBHTs. (#582)
  • Using portfolio.toolkit no longer adds the benchmark to the Portfolio's own data, which made the portfolio overview fail afterwards. (#557)
  • get_trades, get_trade_statistics and get_position_timing on the Portfolio: round trips from the transactions (long and short, partial closes, open lots marked to market) with win rate, profit factor, expectancy, SQN, Kelly, streaks and average holding period, and the flattening and flip dates of López de Prado; signal or pairs positions give the same trade list through the model. (#601)
  • Estimators: covariance= gains "nercome" (Lam's split estimator), "ccc_garch" (constant conditional correlation on per-asset GARCH), "mm" and "rocke" (robust S/MM estimators) and "denoised_detoned"; co-moments from CCC-GARCH; get_random_matrix_statistics (the Marčenko-Pastur fit); absolute_angular, squared_angular and gnpr codependence; ONC clustering (get_asset_clusters(method="onc") and cluster_criterion="onc" for NCO), identical to RiskLabAI; centroid expected returns from a ranking; and ranking views in entropy pooling. The slow estimators are refused in the MCP backtest. (#623)

Risk

  • Dispersion and distribution measures, referenced against Riskfolio-Lib, skfolio and PerformanceAnalytics: partial moments of any order (downside potential, downside and upside frequency), the semi-deviation, central moments, the worst realization, the Gini mean difference, the tail Gini, risk ranges, L-moments and the L-moment risk measure, the skewness-kurtosis ratio, upside deviation and volatility skewness. (#538)
  • Tail and drawdown measures, referenced against Riskfolio-Lib, skfolio, empyrical, ffn and PerformanceAnalytics: the historical EVaR (method="historic"), the entropic risk measure, the EVaR range, the weighted (spectral) CVaR, kernel VaR and expected shortfall, uncompounded drawdowns (compound_returns=False), the rolling maximum drawdown, Drawdown at Risk, the average drawdown, drawdown statistics and the Entropic Drawdown at Risk. (#543)
  • Adjusted prices add up the dividends paid on one ex-date (an ordinary and a special dividend), where only one of them was used. (#538)
  • The GARCH family on get_garch, get_garch_forecast and get_garch_parameters: IGARCH, APARCH, TGARCH, NGARCH, AVGARCH, NAGARCH and component GARCH as method=, Student-t, skewed-t (Hansen and Fernández-Steel), GED and Johnson SU innovations with distribution=, constant, ARMA(1,1) and in-mean models with mean=, fit diagnostics (persistence, half-life, information criteria, classic and robust standard errors), standardized residuals, plus get_news_impact_curve, get_garch_simulation and the Garman-Klass Yang-Zhang volatility; log-likelihoods within 5e-7 of arch. (#603)
  • get_hurst_exponent gains the rescaled range (with the Anis-Lloyd-Peters correction) and detrended fluctuation analysis as method=, plus get_fractal_dimension (Higuchi, Katz, Petrosian), get_correlation_dimension and get_lyapunov_exponent (Rosenstein, Eckmann), referenced against nolds and antropy. (#607)
  • Microstructure: get_price_impact (Kyle's, Amihud's and Hasbrouck's lambdas as regression slopes per period, and the Roll impact), get_bekker_parkinson_volatility (from the Corwin-Schultz high-low pairs) and get_vpin (bulk volume classification over equal-volume buckets, a daily-bar approximation of the intraday measure), with volume and dollar bars as a model. (#611)
  • get_value_at_risk, get_conditional_value_at_risk, get_var_backtest and get_acerbi_szekely_test take method="garch": one-step VaR and ES from a GARCH-family fit (normal, t, skewed t, GED or Johnson SU innovations), on a moving window refitted every refit_every returns with rolling=; every refit reaches the multi-start maximum (a warm start from the previous weights falls back to the full multi-start when it touches a bound); within 1e-6 of arch. get_var_backtest(test=...) adds conditional coverage, the Christoffersen-Pelletier duration test (with Monte Carlo p-values, as in the paper), the McNeil-Frey bootstrap test and the tick loss, and takes a list or "all"; with more than one test, each p-value row is named after its test ("Kupiec P-Value", "Christoffersen P-Value"). (#612, #643)
  • get_volatility(method="compounded"): the annualized volatility of compounded returns, identical to backtesting.py. (#619)
  • get_higher_moment_coherent_risk (Krokhmal's coherent second moment and higher orders), get_expected_quadratic_shortfall (on losses) and get_conditional_expected_drawdown (Goldberg and Mahmoud); the drawdown table and statistics gain recovery ratios and returns, coverage and the state of an open drawdown. (#631)
  • The GARCH methods gain method="figarch" (FIGARCH(1,d,1), truncated at 1,000 lags as arch does, within 1e-10 of its likelihood), method="realized" (Realized GARCH of Hansen, Huang and Shek on the daily Parkinson variance) and mean="arfima"; get_garch_simulation(bootstrap_fits=) gives the Pascual-Romo-Ruiz bootstrap forecast density. (#632)

Ratios

  • Fundamental ratios of FMP's key metrics: operating cash flow, free cash flow, cash, tangible book value and Graham's net-net working capital per share, long-term debt to capitalization, debt to market cap, the solvency ratio, capex to operating cash flow, intangibles to total assets, operating return on assets, the continuing operations profit margin, and revenue and net income per employee. (#539)

Models

  • Fundamental models of the valuation, quality and distress literature: owner earnings, the Rule of 40, Damodaran's fundamental growth rate, the return on incremental invested capital, the unlevered beta, capitalized research and development, CFROI, Graham's criteria for the defensive investor, the Beneish M-score, the Shumway score, accrual quality and Francis et al.'s earnings attributes. The economic value added also returns the ROIC and the EVA spread. (#546)
  • Renamed: toolkit.ratios.get_reinvestment_rate is now get_retention_ratio (1 − payout ratio), as it is not Damodaran's reinvestment rate. (#546)
  • A company without interest expense and with a positive operating income gets the highest synthetic credit rating, where it had none. (#546)
  • Equal moves of a rate count as ties in the move significance when they differ only in their last bits. (#546)
  • get_implied_move shows the straddle's Bid-Ask Spread and how many of its legs are priced from a last trade (Last Trade Legs), and warns with the leg, its last trade date and open interest when the move rests on a last trade or a spread wider than half the straddle. (#684)
  • get_intrinsic_valuation shows the Present Value of Cash Flows and the Present Value of Terminal Value, which add up to the Enterprise Value, and get_reverse_discounted_cash_flow names the years behind its Historical Growth Rate in a Historical Growth Period column. (#677)
  • get_merton_model and get_merton_distance_to_default return the market value of debt and the Merton credit spread. (#610)

Fixed income, rates and options

  • get_loan_payment has a Change column, the payment relative to the first survey in the range, like get_affordable_loan. (#563)
  • get_outstanding_mortgage_rates adds the Market Rate (the quarterly average of Freddie Mac's 30-year fixed rate) and the Market Rate Gap, the market rate minus the average rate of outstanding mortgages, the lock-in measure of Batzer, Coste, Doerner and Seiler (2024) and Fonseca and Liu (2024). (#563)
  • get_skew_index says when no quotes are available (outside market hours) instead of returning empty values. (#563)
  • get_american_option with QD+ (Li), Barone-Adesi-Whaley and Ju-Zhong, the 1993 Bjerksund-Stensland approximation, American implied volatility (get_implied_volatility(american_option=True)) and discrete cash dividends on get_black_scholes_model (dividends='escrowed' or 'haug_haug_lewis', projected from the dividend history), within 1e-4 of QuantLib. (#602, #644, #649)
  • Swaps and forwards (fixedincome swaps topic): get_swap_rate (par and forward-starting swap rates with the annuity), get_forward_rate_agreement, get_asset_swap_spread, get_i_spread and get_fx_forward_rates on the EIOPA or government curve, plus swap values with PV01 and DV01, futures convexity adjustments (Ho-Lee, Hull-White) and equity forwards as models; the swaption annuity discounts on a curve when one is given. Within 1e-8 of QuantLib, rateslib and FinancePy. (#604)
  • Path-dependent options: get_lookback_option (fixed and floating strike, partial-time) and get_touch_option (one-touch, no-touch and double touches); get_asian_option gains Turnbull-Wakeman, Curran and Monte Carlo (with a geometric control variate) as method= and discrete fixings; get_barrier_option gains double, partial-time and soft barriers and the Broadie-Glasserman-Kou correction for daily, weekly or monthly monitoring. Within 1e-11 of QuantLib's closed forms, and checked by simulation where QuantLib's double-barrier, soft-barrier and partial-time engines fall short. The method and fixings arguments of get_asian_option follow put_option. (#606, #645)
  • Treasury market analytics: get_treasury_floating_rate_notes (discount margin, yield and index and spread durations under Treasury's FRN rules), get_treasury_inflation_protected_securities (reference CPI, index ratio, adjusted price, real yield and breakeven), get_treasury_forward_prices (forward price and yield financed at TGCR) and get_treasury_futures_basis (CME conversion factors, gross and net basis and implied repo of every deliverable, cheapest to deliver first, for ZT, ZF, ZN, TN, ZB and UB); get_treasury_securities fills the yield and duration of FRNs. Reproduces Treasury's published FRN and TIPS figures. (#608, #645)
  • Credit curves: get_survival_curve (survival probabilities and hazard rates by maturity bucket or rating from the ICE BofA option-adjusted spreads) and get_credit_default_swap_spread (the CDS-equivalent par spread per rating or maturity), with the CDS legs, RPV01, upfront and mark-to-market, the single-name CDS bootstrap and risky bond prices as models; the protection leg matches QuantLib's ISDA engine to 1e-12. (#610, #645)
  • Short-rate analytics: zero-coupon bond options, caplets and floorlets and Jamshidian swaptions under Vasicek, Hull-White, CIR and CIR++ (within 2e-9 of QuantLib), get_swaption_price (an expiry by tenor matrix from Hull-White or CIR++ fitted to the Treasury curve), the Feller ratio on get_short_rate_model, scheme="exact" on get_short_rate_simulation and puttable bonds on the Ho-Lee tree. (#613, #645)
  • Volatility smiles: get_volatility_surface(method="svi"|"ssvi"|"sabr") with show_parameters= (SABR from Hagan with Obłój's correction and the shifted variant, within 1e-16 of QuantLib; SSVI fitted jointly across expiries without butterfly arbitrage), the butterfly arbitrage check next to the calendar check, and get_local_volatility_surface (Dupire in total variance, within 1.4e-6 of QuantLib). The surfaces skip expiries less than a day away and the SVI surface also warns about butterfly arbitrage. (#614)
  • Compound-style exotics: chooser (simple and complex), compound (Geske, all four types), forward-start, cliquet and performance, extendible (holder and writer) and quanto options as models, with get_chooser_option and get_forward_start_option (a cliquet with periods=) on the ticker's data; within 1e-13 of QuantLib where its engines are exact and within 2e-9 of direct integration of the payoff elsewhere. (#617)
  • Curve construction: interpolation= on get_zero_coupon_curve, get_forward_rate and get_par_yield (linear on par yields by default, or linear on zero rates, log-linear, natural or monotone cubic and Hagan-West monotone convex, bootstrapped so every par bond reprices; within 2e-13 of QuantLib), maturities= on the zero curve, get_instantaneous_forward_curve, get_fitted_bond_curve (Svensson, Nelson-Siegel, Vasicek-Fong exponential splines or McCulloch cubic splines, fitted to Treasury prices with duration weights, with each bond's rich/cheap residual) and get_smith_wilson_curve (EIOPA's alpha rule, reproducing EIOPA's published curve). (#618, #621, #645)
  • Multi-asset options: get_exchange_option (Margrabe, European and American, against a second ticker or the benchmark) and get_spread_option (Bjerksund-Stensland 2011 or Kirk) from data, plus two-asset correlation, Stulz rainbow (best-of and worst-of) and basket options (Levy, Gentle and seeded Monte Carlo with a control variate) as models; within 1e-13 of QuantLib. (#624, #644)
  • Rate options and inflation: get_cap_floor (caps, floors and collars in Black, shifted Black or Bachelier), cap and Black/normal implied volatilities, swaption greeks with physical or cash settlement, year-on-year inflation caps and floors and CDS options as models; zero-coupon and year-on-year inflation swap rates, seasonality, the forward inflation index and swap values, with get_inflation_swap_rate (US and Germany, from nominal and real curves) and get_forward_inflation_index from data; within 1e-12 of QuantLib. (#626)
  • American options and trees: get_american_option(method="qd_fixed_point") (Andersen, Lake and Offengenden, within 1.6e-6 of QuantLib and a fine finite-difference grid), get_binomial_model(method=...) with the Jarrow-Rudd, Tian, Trigeorgis, Leisen-Reimer and exact inversion trees, get_cev_model (Cox, Schroder) and get_black_76_model for options on futures, with the Black-76 implied volatility as a model; within 1e-10 of QuantLib's engines. The QD fixed point is refused on the MCP server, where QD+ answers in its place. (#628, #644)
  • Rates risk and bond extensions: get_bucketed_delta (par-rate delta through the par-to-zero Jacobian, or forward-rate delta, per Treasury maturity) and get_rate_shift_ladder (P&L, delta and gamma for parallel shifts) on the Treasury curve, curve butterflies through get_yield_curve_spread(middle_maturity=), and as models amortizing and sinking-fund bonds (price, yield, durations, convexity, weighted average life; within 1e-10 of QuantLib) and a Tsiveriotis-Fernandes convertible bond. (#630, #644)
  • Short-rate trees (Hull-White 1994 two-stage trinomial tree on uneven steps, Black-Karasinski, Black-Derman-Toy and Ho-Lee) that reprice the curve exactly, with callable and puttable bonds, the American and European bond option and the Bermudan swaption as models (Hull-White within 1e-12 of QuantLib's tree engines); get_option_adjusted_spread takes model= and speed=, and get_swaption_price takes exercise="bermudan" (Hull-White, one tree for the grid). The model function short_rate_model.price_callable_bond, which priced on a Ho-Lee tree, is replaced by trinomial_tree_model.price_callable_bond (on a tree from build_short_rate_tree) and get_callable_bond_price. (#633, #644)
  • get_variance_swap gives the fair variance strike of each expiry from the option chain with the Demeterfi-Derman-Kamal-Zou replication weights (within 3e-17 of QuantLib's replicating engine), next to the Cboe variance of the same strip, and with a strike the realized variance and the swap's value; get_delta_hedging_backtest sells an option and delta hedges it on the ticker's own prices with transaction costs, and get_delta_hedging_simulation gives the distribution of the hedging error on simulated paths with the Derman-Kamal approximation. (#634)
  • Models for the G2++ two-factor model (bond, bond option and swaption by the one-dimensional integral; QuantLib's engine within 1.2e-12), the LIBOR market model (seeded forward simulation, caps and swaptions by Monte Carlo, Rebonato's swaption volatility; correlation takes a matrix and correlation_decay an exponential decay rate) and portfolio credit (Vasicek large homogeneous portfolio, the Andersen-Sidenius-Basu loss recursion for Gaussian and Student-t copulas, tranche expected loss and nth-to-default swaps). (#635, #644)
  • Numerical engines as models in a new options/numerical topic: a finite-difference θ-scheme on ln S (Crank-Nicolson with Rannacher steps; American exercise by Brennan-Schwartz or PSOR) for European, American, barrier (with rebates) and shout options, and Monte Carlo with antithetic and control variates, scrambled Sobol sequences with a Brownian bridge, correlated multi-asset and Heston (quadratic-exponential) paths, discretely monitored barriers and Longstaff-Schwartz for American and basket options. get_american_option(method="finite_difference") solves the whole strike and expiration grid at once, and get_monte_carlo_option_price takes american_option, variance_reduction and sequence. (#638, #645)
  • Stochastic volatility and jumps: one Fourier pricer (Lewis, COS or Carr-Madan FFT) for Heston (Albrecher's form), Bates, Merton jump diffusion and Variance Gamma as models, within 1e-13 of QuantLib's analytic engines; get_heston_parameters calibrates Heston to each ticker's out-of-the-money options across the term structure (the expiries nearest to 1 to 18 months) with the Feller ratio and the implied-volatility RMSE, and get_heston_nandi_model prices with the Heston-Nandi GARCH model fitted on the ticker's excess returns. (#639, #645)

Speed

  • GARCH fits use analytic gradients and a cache of fitted weights (2 to 7 times faster, within 1e-6 of arch as before); the Fama-MacBeth regression is solved for all dates at once; rolling sample entropy, the ADF lag search behind the unit root, Engle-Granger and pairs methods, the Lyapunov spectrum, the stationary bootstrap and the performance factor analysis are vectorised; bootstrap statistics and the forecast cone simulate in chunks of 1,000, so memory stays bounded (20,000 simulations: 2.4 GB → 0.3 GB). (#646)
  • Option grids are priced on arrays: barrier, Bjerksund-Stensland (with a bivariate normal on arrays), put-call parity, chooser, lookback, geometric Asian, Garman-Kohlhagen, binary, Barone-Adesi-Whaley, Ju-Zhong, QD+, the binomial tree and the Monte Carlo price, identical to 1e-10 (a 51 × 365 barrier grid: 37 s → 0.08 s); define_strike_prices caps strikes × expirations at 10,000,000 values. (#648)

Fixes

  • The Augmented Dickey-Fuller and Engle-Granger tests work with statsmodels 0.15, which moved the MacKinnon p-values and critical values to statsmodels.tsa.adfvalues. (#660)
  • get_merton_distance_to_default converts the Treasury yield from its semi-annual quote to continuous compounding before the model discounts with it, as the option methods do. (#645)
  • Performance: get_sterling_ratio divides by the average of the largest drawdowns (largest_drawdowns=3) plus 10%, as Bacon defines it, instead of the average drawdown over all days below the peak; get_ljung_box_test and the R/S and DFA Hurst exponents of a constant series give NaN instead of a rejection or a spurious value. (#643)
  • Portfolio: market-neutral (net_exposure=0) minimum-risk portfolios return their zero weights instead of an error; Black-Litterman, Brinson, sector and country bounds and look-through say an API key is needed for company profiles; risk budgets name unknown and missing tickers. (#593)
  • Econometrics: get_cusum_test of a constant series and Breusch-Pagan, White and Durbin-Watson on a perfect fit give NaN instead of a rejection on rounding noise; the drawdown of get_level_significance is dated from the last date at its peak; the Wald and F tests report the degrees of freedom they use. (#595)
  • Quarterly revenue and net income per employee use the count of the year a December quarter ends in, also for years ending before 26 December; the option chains' Percent Change is a decimal; get_factor_analysis with fewer tickers than quantiles says so. (#596)
  • Employee counts of a 52/53-week year ending in the first week of January (2 January 2021) belong to the year before, in get_employee_count and in the figures per employee, so that year's statements no longer take the next year's count, and the first year of quarters after the start date gets its count (collected from the year before); the CUSUM test of a series constant up to rounding and the volume profile of a close constant up to rounding no longer fail; the dynamic RSI needs a full window of real changes after a gap. (#599, #600)
  • get_srisk with a rolling window longer than the data returns an empty result instead of an error. (#594)
  • get_srisk, get_marginal_expected_shortfall, get_covar and get_tail_dependence_coefficient work with the benchmark or any other ticker as market_ticker; a market given by its ticker raised an error. (#563)
  • Everything from Yahoo Finance (prices, statements, company and instrument information, option chains, dividends, futures curves and the ISIN lookup) goes through yfinance in one module, financetoolkit.yfinance_model, so a rate limit, an unreachable Yahoo or a locked yfinance cache is handled the same way everywhere. convert_isin_to_ticker moved there from utilities.requests_model, and economics.sources.yfinance_model is folded into it. A Portfolio's Portfolio column is no longer requested for its historical statistics. (#673)
  • Option chains come from Yahoo Finance only: Cboe blocks automated access to its delayed option quotes, so its chain is no longer requested. Cboe's index prices (the VIX term structure) are unchanged. (#573)
  • Option chains, implied volatility, the volatility surface and the risk-neutral density use each ticker's own expiration dates: a ticker without the requested date is left out with a note listing its dates, chains carry an Expiration Date column and show_expiration_dates=True gives a list per ticker when there are several. (#577)
  • The CIR curve stays defined at high speeds of mean reversion; a drawdown that ends exactly at its old high counts as recovered; tail dependence is NaN for a constant series; autocorrelation is NaN at lags without pairs; compare_with_peers cleans the peer tickers. (#578)
  • The bond universe reads only holdings with a published ISIN (an ISIN built from a CUSIP says nothing about the currency, so funds whose feeds give none are left out with a note), prices a bond held by several funds at the median of their prices, and measures each G-Spread on the Treasury curve of the bond's own price date. (#579)
  • The Portfolio class handles two foreign-currency trades on one date, converts a holding on a day its exchange is closed at that day's rate, restates purchases from before a split, keeps a benchmark asked for by argument, starts over when the transactions are read again and orders a day's trades by their time when the file has one; portfolio.toolkit holds the Portfolio's own return series, used for its risk metrics and technical indicators. (#581)
  • In portfolio.toolkit the Portfolio's performance measures (Sharpe, Sortino, Treynor, alphas and betas, capture and drawdown ratios and the rest) are calculated on its own daily return series instead of averaging those of its holdings, and the regressions leave the Portfolio out of a holding's default independent tickers. (#584)
  • With a net exposure other than one, the optimizers hold the rest as a Cash row at the risk free rate, so the Portfolio's return and Sharpe ratio are those that were optimized (also in the minimum tracking error weights, which take risk_free_rate); a transaction cost shows as a column and comes off the Portfolio's return; the backtest holds nothing until an optimizer first finds weights within its bounds and runs to the end date; daily returns of markets that trade every day are annualized with 365 days. (#583)
  • Econometrics: one ticker that can't be fitted (such as a constant price) is left out with a warning instead of emptying get_structural_breaks, get_markov_regime_switching and get_time_varying_beta for every ticker; get_f_test and get_likelihood_ratio_test fit both models on the same dates when a regressor has gaps; get_pairs_trading shows no signal or trades where it has no z-score instead of zero; get_fixed_effects works without arguments, with the benchmark as regressor. (#661)
  • Performance, risk and portfolio: an unknown period in the Performance methods raises instead of returning empty; a zero-volatility asset gives a NaN Sharpe ratio in the weight tables and the optimization backtest instead of −inf; the rolling beta and appraisal ratio are NaN where the window has no variance or residual degrees of freedom instead of ±inf; get_return_statistics returns empty for a range without data instead of raising; the default equal weights of the portfolio methods no longer log that they are scaled to one; get_acerbi_szekely_test and the collections stop repeating warnings. (#662)
  • Options and fixed income: get_stock_price_simulation with a time to expiration of zero or less raises instead of never returning; collect_all_greeks and the other collections return empty with one message when no greek can be calculated instead of a TypeError; get_lambda is NaN where the option is worth nothing instead of inf; the Black-Scholes family rejects negative prices, volatilities and times; the Bjerksund-Stensland approximation (get_american_option(method="bjerksund_stensland")) warns that it undervalues American options at negative rates; the loan methods reject terms of zero or less; an unreachable FRED, ECB or New York Fed says so instead of raising; get_years_to_maturity and get_accrued_interest raise for a bond settled on or after maturity instead of NaN. (#663)
  • Ratios and models: a missing line item makes the PEG ratio, shareholder yield, tax rate divergence, market cap to GDP, the valuation collections and get_intrinsic_valuation return empty with the missing input named, instead of an AttributeError or TypeError; zero shares outstanding or zero revenue give NaN instead of inf in the intrinsic valuation, earnings power value, PVGO, Monte Carlo valuation and DuPont analysis, and no longer empty the other tickers; statements passed to the Toolkit keep the periods before the start date that the ratios need, as downloaded statements do; a missing diluted share count falls back to the basic one with a warning; an unreachable Global Macro Database says so instead of raising; lag below 1 raises. (#664)
  • Economics, discovery and ETFs: an unknown option or period in the economics methods (a level, measure, period the source doesn't publish) raises instead of returning empty; an unreachable or malformed answer from the OECD, BIS, Bank of England, DNB, FHFA, BLS, Bank of Japan or Yahoo Finance says so instead of raising a raw request, zip or JSON error; FMP errors (rate limit, plan, invalid key, server errors) are reported once instead of appearing as a column; the sector, industry and earnings calendars stop at the first failed request instead of trying every day; get_return_excluding skips funds without holdings instead of failing; the discovery sector and industry methods default to the last trading day with data. (#666)
  • Windows and short histories: get_acerbi_szekely_test is NaN instead of -inf where the expected shortfall of a window is 0; the VaR backtests reject a window of 0 instead of using the default and warn when no observation falls in the tail; a rolling window as long as the returns, or too short for the measure (skewness 3, kurtosis 4, the appraisal ratio 3, the Hurst exponent), warns or raises instead of returning NaN without a word; trailing below 1 or not a whole number raises in the ratios and models (2.5 gave a TypeError); the commodity channel and choppiness indexes reject a window of 1; technical indicators and collections say once which indicators have no values and why; a ticker without prices is named instead of turning the marginal VaR into NaN; fewer than three daily observations are reported. (#667)
  • Unreachable and partial sources: when some ICE BofA, HQM or Moody's series fail, the others are kept instead of the whole result failing; a FRED answer that is not JSON and an unreadable Global Macro Database file return empty with a message instead of raising; a source that is down is not asked again for every series within one call (the implied volatility went from 62 requests to 10); get_market_risk_premium reports an FMP error instead of returning it as a column; get_industry_statistics reports an error page instead of raising; get_lambda is NaN wherever it is not finite; get_stock_price_simulation rejects more than 1,000 time steps once instead of once per ticker; numpy integers are accepted where a whole number is asked. (#668)
  • FRED's own message (such as an unregistered API key) is shown instead of a general request error; the stock and crypto news stop paging when FMP fails instead of retrying every page; get_carbon_price gives one line naming the missing years and why (unreachable, refused, not published) instead of one per year; a period that is not a string raises an InvalidArgumentError. (#669, #671)
  • get_income_statement and get_cash_flow_statement reject a trailing window below 1 or not a whole number instead of raising a bare ValueError, and warn when it is longer than the statements. (#670)
  • The slow EGARCH recorder test has a timeout of its own, so a slow run is a failure again instead of an expected one. (#615)

References

  • The docstrings credit the papers, books and libraries behind every measure: they cite the originator of each formula, say where a library defined a measure (with its authors) and refer to the libraries the results are checked against as references ("Referenced against TA-Lib's RSI", "shares similar logic as"). About 30 literature references are corrected (titles, years, volumes and pages), two pointed to papers that don't exist, and about 50 methods that only named a library now also cite their originator. (#560, #561)
  • The README's counts are up to date, and docstrings say a result "agrees with" a library's where the values match. (#575)
  • Every docstring has "Referenced against:" and "Shares similar logic:" sections listing the library function and a link to its page (or the pinned source line); controllers carry the lines of the models they use. First sentences say what each measure shows, variants are named in words and every option is listed under Args. (#653, #654, #656, #659)
  • The methods from López de Prado's books cite the books by section and snippet, and every reference to another library was checked against that library's licence: the code is written from the formulas, the libraries are references. (#627)

Dependencies

  • CI uses astral-sh/setup-uv 10.4.0 and the Docker image uv 0.13.10. (#686)

MCP server

  • The tool list is less than a third of its size (573,000 → 184,000 characters) and answers are tables of columns and rows, sent once as text instead of twice, which halves what a typical answer costs. Each indicator's full parameter reference moves to search_metrics with its name, and a descriptive search gives every hit as a ready call line (get_alpha(method='standard'|'jensen'|..., ...)), with searches such as "golden cross", "Jensen's alpha", "2s10s" and "FCF yield" finding the direct indicator first. (#676)
  • indicator takes up to five indicators of one tool in one call, each answered under its own name as if called alone. show_columns, signals_only and sample apply where they were ignored (index constituents, the signal a column names, any answer finer than the sample), growth rates are not read once a year unless they are year over year, notes stay with the data they concern, and the tracking error and GARCH forecast state their units. (#678)
  • With usage statistics on, the server counts how each indicator of a call ends (data, cut to size, empty, invalid or error) per tool and indicator, without arguments or other user input; /stats shows the totals per outcome. (#679)
  • An indicator asked of a tool that doesn't have it is answered by the tool that does (get_interest_coverage_ratio on solvency is answered by profitability, with a note), where it was read as the closest name in the asked tool, often another measure (the cash interest coverage ratio, or nominal for real GDP). Only a misspelling is still read as the known name, and the suggestions for an unknown indicator include close names of other tools. (#675)
  • The HTTP server runs without sessions: every request stands on its own, so a conversation that resumes after a pause, or a client that sends a call without its session header, is no longer refused with "Session not found" or "Missing session ID". An address pasted with a trailing space, dot or line break (/mcp .) reaches the server instead of a 404. (#674)
  • Passing ticker=, symbol= or symbols= instead of tickers= says so and names the indicator, and a missing column in an answer says which one instead of "Invalid input". (#666)
  • search_metrics with an indicator's name answers with its whole description: what it shows, the explanation and the formula, without the references and parameters. (#656)
  • sample='weekly'|'monthly'|'quarterly'|'yearly' on every tool keeps the last row of each period of a daily answer, so a daily indicator such as the 200-day moving average can be read weekly (52 rows a year instead of 252); it combines with limit. (#651)
  • Limits follow measured timings: option grids at 750,000 values per call; product limits can apply to one method or argument value, divide by a parameter and use the requested date range or number of tickers, and lists can have a maximum length; new limits on GARCH refits over long ranges, bubble-test simulations, Markov regimes (3), ARIMA orders, the forecast cone, estimation uncertainty and the Heston calibration's expirations (12). (#648)
  • The Docker image runs OpenBLAS, OpenMP and MKL on one thread each, which on the server's two cores makes the statsmodels-based methods several times faster (a unit root test 6.6 s → 0.3 s). (#646)
  • A self-hosted server on the sse or streamable-http transport with FINANCIAL_MODELING_PREP_API_KEY set no longer lets callers in without credentials; letting them use the server's key takes FT_MCP_ALLOW_ANONYMOUS=1 as well, and the server logs a warning when that is set. (#642)
  • rebase_to= on every tool indexes a time series to 100 = its average over a base period, a year, month, day or range such as '1340-1347'; the base uses every fetched row, before limit, show_columns and rank. (#562)
  • On the MCP server get_garch(method="egarch") is refused with a pointer to "gjr" or "garch", as EGARCH was before. (#589)
  • series= references take indicator arguments as :name=value, e.g. series='rates:get_outstanding_mortgage_rates:United States:Below 4%:cumulative=true'. (#563)
  • The arguments of a series= reference are held to the same limits as a direct call (refused values such as method='egarch', simulation and forecast sizes), accept only the indicator's own parameters and report the indicator's error when it can't be calculated; rebase_to leaves a column with a non-positive base empty with a note; the shared method parameter lists the values of every indicator; search_by_category shows tools, indicators and metrics; the total counts every method once and leaves out refused variants and estimator choices: the method of get_covariance_estimate, get_coskewness_matrix and get_cokurtosis_matrix is a plain string again. (#597)
  • Answers keep the ticker order of each request (econometrics takes the first ticker as dependent), a series that is also the benchmark is kept, one-ticker series are named after their ticker, holdings adds up repeated tickers, rank with a single ticker is skipped instead of ranking its fields, and the descriptions tell the two Cumulative Returns and Win Rates apart. (#577)
  • search_metric_categories counts the tools, indicators and metrics of every category and in total, where every formula variant (method=) is a metric of its own, and the README, the server and the bundle state that total, rounded down to the hundred (1100+). (#580, #587, #588, #603, #619)
  • parameter_limits.minimums keeps refit_every at 21 or more, and refused values are checked inside lists; the slow GARCH variants (and component GARCH, whose refits sit on a bound) are refused for the GARCH VaR and the model confidence set. (#612)
  • The valuation and market_data descriptions say which shares the two market caps rest on: get_market_cap the weighted average diluted shares of the latest fiscal period, get_quote the current shares outstanding. (#629)