Repository navigation
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_egarchand their_forecastand_parametersmethods →get_garch,get_garch_forecastandget_garch_parameterswithmethod="gjr"or"egarch". (#589) -
get_edge_spread,get_corwin_schultz_spreadandget_abdi_ranaldo_spread→get_bid_ask_spread(method="edge" | "corwin_schultz" | "abdi_ranaldo"). (#589) -
get_minimum_cvar_weights,get_maximum_cvar_ratio_weightsandget_minimum_drawdown_weights→get_mean_risk_weightswithrisk_measure="cvar","cdar","maximum_drawdown"or"average_drawdown"(andobjective="maximum_ratio"), with the same weights and one extra<measure> Ratiocolumn. (#589) -
get_augmented_dickey_fuller,get_phillips_perron_testandget_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_testandget_white_test→get_heteroskedasticity_test(method="breusch_pagan" | "white");get_logistic_regressionandget_probit_regression→get_binary_choice_regression(method="logit" | "probit");get_rmseandget_mae→get_forecast_error(method="rmse" | "mae"). (#641) -
get_treynor_mazuy_modelandget_henriksson_merton_model→get_market_timing_model(method="treynor_mazuy" | "henriksson_merton"). (#647) -
Duplicates removed:
get_net_income_per_ebt(useget_tax_burden_ratio),get_EBT_to_EBIT(useget_interest_burden_ratio) andget_EBIT_to_revenue(useget_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")andget_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_averagetakes 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 throughmethod=. (#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_deviationandget_rolling_conditional_drawdown_at_risk(risk),get_rolling_var_historicandget_rolling_cvar_historic, and the 18get_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 withoutrollingin its name withwindow=N, with identical values. (#658) -
risk.get_move_significance→econometrics.get_move_significance, which gives the same values for the Toolkit's tickers (withinclude_benchmark=Truefor the benchmark). (#658)
Renamed parameters
One name per meaning across the package. The old names are removed:
distribution→methodinget_value_at_risk,get_conditional_value_at_risk,get_marginal_value_at_risk,get_component_value_at_risk,get_var_backtestandget_acerbi_szekely_test;window_size→windowinget_var_backtest,get_acerbi_szekely_testandget_diebold_mariano_test;random_state→seed(default 0 instead of 42) inget_acerbi_szekely_testandget_copula_simulation, whosen_simulations→simulations. (#650)time_steps→forecast_stepsinget_garch_forecast;maxlags→lagsinget_olsandget_wls;k_ar_diff→lagsinget_johansen_cointegrationandget_vecm_forecast;include_constant→add_constantinget_arima_forecast;rolling→windowinget_ulcer_index;threshold→minimum_acceptable_returninget_safety_first_ratio. (#650)confidence_level(0.95) →alpha(0.05) inget_risk_contributionsandget_portfolio_risk_metrics;svensson→method="svensson"|"nelson_siegel"inget_nelson_siegel_svensson;duration_type→methodinget_duration;model→methodinget_altman_z_score;paths→simulationsinget_short_rate_simulation;timesteps→time_stepsinget_binomial_modelandget_stock_price_simulation;atr_multiplier→multiplieringet_keltner_channels;get_monte_carlo_option_pricedefaults toseed=0, so repeated calls give the same price. (#652)window→rollinginget_style_analysisandget_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
InvalidArgumentErrorthat 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. Arolling,trailingorlaglonger 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 withmoving_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_patternscovers 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_patternscovers 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_patternscovers 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_patternscovers 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_featuresgives 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"incollect_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 throughside=),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_uniquenessandget_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")) andget_guppy_multiple_moving_averageswith 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
statisticstopic, 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 Econometricsperiodandinclude_benchmarkoptions. (#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_entropywith 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_complexityandget_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) andget_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")withtime_series=for the Chu-Stinchcombe-White statistic per date,weighted=Trueonget_ljung_box_testandget_arch_lm_test(Fisher and Gallagher),get_sign_bias_test(Engle and Ng) andget_pearson_goodness_of_fit_test(Palm) on GARCH residuals,get_change_points(PELT for the mean, the variance or both) andget_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) andget_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_peersorfinancetoolkit.options.get_variance_swap_terms, so they can be used and tested on their own. (#680, #681) - Technicals:
breadth,momentum,overlap,volatility,pattern,seasonalityandcycle, e.g.from financetoolkit.technicals.momentum import momentum_model. The module pathsfinancetoolkit.technicals.<name>_modelare removed. (#531) - Model functions are importable from their package, e.g.
from financetoolkit.models import get_altman_z_scoreorfrom 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_ratioandget_sales_to_total_assets_ratioinaltman_model;get_net_income_to_total_assets_ratioandget_total_liabilities_to_total_assets_ratioinohlson_model;get_ebit_to_total_assets_ratioingrover_model;get_current_liabilities_to_total_assets_ratioinfulmer_model) and the copies in the other model modules are removed,ratios.efficiency_model.get_operating_marginis removed (useprofitability_model.get_operating_margin) andconstraints_model.get_log_of_total_assetsis renamedget_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_analysisin ratios, models, technicals, performance and risk) gainsgroup=(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, anddetail=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) andget_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_testagainst 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_matrixandget_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_weightsminimizes a risk measure or maximizes the return per unit of it, andget_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_weightsgives the exact corner portfolios of the bounded frontier (Markowitz, 1956), referenced against PyPortfolioOpt's CLA;get_worst_case_mean_variance_weightsoptimizes 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; andget_distributionally_robust_cvar_weightsminimizes 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 HERCwithin_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_weightsmoves between HRP and minimum variance (Cotton, 2024) andget_stacking_weightscombines 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 andget_asset_clusters, referenced against Riskfolio-Lib's DBHTs. (#582)- Using
portfolio.toolkitno longer adds the benchmark to the Portfolio's own data, which made the portfolio overview fail afterwards. (#557) get_trades,get_trade_statisticsandget_position_timingon 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_angularandgnprcodependence; ONC clustering (get_asset_clusters(method="onc")andcluster_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_forecastandget_garch_parameters: IGARCH, APARCH, TGARCH, NGARCH, AVGARCH, NAGARCH and component GARCH asmethod=, Student-t, skewed-t (Hansen and Fernández-Steel), GED and Johnson SU innovations withdistribution=, constant, ARMA(1,1) and in-mean models withmean=, fit diagnostics (persistence, half-life, information criteria, classic and robust standard errors), standardized residuals, plusget_news_impact_curve,get_garch_simulationand the Garman-Klass Yang-Zhang volatility; log-likelihoods within 5e-7 ofarch. (#603) get_hurst_exponentgains the rescaled range (with the Anis-Lloyd-Peters correction) and detrended fluctuation analysis asmethod=, plusget_fractal_dimension(Higuchi, Katz, Petrosian),get_correlation_dimensionandget_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) andget_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_backtestandget_acerbi_szekely_testtakemethod="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 everyrefit_everyreturns withrolling=; 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) andget_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 asarchdoes, within 1e-10 of its likelihood),method="realized"(Realized GARCH of Hansen, Huang and Shek on the daily Parkinson variance) andmean="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_rateis nowget_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_moveshows 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_valuationshows the Present Value of Cash Flows and the Present Value of Terminal Value, which add up to the Enterprise Value, andget_reverse_discounted_cash_flownames the years behind its Historical Growth Rate in a Historical Growth Period column. (#677)get_merton_modelandget_merton_distance_to_defaultreturn the market value of debt and the Merton credit spread. (#610)
Fixed income, rates and options
get_loan_paymenthas a Change column, the payment relative to the first survey in the range, likeget_affordable_loan. (#563)get_outstanding_mortgage_ratesadds 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_indexsays when no quotes are available (outside market hours) instead of returning empty values. (#563)get_american_optionwith 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 onget_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 (
fixedincomeswaps topic):get_swap_rate(par and forward-starting swap rates with the annuity),get_forward_rate_agreement,get_asset_swap_spread,get_i_spreadandget_fx_forward_rateson 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) andget_touch_option(one-touch, no-touch and double touches);get_asian_optiongains Turnbull-Wakeman, Curran and Monte Carlo (with a geometric control variate) asmethod=and discrete fixings;get_barrier_optiongains 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. Themethodandfixingsarguments ofget_asian_optionfollowput_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) andget_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_securitiesfills 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) andget_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 onget_short_rate_model,scheme="exact"onget_short_rate_simulationand puttable bonds on the Ho-Lee tree. (#613, #645) - Volatility smiles:
get_volatility_surface(method="svi"|"ssvi"|"sabr")withshow_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, andget_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_optionandget_forward_start_option(a cliquet withperiods=) 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=onget_zero_coupon_curve,get_forward_rateandget_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) andget_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) andget_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, withget_inflation_swap_rate(US and Germany, from nominal and real curves) andget_forward_inflation_indexfrom 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) andget_black_76_modelfor 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) andget_rate_shift_ladder(P&L, delta and gamma for parallel shifts) on the Treasury curve, curve butterflies throughget_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_spreadtakesmodel=andspeed=, andget_swaption_pricetakesexercise="bermudan"(Hull-White, one tree for the grid). The model functionshort_rate_model.price_callable_bond, which priced on a Ho-Lee tree, is replaced bytrinomial_tree_model.price_callable_bond(on a tree frombuild_short_rate_tree) andget_callable_bond_price. (#633, #644) get_variance_swapgives 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_backtestsells an option and delta hedges it on the ticker's own prices with transaction costs, andget_delta_hedging_simulationgives 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;
correlationtakes a matrix andcorrelation_decayan 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/numericaltopic: 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, andget_monte_carlo_option_pricetakesamerican_option,variance_reductionandsequence. (#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_parameterscalibrates 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, andget_heston_nandi_modelprices 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
archas 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_pricescaps 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_defaultconverts 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_ratiodivides 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_testand 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_testof 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 ofget_level_significanceis 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_analysiswith 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_countand 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_sriskwith a rolling window longer than the data returns an empty result instead of an error. (#594)get_srisk,get_marginal_expected_shortfall,get_covarandget_tail_dependence_coefficientwork with the benchmark or any other ticker asmarket_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_tickermoved there fromutilities.requests_model, andeconomics.sources.yfinance_modelis folded into it. A Portfolio'sPortfoliocolumn 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=Truegives 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_peerscleans 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.toolkitholds the Portfolio's own return series, used for its risk metrics and technical indicators. (#581) - In
portfolio.toolkitthe 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_switchingandget_time_varying_betafor every ticker;get_f_testandget_likelihood_ratio_testfit both models on the same dates when a regressor has gaps;get_pairs_tradingshows no signal or trades where it has no z-score instead of zero;get_fixed_effectsworks without arguments, with the benchmark as regressor. (#661) - Performance, risk and portfolio: an unknown
periodin 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_statisticsreturns 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_testand the collections stop repeating warnings. (#662) - Options and fixed income:
get_stock_price_simulationwith a time to expiration of zero or less raises instead of never returning;collect_all_greeksand the other collections return empty with one message when no greek can be calculated instead of a TypeError;get_lambdais 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_maturityandget_accrued_interestraise 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_valuationreturn 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;lagbelow 1 raises. (#664) - Economics, discovery and ETFs: an unknown option or period in the economics methods (a
level,measure,periodthe 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_excludingskips 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_testis 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; arollingwindow 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;trailingbelow 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_premiumreports an FMP error instead of returning it as a column;get_industry_statisticsreports an error page instead of raising;get_lambdais NaN wherever it is not finite;get_stock_price_simulationrejects 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_pricegives one line naming the missing years and why (unreachable, refused, not published) instead of one per year; aperiodthat is not a string raises anInvalidArgumentError. (#669, #671) get_income_statementandget_cash_flow_statementreject atrailingwindow 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-uv10.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
columnsandrows, sent once as text instead of twice, which halves what a typical answer costs. Each indicator's full parameter reference moves tosearch_metricswith 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) indicatortakes up to five indicators of one tool in one call, each answered under its own name as if called alone.show_columns,signals_onlyandsampleapply 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;
/statsshows 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_ratioonsolvencyis answered byprofitability, 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=orsymbols=instead oftickers=says so and names the indicator, and a missing column in an answer says which one instead of "Invalid input". (#666) search_metricswith 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 withlimit. (#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_KEYset no longer lets callers in without credentials; letting them use the server's key takesFT_MCP_ALLOW_ANONYMOUS=1as 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, beforelimit,show_columnsandrank. (#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 asmethod='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_toleaves a column with a non-positive base empty with a note; the sharedmethodparameter lists the values of every indicator;search_by_categoryshows tools, indicators and metrics; the total counts every method once and leaves out refused variants and estimator choices: themethodofget_covariance_estimate,get_coskewness_matrixandget_cokurtosis_matrixis a plain string again. (#597) - Answers keep the ticker order of each request (econometrics takes the first ticker as dependent), a
seriesthat is also the benchmark is kept, one-ticker series are named after their ticker,holdingsadds up repeated tickers,rankwith 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_categoriescounts 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.minimumskeepsrefit_everyat 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)