Every Finance Toolkit release, newest first, with the notes from its GitHub release. Upgrade with pip install -U financetoolkit.

v2.3.4

14 November 2026

A release on macro data and on judging how unusual a move is. Producer prices by country come from current official sources, with new export and import price indices; the economic calendar reads as a time series; any series can be ranked against its own history, as a level, a spread or a streak; a stock's market-adjusted move gets its size in money and its rank; a basket's market value compares with a country's GDP. Real interest rates, core CPI and commodity prices since 1960 come by month, a basket of stocks gets its own summed statements, and every MCP answer names the publishers its data comes from. Cached data gives the same answers as fresh data, and the MCP server logs every request again.

Package

All modules

  • Every get_, collect_ and search_ method takes show_columns=, a name or a list of names, e.g. economics.get_shiller_stock_market_data(show_columns=["Price", "CAPE"]). A column level left with a single name is dropped, so the Close of several tickers has the tickers as columns; get_historical_data with one ticker and one column returns a DataFrame (#431).

Economics

  • get_producer_price_index comes from the official publishers without an API key: Eurostat for the euro area, the EU and around 35 European countries, the BLS for the United States (FRED with a key for the full history) and the Bank of Japan's corporate goods price index. The OECD dataset it used stopped in 2022. China has no reachable index and is left out with a note; its monthly year-on-year change is in the economic calendar (#405).
  • get_export_price_index and get_import_price_index from the same publishers (#405).
  • get_economic_calendar(as_series=True) returns each event's actual value (and the consensus estimate) by the period it covers, read from the event text, one column per event (#404).
  • Removed: the model function oecd_model.get_producer_price_index (#405).
  • get_chokepoint_transits: IMF PortWatch's daily ship transits through 28 maritime chokepoints from 2019 (the Strait of Hormuz, Suez, Bab el-Mandeb, Panama, Malacca and more), by ship category, as counts or estimated trade volume in metric tons, summed by week, month, quarter or year (#432).
  • get_commodity_prices: the World Bank Pink Sheet, monthly from 1960 (energy, metals including gold, agriculture, fertilizers), with deflate_with= for prices in today's money (#413).
  • get_consumer_price_index(measure=...) and get_inflation_rate(measure=...): core, energy, food, goods, services and shelter (BLS for the United States, Eurostat HICP aggregates for Europe). The US CPI includes the months the BLS released since the BIS last republished it (#415).
  • get_real_interest_rate is monthly by default (period="yearly" for the annual calculation) and takes rate_type="policy", which covers the euro area (#414).
  • The policy rates add the days since the BIS's weekly update from the Bank of England and the ECB, and get_european_central_bank_rates takes period= (#414).
  • get_government_interest_expenditure (with ratios to GDP and to revenue) and get_government_expenditure_by_function (COFOG, with a ratio to GDP), from the IMF (#407).
  • get_purchasing_power, with overnight_rate=True for the real value of cash; get_consumer_price_index(cumulative=True) and get_overnight_rate(cumulative=True) (#408).
  • Monthly, quarterly and yearly data shows a period a source skipped as an empty row, so a change never compares the wrong periods; annual changes compare the same period a year earlier (#413, #417).
  • The economic calendar series keep a release that covers two months (China's January and February trade) once, under the later month, and leave out releases without a period (#417).
  • Removed: fred_model.get_real_yield_curve and fred_model.get_breakeven_inflation_expectations; the US real yields and breakevens come from the Treasury (#414).

Econometrics

  • get_level_significance: the latest value of any series (a rate, a macro series or a close) with its percentile over the history and the last date it was as high or as low (#402).
  • get_streaks: the current run of positive or negative values of a series, its start and length, the run before it and the longest earlier run of the same sign (#404).
  • spread_over= ranks or counts one series minus another, such as producer minus consumer prices (#404).
  • get_level_significance adds the change since the start, the highest and lowest of the range, the first date above a level=, the annualised change, the largest drawdown with its recovery date, and the rank of the latest value (#409, #410, #413, #416, #417).
  • get_window_change_by_year: the change over the same months every year, ranked (#415).
  • get_streaks(level=...) counts runs above or below a level, and ratio=True divides by the spread_over series instead of subtracting it (#416).
  • With changes="difference", the changes of get_level_significance and get_window_change_by_year are in points, such as the change of a yield over a month (#419).
  • zone=True on the Altman, Zmijewski, Springate and Taffler scores adds the Distress / Grey / Safe zone of each score (#420).
  • get_optimization_backtest shows the return and Sharpe ratio each strategy expected in sample next to what it realised (#420).
  • get_issuer_spreads compares issuers' spreads at the same maturities (2Y, 5Y, 10Y, ...) by interpolating along each issuer's bonds (#420).
  • get_yield_decomposition splits the nominal yield of the United States, United Kingdom and Germany into the real yield and breakeven inflation, with the daily change of each part (#422).
  • Econometrics.get_move_significance measures how unusual each change of any series is, e.g. the largest one-day rise of a yield since a date (#422).
  • get_initial_jobless_claims without a FRED key retries when the Department of Labor's report cannot reach its database, which happens for up to half of the requests, and otherwise serves the cached claims instead of failing (#434).
  • The yearly consumer price index and inflation rate warn about years the Global Macro Database repeats from the year before (inflation 0 by construction, e.g. Germany 1913-1914) and about hyperinflations, after which the yearly average still rises sharply (Germany 1924: +723%) (#435).
  • The per-ticker earnings and dividend calendars keep the scheduled dates after today (the next earnings release); price targets FMP lists under another analyst company than the article names are credited to the named company, and get_price_target_history adds each company's Previous Target, Previous Date and Target Change (#437).
  • The US inflation rate and CPI are the CPI-U for every date range; a range ending before 2025 returned Eurostat's experimental HICP-concept US figures (#422).
  • Returns of currency pairs, cryptocurrencies and low-priced shares from FinancialModelingPrep use an unrounded adjusted close; FMP's is rounded to two decimals (#423).
  • get_millennium_of_macroeconomic_data(deflate_with=...) puts the long-run series in real terms, e.g. the oil price since 1861 in today's dollars (#424).
  • get_weighted_average_cost_of_capital accepts single numbers as well as series (#425, @pengpengyi92).
  • The Merton model leaves a non-positive or non-finite horizon empty instead of solving it (#426, @pengpengyi92).
  • The daily present value of growth opportunities keeps figures dated on non-trading days (#427, @pengpengyi92).
  • The estimated EPS growth rate is empty for invalid single inputs, such as a zero trailing EPS (#428, @pengpengyi92).
  • As-of lookups of the credit models sort histories that are not in date order (#429, @pengpengyi92).

Performance

  • get_beta_implied_return adds the Residual Value (the residual times the market cap at the previous close), the Residual Percentile and the Residual Largest Since date, so one row judges the latest stock-specific move against its history (#401).

Bonds and rates

  • get_taylor_price_change(from_date=...) gives each Treasury's own yield change between two dates, the duration and convexity estimate and the realised price change from the FedInvest prices (#402).
  • get_treasury_rates takes maturities= (#402).
  • get_loan_payment, get_affordable_loan and get_amortization_schedule at the 30-year mortgage rate, or any rate (#409).

Data

  • Futures tickers (BZ=F, CL=F, NG=F and others) return quotes and intraday data, and TTF=F its daily history again (#410).
  • Cached financial statements keep every period that overlaps the requested range, the same as a fresh request. Before, a warm cache could drop the year before the start date that the statements are fetched with, so factor analyses and other measures that need that year could differ between a first and a later call (#398).

Discovery

  • With primary_only=True, the earnings calendar chooses primary listings from the releases of a week either side of the range. A company that reported just before the range, while its listings abroad dated the same release inside it, no longer shows with a listing abroad as its primary one (#398).

Data sources

  • Every data source is checked weekly, FinancialModelingPrep (every endpoint, through the public methods) and FRED included, and a failing source opens an issue (#434).

Documentation

  • Docstrings across the package: Args match the signatures and their defaults, mentions that no API key is needed are gone, and errors are fixed (#433).
  • The example tables of the valuation models, factor analysis and tail dependence are regenerated from the current calculations (#398).
  • The performance and risk docstrings describe their definitions directly (#397).

Ratios

  • Toolkit(tickers, basket=True) adds a company named Total whose statements are the summed statements of the tickers, so its ratios and models weight each company by its size (#412).
  • get_market_cap(share=True) gives each ticker's share of the total market value, and get_market_cap_to_gdp(country=...) divides the total by a country's GDP in US dollars, on each date the previous complete year's (#406, #412).
  • get_net_capital_expenditure: capital expenditure beyond depreciation and amortization (#412).
  • The asset coverage ratio deducts goodwill as well as the other intangible assets (#400). Every tangible measure (asset coverage, return on tangible assets, tangible asset value, price to tangible book) takes the combined goodwill and intangible assets row, or the separate rows where it is missing, with a missing part counting as zero (#403).

Code

  • Log records without a credential keep their arguments, and a credential inside an argument is replaced in that argument, so formatters that read the arguments themselves keep working (#396).
  • soupsieve, used by beautifulsoup4, is locked at 4.1 (2.10 below Python 3.11.5) (#439).
  • opentelemetry-api, used by fastmcp, is locked at 1.45.2 (#440).
  • tornado is locked at 6.6.1 and dnspython at 2.9.2 (#443).

MCP server

  • A series= reference passes period= on to the indicators it reads, and reads a calendar event as a series (#402, #404).

  • Every answer lists the publishers its data comes from under _sources, also when it is answered from the cache or from data loaded by an earlier call (#418).

  • An indicator without a period parameter is converted to the requested period, with a note (#416).

  • Daily prices name the days a ticker did not trade (an exchange holiday), which carry its last close (#419).

  • Instances unused for 30 minutes are dropped and their memory is released, so a long-running server no longer keeps the memory of its busiest moment (#419).

  • rank=true on every tool ranks the tickers or countries within each period, with each one's gap to its neighbour (#421).

  • FT_MCP_COMPACT_TOOLS=1 lists the tools without their long descriptions, and search_metrics with an indicator's name returns its description and parameters (#422).

  • The Altman, Zmijewski, Springate and Taffler scores include their zone by default (#420).

  • The access log writes a line for every request again instead of a logging error, with request paths still free of credentials (#396).

v2.3.3

9 November 2026

A release on correctness, robustness and security, with bonds as a new asset class. Each ticker is now measured on its own trading days and calculated on unrounded data, so the Python package and the MCP server give the same figures. Controller methods work without arguments, bond calculators work on real bonds and market curves, the portfolio optimizers gain new objectives, constraints and a walk-forward backtest, and the MCP server, the cache, data retrieval and the release pipeline are hardened.

Package

Defaults from the data

  • Controller methods work without arguments: the valuation models default to each company's cost of equity (CAPM with its country's equity risk premium) or WACC, the dividend CAGR or the reinvestment growth, with the stable growth kept within 0% and 2.5%, all measured without look-ahead. Rates also take a list or a dict per ticker (#359).
  • With trailing set, the beta of the WACC and residual income covers the trailing periods, so quarterly defaults agree with annual ones (#359).
  • Defaults for get_tail_dependence_coefficient and get_covar (against the benchmark), get_style_analysis (Sharpe's asset classes as ETFs), get_commodity_forward_curve (all eight commodities), get_return_excluding (the largest holding), get_strategy_payoff (an at-the-money straddle) and the Discovery news searches (#359).

Bonds and rates

  • get_treasury_securities lists every marketable US Treasury with price, yield and duration from FedInvest, without an API key. get_bond_universe lists about 9,000 US corporate bonds from bond ETF holdings, with the G-Spread over the Treasury par curve (#356).
  • The bond calculators (collect_bond_statistics, get_present_value, get_duration, get_yield_to_maturity, get_z_spread, get_key_rate_duration, get_taylor_price_change) run on real bonds: by default the benchmark Treasuries, or bonds chosen with bonds=, issuer=, etfs= and a maturity range. The rate calculators read a country's government bond curves on a day (#358).
  • get_implied_default_probability takes ratings= and uses the latest ICE BofA spread per rating (#358).
  • Removed: get_option_adjusted_spread, get_derivative_price and the parameters for typing in a bond's terms by hand (#358).

Economic data without a FRED key

  • Initial jobless claims, retail sales, housing starts, real personal income, nonfarm payrolls and the HQM corporate bond curve and spread come straight from the Department of Labor, Census Bureau, BEA, BLS and Treasury when no FRED key is set, identical to FRED over their full history (#357).

Portfolio optimization

  • get_maximum_diversification_weights, get_minimum_tracking_error_weights (with objective="information_ratio") and get_growth_optimal_weights (Kelly, with fraction=), and covariance="denoised" (López de Prado) in every optimizer and in get_risk_contributions, (#362).
  • Per-asset weight bounds (one number or a dict per ticker), sector_bounds= and country_bounds= from the company profiles, and net_exposure and gross_exposure for long-short portfolios in every optimizer; risk parity takes weight, sector and country bounds (constrained risk budgeting) and HRP weight bounds. Infeasible constraints are refused with the reason (#378).
  • get_hierarchical_equal_risk_contribution_weights (HERC, Raffinot), get_nested_clustered_optimization_weights (NCO, López de Prado), get_minimum_drawdown_weights (CDaR, maximum or average drawdown), get_maximum_omega_weights and get_maximum_cvar_ratio_weights (#385, merged through #386).
  • get_optimization_backtest: a walk-forward backtest that re-optimizes on each monthly, quarterly or yearly date from the trailing returns, without look-ahead, against equal weights and the benchmark, with turnover and transaction costs (#386, #391).
  • current_weights= with maximum_turnover= and transaction_cost= in the optimizers, and expected_returns= ('mean', 'exponential', 'capm' or Jorion's 'james_stein') (#386, #391).
  • get_resampled_efficient_weights (Michaud resampling), get_diversification_metrics (concentration, effective number of assets and of bets, diversification ratio) and get_risk_contributions(risk_measure="cvar") for the contributions to expected shortfall. Every CVaR uses the exact Rockafellar-Uryasev tail (#386, #391).
  • covariance= gains the Ledoit-Wolf constant-correlation and single-factor targets, codependence= ('pearson', 'spearman' or 'kendall') sets the correlation behind HRP, HERC and NCO, get_mean_variance_weights takes target_volatility= for the highest expected return at a volatility, and Black-Litterman takes risk_aversion="market" (implied by the benchmark) and reports the posterior volatility (#394).
  • get_discrete_allocation turns weights into whole shares for a portfolio value (integer programme or greedy), get_portfolio_risk_metrics gives the return, volatility, Sharpe, Sortino, maximum drawdown, VaR and CVaR of given weights next to the benchmark, and get_risk_contributions adds semideviation, mean absolute deviation and CDaR (#393).
  • The portfolio docstrings describe every optimizer by its paper and formula (#392).
  • Removed: optimization_model.get_black_litterman_returns returning only the returns; it now returns the returns and the posterior covariance (#394).

Ratios

  • Gross profitability (Novy-Marx), operating profitability (Fama-French), cash-based operating profitability, cash return on invested capital, free cash flow conversion, free cash flow to EBITDA, capex intensity and capex to depreciation (#361).
  • EBITDA, EBITDA minus capex and cash interest coverage, FFO to debt and discretionary cash flow to debt (S&P, Moody's), the degrees of operating, financial and total leverage, the free cash flow payout ratio, EV to invested capital and price to tangible book (#373).
  • The investment and issuance anomalies: asset growth (Cooper, Gulen and Schill), net operating assets (Hirshleifer et al.), percent accruals (Hafzalla, Lundholm and Van Winkle), net share issuance (Pontiff and Woodgate), composite equity issuance (Daniel and Titman) and net external financing (Bradshaw, Richardson and Sloan) (#380).

Models

  • get_altman_z_score(model=...): the original Z, Z' (private firms), Z'' (non-manufacturers) and Z''-EM (emerging markets), each with Altman's own coefficients and zones, and get_taffler_z_score, the UK model of Taffler (1983) (#369).
  • get_campbell_hilscher_szilagyi_score: the failure probability of Campbell, Hilscher and Szilagyi (2008), with its components (#390).
  • On quarterly data the distress scores (Altman, Taffler, Ohlson, Zmijewski, Springate, Grover, Fulmer, Piotroski, Beneish) cover a trailing year and compare with the same quarter a year earlier (#387).
  • The valuation models warn when the required return is less than two percentage points above the growth kept forever (#387).
  • Removed: the model function parameter market_value_of_equity_to_book_value_of_total_liabilities_ratio of altman_model.get_altman_z_score, now equity_to_total_liabilities_ratio (#369).

Risk and performance

  • Each ticker uses its own trading days, and measures against the benchmark pair returns only on dates both traded (#353).
  • The drawdown table gains calendar-day and year durations, and get_drawdown_series a deepest_since= date (#354).
  • Calculations run on unrounded prices, returns and Treasury yields; only the returned tables are rounded (#367).
  • Lo's autocorrelation-adjusted Sharpe ratio (method="lo", with Moran's bias correction and at least 30 returns), get_sharpe_ratio_standard_error (iid, non-normal and GMM), get_minimum_track_record_length, and get_coskewness and get_cokurtosis with the benchmark (#379).
  • Drawdown and tail ratios no longer drop a period for every ticker when one ticker has no value; a zero denominator gives NaN instead of ±inf; returns that do not vary have no skewness or kurtosis; and a bad OHLC bar only leaves out that day in the range-based volatility estimators (#364).

Robustness

  • Supplied historical= data is checked and normalised (dates of any type, sorted, duplicates removed, returns calculated when missing), and supplied statements without a ticker level or with repeated line items are refused with a clear message (#371).
  • All Options methods carry @handle_errors; a ticker without a price on the pricing date is left out instead of failing the others, and a start_date on a non-trading day uses the last trading day before it (#371).
  • The package no longer silences RuntimeWarnings for the whole process (#371).
  • Symbols are percent-encoded in every FMP request, so M&M.NS is no longer read as Macy's (M); FMP errors sent with status 200 are classified, and one failing ticker no longer discards the results of the others (#363).

Analyst estimates

  • The latest price target's date and the days since it (#355).
  • The number of analysts behind the revenue and the EPS estimates as separate rows, and min_analysts= on the forward P/E and PEG to leave out thinly covered years. Estimate years follow the same calendar labelling as the statements, so for fiscal years ending January to May they move one year back and the forward PEG compares the right years. Removed: the averaged "Number of Analysts" row (#381).
  • The market-wide earnings calendar returns every release of a range instead of the latest 4,000, with each company's name, exchange and market cap in USD (from its primary listing), and min_market_cap, country, exchange, primary_only and sort_by (#381).

Commodities

  • get_commodity_term_structure: the front and far contracts, spread, slope, annualised roll yield and backwardation or contango per date, on the curve as listed each day or on fixed contracts (#382).
  • get_commodity_forward_curve takes generic=True for the front month and the next eleven as listed each day, and growth/lag; its end date is now included (#382).

Technicals

  • One get_moving_average(method=...) for the simple, exponential, double exponential, triangular, weighted and Hull moving averages. Removed: get_exponential_moving_average, get_double_exponential_moving_average, get_triangular_moving_average, get_weighted_moving_average and get_hull_moving_average (#388).
  • signals_only=True on get_signals and get_candlestick_patterns keeps only the days with a signal or pattern (#352).

Data sources

  • Fiscal periods are labelled alike from FMP and Yahoo Finance: a period ending in the first five days of a month counts as ending in the month before, which keeps the quarters of 52/53-week years that were dropped before. Yahoo statistics carry the fiscal quarter, so its filing deadlines match. Removed: yfinance_model.get_reported_currency, now get_company_information (#389).
  • Results whose periods have a multiplier, such as 2M, keep their period (#383).
  • The cache stores data as compressed JSON instead of pickle, so reading a cache file never runs code (#366).

Security

  • Only the FMP and FRED keys are read from .env files, never over a key already set in the environment; API keys are removed from every log message and traceback; the setup wizard writes its files readable only by you (#368).

Economics

  • Removed: get_real_gross_domestic_product_usd, the same series as get_gross_domestic_product(inflation_adjusted=True, usd=True) (#388).

Code

  • Misspelt names corrected, without aliases: get_gordon_growth_model (was get_gorden_growth_model), show_ticker_separation (was show_ticker_seperation), oecd_model.get_trust_in_government and the stock_simulation_dictionary parameter; duplicated value splitting and API key checks merged; unused pylint comments removed (#384).
  • Duplicated helpers merged into one place and dead code removed, including the unused constants Toolkit.TICKER_LIMIT and historical_model.TREASURY_LIMIT, portfolio.helpers.Style and SQLiteBackend.read_series and read_coverage (#374).
  • Docstring fixes across the package (#352).

MCP server

  • risk_free_rate ('13w', '5y', '10y' or '30y'; default '10y') on the performance, risk, models and portfolio tools (#367).
  • The earnings calendar answers with primary listings ranked by market cap by default (#381).
  • Size limits per call on simulations, backtests (lookback at most 504 days), resamples, strike grids, downloads and repeated fits, a 180-second time limit and at most three running calls per user when hosted, and responses cut to size before they are built (#360).
  • MCP_HOST defaults to 127.0.0.1 with DNS rebinding protection on loopback; forwarded headers are trusted only from FORWARDED_ALLOW_IPS; tickers are validated before they reach a URL; a hosted server never retries without TLS verification (#360).
  • Sign-in tokens are encrypted and last 24 hours, renewed by 90-day refresh tokens; registered clients are bound to their redirect addresses; pending authorization codes are limited per client address (#360, #368).
  • The Docker image pins its base image by digest, installs dependencies at build time and runs as a non-root user (#365).

Release pipeline

  • Merging a release PR publishes it to PyPI, GitHub and the MCP Registry after an approval, GitHub Actions are pinned to commit SHAs, and Dependabot keeps those pins and the Docker base image current (#365, #376, #377).
  • Offline tests block the network, and the calculations that no test covered are tested against values worked out by hand (#370, #375).

v2.3.2

6 November 2026

A large release with new analytics throughout the package: factor analysis (predictive power) in every module, return decomposition, earnings surprises, ETF contributions, alternative betas, Morningstar's risk-adjusted return, drawdown tables, candlestick patterns and indicator summaries. New data comes from analyst targets, 13F ownership, FINRA short volume, historical index constituents, the NY Fed, the BIS and Damodaran. The MCP setup wizard now writes to the right places for Claude Desktop on Linux, Devin Desktop and VS Code.

Package

New analytics

  • Factor analysis (predictive power): get_factor_analysis in ratios, technicals, models, risk and performance tests any metric, a list of them or a collection (e.g. ratios="valuation") as a cross-sectional signal: information coefficient (mean, IR, t-stat), quantile returns, top-minus-bottom spread, turnover and rank autocorrelation, without look-ahead. performance.get_factor_analysis also takes your own signal as a DataFrame (#335).
  • Returns explained: models.get_return_decomposition splits a price return into EPS growth × P/E change, plus dividends (#320). performance.get_beta_implied_return gives the beta-implied return, the actual return and the residual per period (#344). risk.get_move_significance shows how unusual a move is: volatility multiple, percentile and "largest since" date (#324).
  • Earnings: get_earnings_surprise gives EPS and revenue surprises, SUE, and the share's reaction against the benchmark per announcement (#321).
  • ETFs: etf.get_contribution gives each holding's or sector's contribution to the return (also in index points), and etf.get_return_excluding the return without chosen holdings or sectors (#322). etf.get_active_share (#339).
  • Performance: alternative betas via get_beta(method=...): Blume, Vasicek, Dimson, Scholes-Williams, upside and downside (#325). get_kelly_criterion and get_return_statistics (profit factor, payoff ratio, expectancy, streaks, recovery factor) (#336). Morningstar Risk-Adjusted Return and Morningstar Risk, checked against Morningstar's April 2023 methodology (#339).
  • Risk: get_drawdown_series and get_drawdown_table (#323), with the gain needed to recover: get_drawdown_series(recovery=True) and a Recovery Needed column (#350). get_move_significance also gives the VaR Multiple, a move divided by its trailing VaR (#350).
  • Portfolio: covariance= on every optimiser: sample, Ledoit-Wolf, OAS, semicovariance or exponential. Matches scikit-learn and PyPortfolioOpt (#326).
  • Models: H-model, three-stage DDM (transition_periods=), justified P/E and P/B, and get_intrinsic_valuation(historical=True) (#341). get_quality_score, a Quality Minus Junk composite (#343).
  • Growth: compound=True with growth=True, lag=n gives the n-period CAGR of statements, estimates and every ratio (#329).
  • Technicals: get_candlestick_patterns, 15 patterns identical to TA-Lib, and get_signals (crossovers, RSI zones, band breaks, new highs/lows) (#338). get_indicator_summary gives an indicator's latest value, its percentile and rank in its own history, its extremes with dates, threshold crossings and the average returns after them (#348).

New data

  • Analyst price targets, target history and monthly recommendations (#328). Institutional ownership from 13F filings (#333). FINRA daily short sale volume (#337).
  • Index constituents on a past date, plus the dated changes (#330).
  • NY Fed ACM Treasury term premium and Global Supply Chain Pressure Index (#331). BIS credit-to-GDP gap, debt service ratios and credit to GDP by sector (#332). Damodaran industry averages (#334).

Fixes

  • A ticker without data no longer adds calendar days to the other tickers (#318).
  • Yahoo Finance prices are taken unrepaired when yfinance's repair extra (scikit-learn) is missing, instead of failing (#327).
  • A daily bar fetched before its session closed is asked for again after the close (#345).
  • Technical indicators are calculated on a year of prices before the start date, so smoothed indicators (RSI, ATR, ADX, MACD, moving averages) no longer depend on it (#349).
  • The daily P/E, P/B, earnings yield and dividend yield carry the latest reported figures to the latest close instead of dropping periods before the start date (#349).
  • get_factor_analysis leaves out a metric that fewer than three tickers have (e.g. the preferred dividend coverage ratio in ratios.get_factor_analysis(metrics="all")), with a warning, instead of failing the whole analysis.

MCP server

  • limit selects rows per ticker in multi-ticker answers (#342).
  • A requested ticker that is also the benchmark is returned by methods without a benchmark, such as quotes (#346).
  • benchmark_ticker "None", "null" or "" means no benchmark (#318).
  • All new methods are available on their tools; there are still 25 router tools.
  • A note says when the last daily row comes from an unclosed session (#345).
  • Setup wizard (financetoolkit-mcp-setup):
    • Claude Desktop's Linux path is ~/.config/Claude.
    • The Windsurf client is replaced by "Devin Desktop (Windsurf)" (devin): it writes ~/.config/devin/mcp_config.json, or the old Windsurf file where it still exists.
    • VS Code entries carry "type": "stdio".
    • A new copilot client writes the global ~/.copilot/mcp-config.json.
  • server.json is published to the MCP Registry on every release (#319), and financetoolkit.mcpb is built and attached to every release by the release workflow (#351).

Removed

  • The windsurf choice of financetoolkit-mcp-setup --client; use devin.

The version is 2.3.2 in pyproject.toml, server.json, the bundle manifest, mcp_server/mcpb/pyproject.toml (including the financetoolkit[mcp]== pin) and uv.lock.

v2.3.1

3 November 2026

Some minor new functionalities that resolve edge cases and potential security flaws. Also introduced point-in-time mode as suggested by #298.

Package

New

  • Point-in-time mode (Toolkit(..., point_in_time=True), #301, closes #298).
    • Statements, ratios and models use each period's figures only from the day they were filed (FMP's accepted and filing dates, otherwise the reporting deadline).
    • end_date works as an "as of" date.
    • The statistics statement now holds the Filing Date and Fiscal Year.
  • Country equity risk premium in the Cost of Equity (#307).
    • CAPM, WACC, EVA, residual income and PVGO use the Damodaran premium of each company's country instead of the benchmark's historical excess return.
    • An explicit market_risk_premium still wins.
    • AAPL's 2024 WACC goes from 0.1947 to 0.0823.
  • Portfolio performance on the MCP server. The new tool portfolio_performance takes a portfolio as transactions, holdings, weights or a preset. It returns the overview, performance, positions, transactions and the money-weighted return.

Improved

  • Toolkit core (#300, #305):
    • Quarterly data looks back far enough for the trailing year and its growth in the first periods.
    • Supplied statements are never downloaded again and detect their own date order.
    • Statement periods after end_date are left out.
    • Exchange rates older than a month aren't used.
    • Inputs are validated (tickers, benchmark, lag, dates).
  • Data layer (#304):
    • The price cache refetches when a dividend or split rescales the adjusted history.
    • Prices with a failed dividend or adjusted-close request aren't cached.
    • API keys are removed from logged errors.
    • Discovery queries are URL-encoded ("AT&T", "Aerospace & Defense").
    • Certificate errors fail at once instead of retrying for minutes.
    • On the Free plan, dividends before the latest five come from Yahoo Finance.
  • Portfolio (#311):
    • Transactions in several currencies are converted to one reporting currency at each day's rate; pence and pounds are unified.
    • Purchases come before sales within a day.
    • Decimal commas are read per column.
    • The stored data is not rounded.
  • Utilities and cache (#311):
    • Growth is NaN around a gap.
    • standardize covers the shown window.
    • Cache entries are evicted daily, and the coverage of a cached range never extends past today.
  • Heavy calculations are bounded (#306): option, bond, Monte Carlo and binomial models cap their sizes.
  • Edge-case fixes:
    • Brinson, Black-Litterman, cointegration, YTM, DCC-GARCH, Omega and the MWR (#306).
    • SAR, OBV, the McClellan Oscillator, Supertrend, support/resistance and the volume indicators per ticker over gaps (#309).
    • ETFs compared on common dates (#299).
    • Hurst lags (#297).
    • Brinson looks through funds (#296).
  • Speed (#310): the rolling CVaR, CDaR and Omega, the grouped Ulcer Index and period resampling are vectorised.
  • Clearer messages (#308): a missing key outside the statements says which data is missing, and inflation expectations name the countries they cover.
  • Fixes in this PR:
    • Discovery:
      • The screener sends the upper market cap bound.
      • UK home listings are recognised (SHEL.L instead of the NYSE ADR).
    • Performance: the whole-period Omega, Gain-to-Pain and Rachev ratios are no longer empty.
    • Company data:
      • Annual ESG scores take the year's latest disclosure.
      • Missing revenue segments are NaN, and names keep FMP's spelling ("iPhone").
      • A changed actual_dates applies to a cached earnings calendar.
      • Statements and analyst estimates are stored unrounded, so the rounding of a first call no longer sticks.
      • The statistics statement follows start_date and end_date.
    • Docstrings: the WLS and GLS examples use the estimated weights and the AR(1) Omega.
  • Docs and packaging (#302): docstring defaults match the code, and the package metadata has project links.

Breaking

  • The reverse_dates and smooth_widow parameters are removed (#305, #302).
  • ROC, PPO, TRIX and the KST are decimals instead of percentages (#309).
  • Economics country names follow the Global Macro Database: Macedonia, Macau, Cape Verde, Sao Tome and Principe. The official names are accepted too (#309).
  • The rolling Omega is inf for a window with gains and no losses, like get_omega_ratio (#306, #310).

MCP server

  • Tools:
    • New tool portfolio_performance. Its inputs are validated before anything is fetched (one way to describe the portfolio, at most 1,000 transactions and 50 tickers), and transactions never reach the server as a file path.
    • 25 router tools.
  • OAuth hardening (#303):
    • Single-use authorization codes that expire after 5 minutes.
    • Validated redirect URIs.
    • PKCE S256 is required.
    • Field length caps.
    • An invalid token gets a 401.
  • Request handling (#303):
    • Tools run in a bounded thread pool with a lock per cached Toolkit.
    • A call waiting for a busy Toolkit gives up its slot.
    • Default dates are computed per call.
    • Ticker, search and series counts are capped.
    • Credentials are redacted from the access log.
    • The secret file is created private.
  • Inputs (#295): fractional, JSON and estimated inputs are accepted.

Other

  • Tests:
    • The flaky CI tests are fixed. 16 portfolio and point-in-time tests built Toolkits from supplied prices but without Treasury data, so valuing them retrieved Treasury yields from Yahoo Finance in parallel threads, which locked yfinance's SQLite cache ("database is locked"). Every such Toolkit now gets the supplied Treasury yields; with yfinance blocked, no test reaches it any more. Another test re-read the shared Portfolio's dataset and sent later tests online; it now uses its own Portfolio, and each test process gets its own yfinance cache.
    • 20 technical indicator tests that only recorded NaN now run on 60 sample bars and assert values.
    • New offline tests for the company data parsers.
  • Weekly source checks: a source that returns nothing is reported with what it logged, and a refusal over a request limit is skipped. The BLS allows 25 keyless requests a day per IP address, which GitHub's runners share (#315).
  • Dependencies:
    • tabulate moves from the mcp extra to the dev group.
    • Dependabot: tornado 6.6, joserfc 1.7.6, authlib 1.9.1, dnspython 2.9.0 (#312–#314, #316).
  • Dead code: the dead "pip install yfinance" branches are removed (yfinance is a required dependency).

v2.3.0

25 October 2026

New release with some new modules, lots of verification checks and overall improvements. See the complete list below.

Library

New

  • toolkit.portfolio: optimal weights (minimum variance, maximum Sharpe, mean-variance, risk parity, HRP, inverse volatility, minimum CVaR, Black-Litterman), efficient frontier, risk contributions, stress tests, look-through exposure and Brinson-Fachler attribution. Portfolio takes weights, holdings or transactions and ships 13 presets (#281).
  • toolkit.etf: holdings, weightings, profile with premium/discount to NAV (stale_nav=True for a NAV that is not current), tracking, concentration, overlap, look-through valuation and liquidity (#288).
  • Models: peer comparison, Merton distance to default, synthetic credit rating, reverse DCF, Monte Carlo valuation and more (#282).
  • Options: put/call ratio, max pain, gamma exposure, implied move, model-free implied volatility and the volatility risk premium (#283).
  • Fixed income: zero-coupon curves, Nelson-Siegel-Svensson, yield curve PCA, Vasicek/CIR/Hull-White, callable bond OAS, implied default probabilities and Treasury auctions (#284).
  • Econometrics on any series (Econometrics(data=...)), Markov regime switching, structural breaks, time-varying beta, DCC-GARCH and pairs trading (#285).
  • Performance and technicals: style analysis, regional Fama-French factors, market breadth, seasonality, relative strength and index constituents (#287).

Improved

  • Modules load statements and prices only when a calculation needs them (#290).
  • Every calculating method documents its formula with the defaults it uses, and every docstring example is regenerated live (#286).
  • Correctness, verified against the sources (#286): decimals everywhere, the traded close for market values, no look-ahead (figures apply from the fiscal period end), each ticker keeps its own history, quarterly ratios over a trailing year, continuous rates for options, the arch backcast for GARCH, and many method-level fixes.
  • show_columns selects numeric column labels such as years, thanks to @jackiectl2 (#292).

Breaking

  • Toolkit.get_etf_holdings, get_etf_information, get_etf_sector_weightings and get_etf_country_weightings moved to toolkit.etf (get_holdings and so on).
  • ICE BofA option-adjusted spreads and the discovery quote changes are decimals.
  • A Toolkit whose only ticker is the benchmark raises a clear error; pass benchmark_ticker=None.

MCP server

  • New portfolio and etf tools: 24 router tools.
  • Econometrics takes series= to analyse any indicator.
  • Descriptions follow the new methods, units and defaults; the bundle manifest is synced.

Other

  • A weekly GitHub Actions run checks every keyless data source and opens an issue per broken source (#289).

v2.2.3

12 October 2026

Mostly work for the MCP server to provide more reliable answers.

MCP server
  • Answers stay readable: anything over 60,000 characters is cut to the most recent rows, with a note on how to narrow it. limit works as head/tail (5 first, -5 last) on every tool. Large outputs (simulations, binomial tree, ETF holdings) have compact defaults.
  • Better discovery: search_metrics returns the exact indicator and its tool and understands analyst wording ("how expensive is the stock"). The server sends usage instructions on connect. Every parameter has a real description, from the docstrings.
  • Notes explain the answer: tickers without data, ignored arguments, yearly-only data, sample yield curves, assumed bond inputs, where a series ends, fiscal-year mapping and currency conversion.
  • Inputs: show_columns matches any casing and countries accept short forms (USA, UK). Weights, yield curves, option strategy legs and lists can be passed. Transcripts come back in full per company and fiscal period. Option chains say which expiry they show.
  • Hosted server: at most 4 Economics and 64 Toolkit instances are kept, and one Global Macro Database copy is shared per process (memory stays flat across date ranges).
  • Tools: search_instruments is removed (Finance Database covers it), search_categories is renamed search_metric_categories, and EGARCH is no longer offered (~45s per fit).
Package
  • Stale FMP data fixed: Commitment of Traders, sector and industry history and 8-K filings now request a date range.
  • Stock screener: market caps are in USD, primary_only keeps the home listing, and it returns stocks only unless is_etf=True.
  • Symbols: ISIN/CUSIP/CIK search uses its own parameters, and currency and crypto pairs are accepted in either notation (EURUSD or EURUSD=X).
  • Economics: quarterly and monthly rates use sources with that frequency, calendar event matching ignores spaces and hyphens, and Current Policies climate scenarios work.
  • Fixes and additions:
    • Daily GARCH forecasts are dated by business day.
    • Gainers and losers are sorted by change and ETF weights largest first.
    • Gross margin is empty where cost of goods sold is zero.
    • The Sharpe ratio takes annualize.
    • Option chains take strike_price_range.

v2.2.2

10 October 2026

This release adds new FMP endpoints and recent economic and market data from official sources that need no API key. It also adds scenario and credit inputs, caches external data by default, speeds up many calculations, and fixes a range of calculations and data issues.

New data

  • FinancialModelingPrep:
    • Toolkit: executives and compensation, company notes, employee count, shares float, M&A, stock splits, insider statistics, stock grades, ETF holdings, information and weightings, and earnings call transcripts. Stock news now covers crypto and forex.
    • Discovery: market-wide earnings calendar, 8-K filings and latest insider trades.
    • Economics: economic calendar and market risk premium (optional key).
  • No API key needed:
    • Monthly inflation, CPI and unemployment; quarterly GDP growth.
    • Daily policy, overnight and long-term rates.
    • Government yield curves for nine economies, plus every EU member's 10-year yield.
  • FRED no longer required for the mortgage rate, industrial production, the recession indicator, real yields and breakevens. FRED is still used when a key is set.
  • Credit:
    • The Treasury's HQM corporate curve and spreads, and Moody's Aaa/Baa yields.
    • The excess bond premium and corporate bond yields by country.
    • Rating transition matrices and default rates from ESMA's CEREP database.
    • ECB borrowing costs and stress index.
  • Insurance and long horizons:
    • EIOPA risk-free curves, incl. shocks and the symmetric adjustment.
    • Eurostat life tables and Shiller's US stock market data.
    • Long-run asset returns 1870–2020 (opt-in, non-commercial licence).
    • The Bank of England's UK series from 1086.
  • Scenario inputs:
    • Real and breakeven inflation curves for the US, UK and Germany, and survey inflation expectations.
    • Implied volatility indices (VIX, VSTOXX, MOVE).
    • Fed and ESRB stress-test scenarios and DNB pension scenario sets.
    • NGFS climate scenarios and the EU carbon price.
    • Listed proxies for private markets.
  • Global Macro Database: uses the latest quarterly release. IMF projections are excluded by default.

Caching

  • On by default: data from external sources is cached in the Toolkit, Economics, Fixed Income, Discovery and Portfolio modules. Each dataset is refreshed on its own schedule, and calculated metrics are never cached.
  • Empty answers: an answer that a source has no data is cached too; a failed request is not.
  • FMP first: with an FMP key, FMP data takes priority. Yahoo Finance is used when it has the longer history, for example on the Free plan.

Performance

Before After
EGARCH / GARCH 186 s / 7.9 s 13 s / 1.2 s
Monte Carlo option prices 66 s 2.5 s
All option greeks 5.4 s 0.15 s
All technical indicators 3.3 s 0.7 s
from financetoolkit import Toolkit 2.5 s 0.9 s
Reading prices from the cache 3.8 s 1.1 s

Excel files are read with calamine, modules load on first use, and repeated module access is about twice as fast.

Breaking changes

  • get_real_yield_curve and get_breakeven_inflation_expectations take countries= and return (Country, Maturity) columns labelled 5Y.
  • The market risk premium and percentage releases in the economic calendar are now decimals.
  • GMDB series end at the last observation; gmdb_forecasts=True on a method includes the projections.
  • Corrected calculations change some results:
    • Drawdowns now count a loss on the first day.
    • RSI and CMO start one day later, matching Wilder's definition and TA-Lib.
    • Growth from zero is missing instead of infinite.
    • Missing values no longer skew beta, VaR/CVaR or the portfolio average.
  • External data is cached by default. Opt out with use_cached_data=False or FINANCE_TOOLKIT_CACHE_ENABLED=0.
  • Requests carrying an API key are no longer retried without certificate verification. Behind a corporate proxy, set REQUESTS_CA_BUNDLE; the README Q&A explains how.

Fixes

  • Data:
    • FMP timeouts and server errors are retried per ticker instead of failing the whole request.
    • Cached prices survive a provider switch.
    • Holidays no longer invent returns or volume.
    • CIK and CUSIP keep their leading zeros.
    • Yahoo listing dates use the exchange's timezone.
  • Calculations:
    • WACC is correct for companies without debt, and the Graham Number for loss-making companies.
    • Barrier options are priced correctly once the barrier has been crossed.
    • Black-Scholes at expiry, bond coupon counts and yields, and binomial tree inputs are handled correctly.
  • Consistency:
    • rounding=0 and rounding=None work everywhere.
    • One error handler serves all modules, so strict mode now covers Performance and Technicals.
  • Other:
    • EIOPA shocked curves and the life tables are fixed.
    • The enterprise value breakdown and implied volatility work again.
    • The economic calendar's order is now deterministic.
    • Moved BIS, Fed and NBER endpoints are updated.
  • Docstrings: all 553 examples were run and their output tables refreshed.

MCP server

  • New methods are added to the existing tools, and an empty result explains why.
  • Tool descriptions are no longer cut off.
  • Daily rolling performance metrics work.
  • A hosted server caches every source except FMP.
  • Optional usage statistics at /stats with FT_MCP_ANALYTICS=1.
  • The server reports the Finance Toolkit's version to clients.

Dependencies

All new requirements use wide version ranges, so the Finance Toolkit fits alongside other packages without forcing upgrades.

Change Package Why
Added python-calamine>=0.3.0 Reads Excel workbooks up to 10× faster than openpyxl. Used for the large official workbooks, such as the Bank of England, EIOPA and ESRB files. Not installed on Python 3.15 until wheels are published there; openpyxl reads the files instead.
Added xlrd>=2.0 Reads the older .xls workbooks some official sources still publish, when calamine is not available or cannot read a file.
Declared numpy>=1.26, scipy>=1.10 Already used throughout, but until now they were only installed because other packages depended on them. They are now listed explicitly.
Removed scikit-learn Only used for the linear regressions of the factor models (e.g. Fama-French). These now use SciPy's least squares, with the same results, which removes a large dependency.

Unchanged: pandas>=3.0, requests, yfinance, openpyxl and pyyaml, and the optional econometrics and mcp extras.

v2.2.1

1 October 2026

A focused maintenance release. Its most urgent fix: a fresh install of the 2.2.0 MCP server crashed on startup, because the mcp dependency had no upper bound and mcp 2.x removed a module the server imports. The local install command on the website therefore failed for everyone. This release caps mcp below 2.0 and fixes two MCP data bugs on top: the rates tool returned no Treasury yields at all, and a benchmark that was also a requested ticker was silently swapped for a different index.

The second theme is daily-first analysis. Risk and Econometrics now default to daily calculations over the whole series instead of quarterly/yearly per-period values, which removes the intraday-data requirement that made period="daily" unusable in Econometrics. Some results change for existing code as a result; see Changed Defaults below.

Underneath, data collection is faster and better behaved. A bounded worker pool replaces one thread per ticker, HTTP connections are reused, and retries back off with jitter. The package now ships type information (py.typed), and the type checker runs in CI.

Every method below hangs off the matching Toolkit sub-module (e.g. toolkit.risk.get_value_at_risk()) or its standalone class (Economics(...), FixedIncome(...), Discovery(...)). Full runnable examples live in the documentation, which now has a dedicated page for every method.

Changed Defaults

  • Econometrics defaults to period="daily" across all methods (previously quarterly or yearly, depending on the Toolkit). within_period now defaults to False on the five diagnostic tests that take it (ARCH-LM, Jarque-Bera, Ljung-Box, CUSUM, Variance Ratio). Every Econometrics method previously rejected period="daily" outright, even though only the within-period nesting needs intraday data. Intraday data is now only required for period="daily" combined with within_period=True, and the error message says how to avoid it. Full examples: docs/econometrics.
  • Risk defaults to period="daily" and within_period=False as well, so metrics such as Value at Risk, CVaR and the GARCH family are calculated over the whole daily series by default. Per-period aggregates (variance, volatility, excess volatility, MAD, coefficient of variation) keep their quarterly/yearly default, since a single daily return has no spread to measure. Full examples: docs/risk.
  • If your code relied on the old defaults, pass period="quarterly"/"yearly" (and within_period=True) explicitly to get the previous behaviour.

Performance

  • Bounded worker pool. Every data collection function used to start one bare thread per ticker, with a 0.1-second stagger between them. A 100-ticker universe spent 10 seconds just starting threads, exceptions died silently inside their thread, and the number of concurrent API calls grew with the universe. All 13 collection sites now share one ThreadPoolExecutor with 10 workers by default (configurable via FINANCETOOLKIT_MAX_WORKERS) that re-raises worker exceptions.
  • Connection reuse. Every request goes through one shared requests session with enlarged connection pools, so repeated calls to the same API reuse TCP connections and TLS handshakes instead of paying for a new handshake each time.
  • Retries back off with jitter, so ten workers hitting a rate limit don't all retry at the same moment.
  • Treasury rate windows are fetched in parallel through the same pool, instead of one by one with sleeps in between.
  • Memoized slices. Risk (_get_returns), Econometrics and Performance cache the return and column slices their methods start from, so collecting many metrics, as the MCP server does in one session, no longer recomputes them for every metric.

Bug Fixes

Risk & Econometrics

  • Whole-series Risk calculations on resampled periods returned NaN, because the first resampled return is always NaN. That row is now dropped before the calculation.
  • get_arch_lm_test(within_period=False) produced no values at all under the old yearly default: four yearly observations can't support a 5-lag ARCH test. With the daily default it now returns real results.
  • Fresh installs now resolve statsmodels 0.15, where the ADF test (get_augmented_dickey_fuller) and the ARCH-LM test (get_arch_lm_test) printed a FutureWarning about an upcoming change to their return format. The toolkit is unaffected by that change until statsmodels 0.16, so these two notices are now silenced. Results are identical on statsmodels 0.14 and 0.15.

API key handling

  • Passing the documentation placeholder api_key="FINANCIAL_MODELING_PREP_KEY" used to reach FinancialModelingPrep and come back as a generic "invalid API key", without saying that the example value was never replaced. It's now reported as a placeholder, with a link to get a key, and treated as no key at all (e.g. the Toolkit falls back to Yahoo Finance). This applies to Toolkit, Portfolio, Discovery, FixedIncome and the MCP server.

MCP Server

  • Fresh installs crashed on startup. mcp 2.x removed mcp.server.fastmcp, which the server imports, and the mcp extra had no upper bound, so pip install financetoolkit[mcp] resolved mcp 2.x and failed immediately. The extra now requires mcp[cli]>=1.27.0,<2.
  • rates → get_treasury_rates returned no data. The server built FixedIncome without the FMP API key, which the Treasury par yield curve needs, and the error was swallowed into "No data available". The key is now passed on, and both the FMP and FRED keys are part of the instance cache key, so instances are never shared between keys.
  • The benchmark could silently be a different security. When a requested ticker was also the benchmark (e.g. tickers="AAPL,SPY" with benchmark_ticker="SPY"), the server replaced the benchmark with the first unused fallback. "Benchmark" was then QQQ (739.77 instead of SPY's 762.63 on 2026-09-30), so every beta, alpha and excess return was measured against the wrong index. The requested benchmark is now kept, matching the library; a fallback is only used when the benchmark is the sole ticker. Either way, the response includes a note explaining where the benchmark's data is.
  • The startup log reported "Registered router group '…' → True tool(s)" instead of a count; it now names the registered group.
  • Daily period is no longer blocked for the risk tool, matching the new default.
  • Per-call timing is logged at debug level, so a slow tool can be diagnosed from the logs alone.

Documentation

  • Every method has its own documentation page. The 76 README links that pointed to an anchor on a module page (docs/ratios#collect_profitability_ratios) now point to that method's dedicated page (docs/ratios/all-profitability-ratios).
  • 21 Econometrics methods, including get_vif, get_ols, the heteroskedasticity and specification tests, the nested-model tests, Fama-MacBeth, synthetic control and the VAR forecast, previously had a single sentence plus a pointer to an internal function the website doesn't show. Each now explains what it computes, the formula, how to read the result for the tickers involved, and the original reference.
  • 31 Econometrics docstrings still said period followed the Toolkit's quarterly/yearly setting; they now document the actual "daily" default.
  • FixedIncome.get_government_bond_yield opened with the 10-year description even when short_term=True returns the 3-month rate. Both maturities are now described, including that the OECD short-term figure is the 3-month interbank rate rather than a Treasury bill yield.
  • get_dual_gamma reused the gamma description; it now describes the second derivative with respect to the strike price.
  • The dead Global Macro Database link in get_gross_domestic_product now points to the GMD documentation page.

Typing

  • The package now ships py.typed, so downstream type checkers see its annotations.
  • uv check (Astral's ty) runs in pre-commit and in the linting workflow. Five rules are back at their default severity (call-non-callable, not-iterable, not-subscriptable, unsupported-operator, unknown-argument), with the code they flagged fixed. 29 stale type: ignore comments are gone. The rules that only reflect pandas' very wide Series | DataFrame return types stay disabled.

Test Coverage & CI

  • Toolkit parameter validation (dates, risk-free rate, source, intraday period, tickers) now lives in its own module, validation_model, so bad input can be tested without building a Toolkit and fetching data.
  • CI runs the suite in parallel (pytest-xdist) with the uv cache. The Economics tests skip cleanly when offline or without a FRED key, instead of erroring.
  • The recorder gains --rewrite-failing, which regenerates only the stored outputs that fail comparison, so a regeneration can't churn unrelated files through float noise.
  • New tests cover the MCP provider (the treasury key and the benchmark handling) and the placeholder API key.
  • A version-alignment test makes sure pyproject.toml, server.json, the MCPB manifest and the MCPB bundle's own pyproject.toml all carry the same version.
  • A Python 3.15 job runs in CI and is skipped until the lock file contains SciPy wheels for 3.15, rather than compiling SciPy from source on the runner.

Dependencies

  • mcp[cli]>=1.27.0,<2 in the mcp extra (see MCP Server above).
  • Lockfile updates: cryptography 50.0.0, httpx2/httpcore2 2.12.0, jupyterlab 4.6.4, notebook 7.6.3, pyjwt 2.15.0, tornado 6.5.9, urllib3 2.8.0.

Full comparison: v2.2.0...v2.2.1

v2.2.0

18 August 2026

This is the largest release to date. The headline addition is a brand new Econometrics module (toolkit.econometrics) — 48 methods covering regression, panel data, causal inference, unit root/cointegration testing, Granger causality, diagnostics, and forecasting, all funneled through statsmodels/linearmodels instead of hand-built math. Alongside it, Risk, Performance, Models and Economics roughly double in depth with systemic-risk, market-timing, bankruptcy-scoring and crisis-dating metrics, and Technicals, Ratios, Fixed Income and Options each pick up a batch of previously-missing metrics.

The second large addition is a rebuilt caching layer. Three separate, incompatible caching mechanisms have been replaced by one incremental, range-aware SQLite cache that knows what it already holds per ticker and per date range — widening a period now retrieves only the missing years, and adding a ticker retrieves only that ticker. It also removes a genuine correctness bug in the old one, which silently overwrote the tickers and dates you asked for with whatever an earlier cached run had used. See Caching below.

Just as importantly, this release includes an extensive formula-correctness pass across nearly every module, carried out over two separate audit rounds — the second explicitly re-checking the first round's own fixes rather than trusting them. Every accepted finding was verified against live FMP/FRED/OECD/ECB/NY Fed data, published figures from BLS/BEA/the US Treasury/Ken French/the source papers, a reference library (TA-Lib/arch/statsmodels/linearmodels/py_vollib) where one exists, or analytic ground truth via Monte Carlo and finite differences. Combined, this fixed over 200 defects. Several of these are not edge-case bugs — Sharpe Ratio, Sortino Ratio, M2 Ratio, RSI, ADX, ATR, EWMA Volatility, the Hurst Exponent, Macaulay's Duration, bond DV01, Portfolio Volatility, US "headline" unemployment and every price-to-fundamental ratio on the LSE/JSE/TASE were all silently returning the wrong number in prior releases. See Bug Fixes below for the full list with what changed and why.

Minimum requirements changed: pandas>=3.0 (was >=2.2) and Python 3.11+ (was 3.10+, since pandas 3.0 itself drops 3.10 support).

Every method below hangs off the matching Toolkit sub-module (e.g. toolkit.econometrics.get_ols()) or its standalone class (Discovery(...), Economics(...), FixedIncome(...)). Full runnable examples with real output live in the documentation — each section below links to its module's page.

New Features

Econometrics (new module)

toolkit.econometrics is a new, optional module for testing statistical properties of price/return series and estimating causal effects — installed via the financetoolkit[econometrics] extra (statsmodels/linearmodels). Every result is a plain dict (matching the rest of the codebase's convention of returning pd.Series/pd.DataFrame rather than opaque result objects), with a matching *_summary_table/*_summary companion wherever a .summary() would otherwise be expected. Full examples: docs/econometrics.

  • Regression: get_ols, get_wls, get_gls (nonrobust/HC0-3/cluster/HAC-Newey-West standard errors), get_logistic_regression, get_probit_regression, get_quantile_regression.
  • Panel data: get_fixed_effects, get_random_effects, get_hausman_test (which specification to prefer).
  • Causal inference: get_difference_in_differences, get_iv_2sls, get_propensity_score_matching, get_regression_discontinuity, get_synthetic_control (Abadie/Diamond/Hainmueller 2010, with placebo-based inference).
  • Time series forecasting: get_arima_forecast, get_var_forecast (plus get_impulse_response_function and get_variance_decomposition), get_vecm_forecast.
  • Cross-sectional asset pricing: get_fama_macbeth_regression (Fama-MacBeth two-pass regression).
  • Event studies: get_event_study (MacKinlay 1997 market-model cumulative abnormal return analysis).
  • Unit root & cointegration: get_augmented_dickey_fuller, get_kpss_test, get_phillips_perron_test, get_zivot_andrews_test; get_engle_granger_cointegration, get_johansen_cointegration.
  • Granger causality: get_granger_causality.
  • Diagnostics: get_arch_lm_test, get_jarque_bera_test, get_ljung_box_test, get_cusum_test, get_variance_ratio_test.
  • Specification & hypothesis tests: get_breusch_pagan_test, get_white_test, get_durbin_watson_test, get_vif, get_ramsey_reset_test, get_chow_test, get_f_test, get_likelihood_ratio_test, get_wald_test, get_hausman_wu_test, get_two_sample_t_test.
  • Forecast evaluation: get_rmse, get_mae, get_diebold_mariano_test, get_out_of_sample_validation.
Risk

Call these via toolkit.risk.<method>(). Full examples: docs/risk.

  • get_covar (CoVaR / Delta-CoVaR) — how much returns' own tail risk worsens when conditioning_returns (e.g. the financial system, or a specific counterparty) is itself in distress, via quantile regression. Reference: Adrian, T. & Brunnermeier, M.K. (2016), American Economic Review.
  • get_marginal_value_at_risk / get_component_value_at_risk — Euler risk decomposition of portfolio VaR: Marginal VaR is each asset's Beta to the portfolio times portfolio VaR; Component VaR is that scaled by the asset's weight, and the components sum exactly to total portfolio VaR (Garman 1997, Litterman 1996).
  • get_amihud_illiquidity (Amihud 2002) and get_roll_spread (Roll 1984) — market-microstructure liquidity measures derived purely from price/volume, without needing order-book data.
  • get_volatility(method=...) — four realized-volatility estimators ("parkinson", "garman_klass", "rogers_satchell", "yang_zhang") built from daily OHLC(V) prices rather than just closes, each using more of the day's price action (and, for Yang-Zhang, overnight gaps) to estimate volatility more efficiently than a close-to-close standard deviation. The default method="close_to_close" is the existing behaviour.
  • get_har_rv_forecast (Corsi 2009 HAR-RV) — forecasts future realized variance from a simple linear combination of daily, weekly and monthly lagged realized variance, a cheap and surprisingly effective alternative to a full GARCH fit.
  • get_hill_estimator — a nonparametric estimate of the tail index of the return distribution, i.e. how fat the tails actually are.
  • get_gjr_garch / get_egarch (plus _forecast/_parameters variants, and get_garch_parameters for the plain model) — asymmetric GARCH models where negative and positive shocks affect future volatility differently (the leverage effect), unlike plain GARCH. References: Glosten, Jagannathan & Runkle (1993); Nelson (1991).
  • get_var_backtest — builds a rolling, out-of-sample VaR path and backtests it with the Kupiec (1995) proportion-of-failures test and the Christoffersen (1998) independence test, to check whether a VaR model's breach rate and breach clustering match what the confidence level implies.
  • get_acerbi_szekely_test — the counterpart for Expected Shortfall, backtesting a CVaR model against realized returns via the Acerbi-Szekely (2014) Z2 statistic, since the breach-counting tests above only validate VaR.
  • get_tail_dependence_coefficient, get_copula_parameters / get_copula_simulation / get_best_fitting_copula — Gaussian, Student-t, Clayton, Gumbel and Frank copulas with MLE fitting, simulation, and AIC-based family comparison, for modelling joint tail behaviour between two return series beyond what linear correlation captures. Default to running across every unique ticker pair on the Toolkit instance when no explicit pair is given.
Performance

Call these via toolkit.performance.<method>(). Full examples: docs/performance.

  • get_sharpe_ratio(method=...) — three corrections to the plain Sharpe Ratio: "adjusted" for skewness/kurtosis, "probabilistic" for estimation uncertainty given the sample size, and "deflated" for multiple-testing bias when many strategies were tried before picking the best one. The default method="standard" is the existing behaviour.
  • get_appraisal_ratio — Jensen's Alpha divided by the idiosyncratic (residual) standard deviation left over from the CAPM regression that produced it: how much stock-picking skill an active manager is generating per unit of the risk that skill itself introduces.
  • get_fama_decomposition (Fama 1972) — splits total excess return into Selectivity and Diversification, decomposing Jensen's Alpha further than the Alpha figure alone can.
  • get_henriksson_merton_model and get_treynor_mazuy_model — market-timing regressions that test whether a manager's returns show evidence of successfully timing the market, not just picking good securities.
  • get_rachev_ratio (R-Ratio) and get_starr_ratio — tail-focused alternatives to Sharpe/Sortino that measure reward per unit of tail risk (CVaR-based) rather than per unit of standard deviation or downside deviation.
  • get_carhart_four_factor_model (Carhart 1997) — adds a momentum factor to the existing Fama-French regression machinery.
Models

Call these via toolkit.models.<method>(). Full examples: docs/models.

  • get_fulmer_h_score, get_grover_score, get_ohlson_o_score, get_springate_score, get_zmijewski_score — five more bankruptcy/distress prediction models alongside the existing Altman Z-Score and Piotroski F-Score, each estimated on a different sample or via a different technique (multiple discriminant analysis, logistic regression), so comparing several together is more robust than relying on any single one.
  • get_free_cash_flow_to_equity / get_free_cash_flow_to_firm (FCFE / FCFF) — the levered and unlevered cash flow bases used in DCF valuation, discounted at cost of equity and WACC respectively.
  • get_market_value_added (MVA) — the market-priced counterpart to Economic Value Added: the gap between a company's current market value and the total capital historically invested in it.
  • get_residual_income — the equity-side counterpart to EVA: profit in excess of what equity holders require, netting only the cost of equity (not debt) off of Net Income.
  • get_tobins_q_ratio — market value of a company relative to the replacement cost of its assets; a high Q suggests management has an incentive to invest further.
  • get_two_stage_dividend_discount_model — extends the (single-stage) Gordon Growth Model to companies not expected to grow at a constant rate forever, explicitly projecting a high-growth phase before switching to a terminal constant-growth phase.
Technical Indicators

Call these via toolkit.technicals.<method>(). Full examples: docs/technicals.

  • get_awesome_oscillator, get_know_sure_thing, get_rate_of_change — momentum oscillators built from moving averages / smoothed rate-of-change components.
  • get_choppiness_index — how much a market is trending versus chopping sideways, independent of direction.
  • get_ease_of_movement, get_vortex_indicator — price/volume and directional-movement indicators for gauging trend strength.
  • get_chaikin_money_flow, get_elder_ray_index, get_negative_volume_index / get_positive_volume_index — volume-based buying/selling pressure indicators.
  • get_kaufman_adaptive_moving_average (KAMA) — a moving average that automatically speeds up in trending markets and slows down in choppy ones, based on an efficiency ratio of net movement to total movement.
  • get_supertrend — a volatility-adjusted (ATR-based) trend-following stop-and-reverse line, in the same family as Parabolic SAR.
  • get_fibonacci_retracement_levels — the standard retracement grid (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%) between a swing high and low, for either trend direction, with the ratios overridable. It sits in the same category as Pivot Points, the Ichimoku Cloud and Support/Resistance Levels: a price-level reading convention rather than a formula with empirical support. The docstring says so explicitly, including that the 50% level is not a Fibonacci ratio at all and that 78.6% is the square root of 61.8% rather than a ratio from the sequence.
Ratios

Call these via toolkit.ratios.<method>(). Full examples: docs/ratios.

  • get_asset_coverage_ratio — how well tangible assets, after covering current liabilities, can cover total debt.
  • get_cash_return_on_assets — operating cash flow generated per dollar of assets, a cash-basis alternative to accrual-based ROA.
  • get_defensive_interval_ratio — how many days a company could keep covering operating expenses using only its most liquid ("defensive") assets, with no further revenue.
  • get_ebitda_margin, get_free_cash_flow_margin — EBITDA and free cash flow, each as a share of revenue.
  • get_gross_debt_to_ebitda_ratio — total (gross) debt relative to EBITDA, a common leverage covenant metric.
  • get_price_to_sales_ratio — market cap relative to revenue, useful for unprofitable or early-stage companies where P/E doesn't apply.
  • get_working_capital_turnover_ratio — how effectively working capital is converted into revenue.
Economics

Call these via Economics(...).get_*(), or toolkit.economics.<method>() on a Toolkit instance. Full examples: docs/economics.

  • Crisis dating: get_banking_crisis, get_currency_crisis, get_sovereign_debt_crisis — Reinhart & Rogoff style binary (0/1) crisis dummies per country and year from the Global Macro Database, rather than the continuous series the rest of the module returns, for marking historical stress episodes on a chart or conditioning a model on them.
  • Cross-country real activity: get_real_gross_domestic_product_usd and get_real_gross_domestic_product_per_capita (GMDB, inflation-adjusted and directly comparable across countries), get_trade_balance, get_real_effective_exchange_rate (trade-weighted and inflation-adjusted), and the OECD's get_output_gap (actual versus potential GDP).
  • Composite and derived indicators: get_misery_index (unemployment plus inflation), get_real_interest_rate (nominal rate net of inflation) and get_yield_curve_slope (10-year government bond yield minus the 3-month money market rate).
  • 8 new FRED-backed, US-only indicators with no existing GMD/OECD alternative: get_nonfarm_payrolls, get_initial_jobless_claims, get_retail_sales, get_industrial_production_index, get_housing_starts, get_recession_indicator (NBER-based), get_real_personal_income, get_mortgage_rate_30_year.
  • TIPS/inflation-market data: get_real_yield_curve (FRED TIPS real yields, 5/7/10/20/30Y) and get_breakeven_inflation_expectations (market-implied inflation, including the 5Y5Y forward rate).
  • get_commercial_real_estate_prices (FRED's commercial, not residential, property price index) and get_commodity_forward_curve (dated CME futures contracts from Yahoo Finance, since FRED/OECD/FMP only expose a single spot price per commodity).
  • 3 new OECD-backed methods: get_producer_price_index, get_household_savings_rate, get_household_debt_to_income_ratio, plus an OECD-sourced CPI option; startPeriod/endPeriod support added across all OECD-backed functions.
  • On the Toolkit itself (not ticker-scoped): get_market_risk_premium and get_commitment_of_traders.
  • The FRED API key is now actually threaded through to Economics/FixedIncome when using the MCP server — it was silently never passed before.
Fixed Income

Call this via FixedIncome().get_*(), or toolkit.fixedincome.<method>(). Full examples: docs/fixedincome.

  • get_par_yield, get_forward_rate — deriving par and forward rates from a zero-coupon spot curve.
  • get_breakeven_inflation_rate — the inflation rate implied by a nominal yield versus its inflation-protected counterpart.
  • get_key_rate_duration — a bond's sensitivity to a single maturity point on the yield curve moving in isolation, rather than the whole curve shifting in parallel.
  • get_yield_curve_spread, get_z_spread — spread between two curve points, and the constant spread that reprices a bond exactly against a benchmark curve.
  • get_bond_equivalent_yield — converts a money-market discount yield (e.g. quoted for T-bills) into a directly comparable bond-equivalent yield.
  • get_taylor_price_change — estimates a bond's price change for a given yield move using a second-order Taylor expansion (duration + convexity) instead of duration alone.
  • get_treasury_rates — the official U.S. Treasury par yield curve, every maturity from 1 Month to 30 Year in one dataset, paginated in 90-day windows to respect the endpoint's per-request cap.
Options

Call these via toolkit.options.<method>(). Full examples: docs/options.

  • get_asian_option — geometric-average Asian option pricing (Kemna & Vorst 1990 closed form).
  • get_barrier_option — single-barrier knock-in/knock-out option pricing (Reiner & Rubinstein 1991).
  • get_binary_option — cash-or-nothing digital option pricing under Black-Scholes.
  • get_bjerksund_stensland — a closed-form analytical approximation for American option prices (Bjerksund & Stensland 1993), much faster than a binomial tree.
  • get_garman_kohlhagen — Black-Scholes adapted for FX options, using both the domestic and foreign risk-free rate.
  • get_monte_carlo_option_price — European option pricing via Monte Carlo simulation of Geometric Brownian Motion price paths.
  • get_put_call_parity — checks or derives the no-arbitrage put-call parity relationship for European options.
  • get_strategy_payoff — net expiration P&L of a multi-leg option (and, optionally, stock) strategy.
  • get_volatility_surface — fits a raw SVI smile (Gatheral 2004) per expiry across multiple maturities and flags (rather than silently ignoring) calendar-spread arbitrage between them.
  • get_risk_neutral_density — the market-implied risk-neutral probability density of the underlying at expiration via the Breeden-Litzenberger (1978) theorem, applied to a calibrated SVI smile rather than one flat assumed volatility (see Bug Fixes).
Caching (rebuilt)

use_cached_data=True still turns caching on, but what happens underneath is entirely new. Where the old cache stored one pickle per dataset and could only ever answer "same request as last time, or nothing", the new one records which tickers and which date ranges it actually holds, and asks the API only for what is missing.

  • Incremental and range-aware. Repeating a request retrieves nothing at all. Widening start_date/end_date retrieves only the years that were not already there. Adding a ticker retrieves only that ticker. Previously any change to any parameter refetched everything.
  • Every external source is covered — financial statements, historical and intraday prices, FRED series, OECD queries, treasury rates, futures contracts, company profiles, quotes, ratings, analyst estimates, earnings and dividend calendars, ESG scores, segmentations, Commitment of Traders, option chains and expiries, GMD, ECB, Fed, Ken French factor datasets, the market risk premium and the discovery endpoints. Anything the Toolkit computes itself is never cached — it is always derived from that data on demand.
  • One shared database. It lives in your platform's user configuration directory (overridable with FINANCE_TOOLKIT_CACHE_DB, or by passing a folder to use_cached_data), which is the same file the MCP server uses, so a local server and the library warm each other's cache instead of each keeping their own.
  • Two freshness knobs per dataset. A time-to-live decides whether to refresh at all, and a revision window decides how much of the recent tail is re-requested when it does — so a rerun inside the TTL makes zero external calls, while a stale daily price series re-requests only its last few days rather than its whole history.
  • toolkit.get_cache_contents() reports what is stored, grouped by source and dataset with entity counts and write times.
  • toolkit.clear_cache(source=, dataset=, ticker=, confirm=) is the only way anything is ever removed. Nothing expires or is evicted on its own, not even when the cache's own internal structure changes between versions — a version mismatch is reported and left alone. An unscoped wipe requires confirm=True. It is deliberately not exposed as an MCP tool.
  • The source names are the same ones enforce_source uses ("FinancialModelingPrep", "YahooFinance", "OECD", "FRED", …), so they mean the same thing in both places.
  • A cache is an optimization and never breaks the caller: a corrupt database, a read-only directory or an unreadable entry disables caching with a warning instead of raising, and every read treats a storage failure as a miss.
  • store() originally spanned three separate connections, so two concurrent writers could both record coverage while the second discarded the first's rows — now a single atomic BEGIN IMMEDIATE transaction under WAL, verified across 8 concurrent processes.

Your FMP subscription plan is part of the cache key for the five endpoints whose response length depends on it, so a Free-plan response can never be served to a Premium caller on a shared database. Cached price history is also only ever spliced together when the same provider served both halves, since a ticker that fell back to the other provider carries different split and dividend adjustments.

Existing cached/*.pickle directories are ignored rather than migrated — the new cache simply rebuilds on first use, and the old folder can be deleted by hand.

Breaking Changes

  • Minimum Python is now 3.11 (was 3.10) and minimum pandas is now 3.0 (was 2.2) — pandas 3.0 itself drops Python 3.10 support, so both floors moved together.
  • get_relative_vigor_index no longer accepts a volumes argument. Its old "volume-weighted" formula algebraically reduced to plain up_sum / down_sum regardless of volume (volume canceled out of both sides of the ratio), so the parameter never actually did anything; it's been replaced with a correct, bounded 0-1 ratio and the dead parameter removed.
  • get_short_term_coverage_ratio now takes short_term_debt instead of accounts_receivable/inventory/accounts_payable — see Bug Fixes.
  • use_cached_data=True no longer restores your previous parameters. It used to reload tickers, start_date, end_date and quarterly from a configurations.pickle, which meant a cached run could not be given a different ticker list or period without first clearing the cache. Those arguments are now always taken from what you pass. This was a correctness bug rather than a feature (see Bug Fixes), but it is listed here because the old behaviour of initializing Toolkit(use_cached_data=True) with no arguments at all and getting your previous session back no longer works.
  • Caching is now off by default on a hosted MCP server (MCP_TRANSPORT=sse or streamable-http); a local stdio server is unaffected. Set FINANCE_TOOLKIT_CACHE_ENABLED=true to opt back in.
  • financetoolkit.utilities.cache_model has been removed, along with the MCP server's own SQLiteCache. Both are replaced by financetoolkit.cache. These were internal modules, so this only matters if you imported load_cached_data/save_cached_data directly.
  • Rates and ratios are decimals everywhere now. get_treasury_rates, the FRED rate methods, the whole Global Macro Database family, the output gap and get_commercial_real_estate_prices previously returned percentage points. 4.25% is now 0.0425, not 4.25.
  • Quarterly statement labels shift for companies whose fiscal quarters end in January/April/July/October — both frequencies now apply the same month-rule relabelling the annual path always had, so a company's quarters actually sum to its annual figures (they previously didn't for these companies). Calendar quarter-enders (the majority) are unaffected.
  • handle_errors raises AttributeError and TypeError where it previously swallowed them into an empty Series. FINANCETOOLKIT_STRICT_ERRORS=1 raises everything.
  • Unreported statement line items are NaN, not 0 — both whole missing rows and, as of this cycle, individual missing cells within an otherwise-reported row on the Yahoo path, which is common for the oldest year of a multi-year statement.
  • Yahoo-sourced non-USD tickers are now currency-converted, where before they silently weren't (Yahoo published no statistics_yf.csv, so Reported Currency was never available for that path).
  • Unadjusted OHLC from Yahoo changes, since auto_adjust is now off — this is the fix that makes Yahoo and FMP agree on Close.
  • smooth_widow is renamed to smooth_window (old spelling deprecated but still accepted).
  • pyyaml moved to the base dependencies — the package root imports it at module scope for Portfolio, so a plain pip install financetoolkit couldn't previously even import the package; it was only pulled in by the mcp extra.

Bug Fixes

Core data plumbing

  • Quarterly statements never had the fiscal-year relabelling the annual path applies (see Breaking Changes above); a company's calendar-year quarters now sum exactly to its annual revenue, an identity that didn't hold before.
  • Four normalized column labels pointed at source keys that no longer exist in either provider's schema and were zero-filled phantoms for every ticker; four labels the ratios/models code reads were entirely missing from the Yahoo vocabulary. All 56 labels the package reads are now available from both providers (40/40 spot-checked against actual 10-K filings).
  • filter_columns only searched the first level of a MultiIndex and silently returned the unfiltered frame on a miss. rounding=0 fell through to the default in 31 places; rounding=None raised outright.
  • FMP caps a response at a fixed row count, not a span, so a capped response runs to the requested end but is short only at the start — this bypassed the existing span-ratio truncation check entirely (AAPL from 2005 came back starting 2006-02-16, 94% of the requested span). Now detected and falls back to Yahoo unless a source is forced.
  • Raw Yahoo statement cells the provider genuinely never reported (common for the oldest year of a partially-reported multi-year statement) were zero-filled instead of left NaN, reintroducing the "unreported = 0" bug for individual cells even after it was fixed for whole missing rows.
  • yfinance's repair=True split-repair heuristic — genuinely useful for real equities, where it catches actual $/cents unit mixups and bad splits — misfires on synthetic instruments that have no real splits: it inflated ^IRX (13-week Treasury) by exactly 100x for every date before its March 2020 crash to near-zero, and blew CL=F (WTI crude) up by 10,000x on the day after oil settled negative. Now scoped off for anything ^-prefixed or containing = (indices, FX, futures) and left on for everything else.
  • get_historical_data()'s cache guard only checked whether the cached frame was empty, not whether enforce_source (or return_column/include_dividends/fill_nan/rounding) changed since the call that populated it — the first call's source won for the Toolkit's whole lifetime, and every later call with different arguments silently got the same cached frame back unless overwrite=True (which then re-fetched everything rather than reacting to what actually changed). Now tracks the params used and auto-invalidates on a mismatch.

Currencies

  • LSE (pence), JSE (cents) and TASE (agorot) quote in a fractional unit, but the FX pair resolved to the major unit. JSE now routes through FMP's native minor-unit ticker; TASE has no equivalent on either provider and now produces an honest warning instead of a silent NaN (a working ticker for a different currency in the same batch was previously suppressing that warning entirely).

Ratios & Models

  • Piotroski F-Score's ΔROA criterion computed the growth rate of ROA growth (comparing this period's YoY ROA growth to last period's), instead of simply comparing current ROA to the prior period as Piotroski's (2000) original F_dROA signal does.
  • get_interest_burden_ratio was computing the interest coverage ratio, not the burden ratio (AAPL FY23: 0.9951 against FMP's own figure, was 29.06). get_free_cash_flow_yield summed share prices instead of averaging them. Three days-based ratios silently dropped their days argument in the trailing branch.
  • Piotroski's F_ACCRUAL and F_ΔLEVER were both mis-specified against Piotroski (2000); an unreported fiscal year scored 0/9 rather than NaN, since every criterion is a boolean and NaN > x evaluates to False. That NaN-vs-zero mask has since been extended twice more this cycle: first to cover all nine criteria's underlying fields (not just the three feeding ROA/CFO/accruals), then to also require the previous period be reported before trusting the five criteria that compare against it — a NaN in period t-1 was still silently scoring period t's change-based criteria as 0 instead of propagating.
  • Fulmer's H-Score returned inf on zero interest expense; Market Value Added averaged the market value of debt, which cancels debt out of the measure entirely. Every published coefficient set (Altman, Ohlson, Zmijewski, Springate, Grover, Fulmer, Beneish) was re-derived from raw statements and matches to ≤5e-11.
  • Three collect_* ratio methods (efficiency, profitability, valuation) silently dropped the caller's trailing argument on one method each, while every sibling in the same table correctly forwarded it. get_price_to_cash_flow_ratio's denominator was rolled up to the trailing window but its numerator wasn't, a numerator/denominator period mismatch.
  • get_net_current_asset_value computed Working Capital (Current Assets − Current Liabilities), not Graham's actual NCAV (Current Assets − Total Liabilities) — a $162bn, sign-flipping error on AAPL 2021. get_asset_coverage_ratio double-subtracted short-term debt, once inside Current Liabilities and again inside Total Debt.
  • The Gordon Growth Model's period-tracking froze one period early, so the true final historical period was valued off a stale projected dividend instead of its own actual reported one — contradicting the method's own documented behaviour.
  • Intrinsic value and the two-stage dividend discount model summed their discounted cash flows with the builtin sum, whose accumulation order (and therefore last-digit result) depends on the Python version. Both now use math.fsum, which is correctly rounded and gives the same answer everywhere.

Performance & Risk

  • Sharpe Ratio was returning the wrong thing entirely: excess_returns / excess_returns.std() divided the whole return series by its own standard deviation instead of dividing the mean by the standard deviation — every "Sharpe Ratio" was actually a series of standardized returns, not a single risk-adjusted number.
  • Sortino Ratio's (and Kappa Ratio's) downside deviation used the wrong denominator — .std() of only the negative returns instead of the root-mean-square of the shortfall below the minimum acceptable return over all observations (Sortino & Price, 1994) — understating downside risk whenever there are a few large losses. M2 Ratio never used the benchmark's standard deviation, the entire point of the M2 rescaling, and was silently computing the plain Sharpe Ratio under the "M2 Ratio" name; it now requires a benchmark_ticker.
  • Fama-French single-factor regression had its arguments swapped (linregress(excess_returns, factor) instead of linregress(factor, excess_returns)), returning the wrong slope, intercept and residuals. The multi-factor variant crashed whenever the factor dataset had missing values, calling .bfill(axis=1) on a pd.Series that doesn't support axis=1. CAPM and Alpha silently returned None on bad input instead of raising TypeError.
  • EWMA (RiskMetrics) Volatility used pandas.Series.ewm().std(), which demeans the series and uses the contemporaneous return, where the RiskMetrics recursion assumes a zero mean and the lagged return — rebuilt directly from that recursion. The Hurst Exponent was systematically doubled (the regression slope already is H for this estimator).
  • Delta-CoVaR re-fit a separate median-quantile regression instead of evaluating the same distress-quantile regression at the conditioning variable's median (Adrian & Brunnermeier 2016, Section II.B). Student-T VaR/CVaR passed loc=1 instead of scale=1 to stats.t.ppf, understating tail risk by roughly 2x; EVaR's formula used std instead of alpha inside the exponential term, ignoring the confidence level entirely.
  • GARCH's log-likelihood paired each return with the wrong period's variance (an off-by-one), which could blow up to ~1e199 and crash the optimizer on zero-return windows; the forecast formula separately double-squared the already-computed long-run variance. GARCH/GJR/EGARCH forecasts were later found to still seed from the last in-sample variance rather than the full sample, so the reported "one-step-ahead" forecast wasn't; the optimizer bound on omega was also six orders of magnitude off the daily optimum.
  • CAGR divided by the observation count rather than compounding intervals (S&P 2015-24: 11.15% → 12.46%, the correct figure). Both market-timing models returned an empty Series for every real Toolkit instance. Four factor-model loops iterated per row, re-running each regression roughly 252 times.
  • Five copula and CoVaR methods defaulted to period="yearly", so a decade of data was ten observations — several of these silently worked around their own broken defaults in the docstring examples rather than raising.
  • get_starr_ratio and the non-rolling branch of get_appraisal_ratio divided a period-scale numerator (excess return, Jensen's Alpha) by a daily-scale denominator (CVaR, CAPM-residual std) with no rescaling, inflating both by roughly √252 (16-30x). GARCH/GJR/EGARCH fits never checked whether the optimizer actually moved off its starting guess before returning it as converged; both now retry once and fall back to NaN on a genuinely stuck fit.
  • Portfolio Volatility was a weighted average of each holding's own volatility, which ignores correlation between holdings and always overstates true portfolio risk unless every pair is perfectly correlated. Now uses the full covariance matrix (w^T Σ w, Markowitz 1952), falling back to the old weighted-average approximation only when a return series isn't available.

Technicals & Options

  • RSI, ATR and ADX used a plain rolling mean instead of Wilder's own smoothing method (a slower recursive average with a 1/window constant) for indicators Wilder specifically defined using that smoothing — one of the most common mistakes when re-implementing these. Added a shared get_wilder_moving_average helper and switched all three (plus DX→ADX smoothing) to use it.
  • Ultimate Oscillator was off by roughly two orders of magnitude — its per-timeframe averages used a rolling mean instead of a rolling sum, and the final weighted combination was missing its ×100 scaling entirely. Ichimoku Cloud's Leading Span A/B were shifted forward by conversion_window instead of base_window. Detrended Price Oscillator's displacement was off by one period and shifted the moving average as well as the close price.
  • Triangular Moving Average's formula was simply wrong (summed prices over the window and divided by (window+1)/2, rather than computing a genuine double-smoothed SMA), and its sub-window length was later found to only be correct for odd windows — the function's own default is even. Aroon Indicator's "periods since extreme" count had an off-by-one error.
  • Force Index used a rolling sum of volume multiplied by a single day's price change instead of Elder's EMA-smoothed raw Force Index. On-Balance Volume and the single-ticker Advancers/Decliners breadth signal divided by abs(price_diff) to derive a sign, which is undefined on any day the price didn't move at all — switched to np.sign().
  • Bollinger Bands used the sample standard deviation where Bollinger's own definition (and TA-Lib) use the population one, inflating the band half-width by 2.6%. Donchian Channels included the current bar in their own high/low window, making a breakout impossible by construction (0 breakouts detected on a series that should have had 129).
  • Parabolic SAR was missing TA-Lib's reversal clamp, letting the stop sit on the wrong side of price for several days right after a trend flip (up to 1.40 off, on 12/500 sampled days). Removed look-ahead bias from Support/Resistance Levels (354/701 values previously revised retroactively as new bars arrived; now covered by a regression test spanning all 55 indicators).
  • Binomial tree option pricing discounted by T / (steps − 1) instead of T / steps (an off-by-one in the per-step discount factor), and had the up/down payoff branches swapped in the backward-induction step. Black-Scholes put Theta was missing a set of parentheses, so the leading negative sign applied only to the formula's first term. Gamma didn't forward dividend_yield into its own internal d1 calculation.
  • get_partial_derivative's docstring claimed to compute the Breeden-Litzenberger risk-neutral density, but used one flat assumed volatility at every strike, which can only ever recover a lognormal density; the new get_risk_neutral_density does it properly by fitting an SVI smile to real market-implied vols first. veta carried the opposite sign to the rest of the Greek surface, and SVI calibration ran a single optimizer start and could silently converge to a degenerate straight line through a real smile while still reporting success.
  • Eleven methods declared a tuple return type but actually return a DataFrame. Several Greeks and Black-Scholes docstrings drifted from their real signatures (get_d2 documented get_d1's stale parameter list; get_dual_gamma/get_vanna documented a put_option parameter that doesn't exist; get_delta/get_lambda/get_vega omitted real dividend_yield/put_option parameters; several used time_to_expiry where the real parameter is time_to_expiration).

Econometrics

  • Event studies didn't validate that pre_event_days <= gap_days, so a badly chosen gap_days could let the estimation window overlap the event window, contaminating the market model's "normal return" estimate. get_out_of_sample_validation duck-typed a .forecast attribute off the raw forecast object rather than reading the documented key, silently returning the entire result dict instead of the forecast itself.
  • A nested closure with no docstring broke the website's regex-based documentation parser, silently dropping the next method in the same file from the generated docs — inside the Diebold-Mariano test (dropping get_ols) and inside get_implied_volatility (dropping get_volatility_surface). Both were moved into proper, documented model functions, and the parser itself has been rebuilt on ast rather than regex — this was still dropping get_gross_domestic_product, collect_bond_statistics and four Risk methods from the published docs.
  • get_vif called add_constant(has_constant="skip"), so a pre-existing constant column shifted every regressor one position left of the index used to look its VIF back up — every value was mislabelled, and the last one raised IndexError. The Ramsey RESET test silently discarded the caller's robust covariance type.

Economics & Fixed Income

  • Macaulay's Duration discounted each coupon by (1 + y/freq)^(t/freq) instead of (1 + y/freq)^t. Bond DV01 had a spurious extra × 0.01 factor on top of the ±1bp yield shift already baked into the price comparison, so every reported DV01 was 100x too small (and sign-flipped); rebuilt on top of get_bond_price.
  • get_house_prices(inflation_adjusted=False) had a copy-paste bug — both branches of the if/else queried the same OECD "real" series, so requesting nominal house prices silently returned real ones. get_short_term_interest_rate silently ignored a class-level gmdb_source=True, always falling through to the OECD path regardless of the source set on the instance.
  • All 22 OECD SDMX queries left their dimensions unpinned. US labour productivity requested a year-over-year growth rate while its own docstring documented a level.
  • get_effective_duration repriced only in the upward direction, inheriting the curvature of the price-yield relationship rather than cancelling it — understated by 2.7% on a 5-year bond and 11.8% on a 30-year. get_bond_equivalent_yield applied the short-bill formula at every maturity, overstating a 52-week bill's yield by roughly 7bp. Black-76 and Bachelier shared a single volatility argument despite needing lognormal versus normal vol respectively — a 20% lognormal vol fed into Bachelier priced it 30.77x too high (exactly 1/forward).

Portfolio & Discovery

  • Passing a DataFrame directly to Portfolio(...) raised, since the guard tested the frame for truthiness — the documented constructor path was completely broken. Weekend and holiday trades were dropped from every position metric. The P&L overview concatenated grouped results positionally, misplacing figures whenever two trades shared a date. The benchmark was replicated in equal share counts rather than matched cash flows, so alpha was never genuinely like-for-like.
  • Five discovery methods pointed at retired FMP endpoints and raised on every call. Portfolio Invested could go negative after a profitable partial exit.
  • The transaction sort used the default non-stable quicksort, so same-date transactions could land in a different relative order than the source file — the FIFO/LIFO cost-basis walk depends on that order to compute realized PnL correctly; now a stable sort.

MCP Server

  • MCP router tools baked the first-inspected indicator's parameter defaults into the schema shared by the whole group (98 of 2,325 parameter entries were wrong, now 0). The MCP response cache key dropped list-valued kwargs, so lag=[1,2] and lag=[2,3] collided. The Ken French cache policy was registered under its pre-rename key, causing a daily re-download of the archive instead of weekly.
  • financetoolkit-mcp --help previously ignored the flag entirely and started the server instead of printing help, since the entry point never parsed its command-line arguments. Both it and the inspector now have a real argument parser; transport/host/port can be passed as flags and still fall back to MCP_TRANSPORT/MCP_HOST/MCP_PORT, so existing client configs are unaffected.

Caching (the previous, now-replaced system)

  • The cache silently overwrote the parameters you asked for. Toolkit(use_cached_data=True) reloaded tickers, start_date, end_date and quarterly from a configurations.pickle and applied them over the arguments you had just passed, so a second run with a different ticker or period quietly analysed the first run's companies and dates instead.
  • The cache never updated once written — save_cached_data returned early if the target file already existed, so a dataset written once was frozen and refetched from scratch on any parameter change. The OECD had its own separate file cache with module-global state that no other module shared or could clear.
  • All three of these are moot with the rebuild described under Caching above, which replaces the whole mechanism rather than patching it.

Documentation

A correctness pass over the docstrings themselves, since they are the reference material on the website and the source of every MCP tool description, across both audit rounds. Roughly 115 defects were found and fixed combined; the ones that could actually mislead:

  • Stated formulas that contradicted the code. The Ulcer Index formula (SQRT(SUM[(Pn / Highest High)^2] / n)) evaluates to ~1 for any series — the code correctly uses (Pn - Highest High) / Highest High. Dollar Duration omitted the /100 the code applies. Modified Duration's formula was only correct at frequency=1, and was falsely equated with DV01. Phillips-Perron's Z_t had the wrong denominator. A simply-wrong extended-DuPont formula, an inverted EQ_OFFER interpretation, an inverted Enterprise Value interpretation, Ohlson's cutoff documented 10x off (0.38 vs the real 0.038), several options Greek formulas with N/N' swapped, and an inverted Theta interpretation.
  • Methods documented as doing something they don't. get_yield_to_maturity claimed Newton-Raphson (it's the secant method); get_arima_forecast claimed Conditional Sum of Squares "as a deliberate limitation" (it's exact MLE via the Kalman filter); get_cusum_test described recursive residuals under a Brownian motion null citing Brown-Durbin-Evans (it's OLS residuals under a Brownian Bridge, Ploberger-Kramer). get_ice_bofa_effective_yield described current yield, and the ICE BofA total-return and yield-to-worst links pointed at entirely different FRED series than the ones fetched.
  • Whole docstrings left over from copy-paste: get_carbon_footprint described environmental taxes, get_kurtosis described CVaR throughout, get_rent_prices described the price-to-rent ratio rather than the rent index it returns.
  • Args: blocks that didn't match the signature — roughly 15 documented parameters that don't exist (alpha, trailing, t, dataset, per_capita), omitted real ones, or stated the wrong default.
  • period defaults across Risk, Performance and Econometrics. 114 methods documented a hard default ("yearly" in Risk, "quarterly" in Econometrics) while the code resolves period to the Toolkit's own quarterly/yearly setting. Around 50 of those also omitted monthly from their list of accepted values despite validating against it. Technicals is unaffected — its period genuinely defaults to "daily".
  • Several stale "Which returns" example tables that had never been regenerated after earlier fixes landed (still showing the pre-fix numbers for ROIC, capex coverage, capex-dividend coverage and the Hurst Exponent) have been re-run against current code.

The website documentation also gains a dedicated Econometrics page, which the README already linked to, plus the matching Econometrics notebook. The headline figure is now 500+ methods, applied consistently across the README, server.json, the MCPB manifest, the MCP tool metadata, the class docstrings, every example notebook and the website — the long-standing "200+" understated it by more than half, given the toolkit documents 522 methods and the MCP server reaches 476 of them. The wording changed with it: these are methods, not "financial ratios, indicators and performance measurements", since ratios are one module out of twelve. The MCP page's tool tables were also still listing the old get_-prefixed tool names (get_valuation_ratios rather than valuation).

Test Coverage

New test suites for the Econometrics module (14 files covering every estimator category), the five new Models bankruptcy scores (Fulmer, Grover, Ohlson, Springate, Zmijewski), Fixed Income's bond and yield curve models, and Risk's new backtesting, copula, CoVaR, market-liquidity and realized-volatility models. Expanded coverage across Technicals (momentum, overlap, volatility, controller) and Ratios/Performance/Risk for the formula fixes described above, so the corrected values are locked in going forward.

A new tests/cache/ suite covers the caching rebuild: the interval algebra, per-ticker splitting, scoped removal, the Toolkit's own cache methods, and one file per family of data source verifying that a warm request makes no external call and a widened one requests only the gap. It also covers the failure modes specifically — a corrupt database, a read-only directory, a corrupted payload, twelve concurrent writers, two processes sharing one file, and a schema-version bump — all of which have to degrade to "no caching" rather than raise.

The stored-output tests now compare CSV records numerically instead of as exact strings: a value is equal if it is within one unit of the last recorded decimal, or within 1e-5 relative. Shape, headers and text still have to match exactly. Iterative estimators (ARIMA forecasts, the GARCH family) walk to slightly different optima on different platforms, so the previous exact-string comparison made the suite pass or fail depending on which machine had recorded the expected values.

The suite grew from 1,353 to 1,475 passing tests across the two audit rounds. tests/economics/ previously asserted only "does not raise" on all 68 of its tests, which is exactly why the OECD unemployment mislabelling survived as long as it did — those tests now assert real values reconciled against BLS/FRED.

MCP Server

  • New econometrics tool group registered in config.yaml, alongside the existing per-module tool groups. The financetoolkit[mcp] extra now pulls in financetoolkit[econometrics] as well, so statsmodels/linearmodels ship with every MCP install and the econometrics tools work out of the box — no client config change needed.
  • The macroeconomics tool group's description and method list updated to cover the new FRED-backed indicators (retail sales, industrial production, housing starts, real personal income, recession indicator) and OECD household savings/debt-to-income methods.
  • FRED API key resolution (header/query/JWT, mirroring the existing FMP key path) wired through to Economics and FixedIncome over MCP — previously the key was never passed through this path at all.
  • The server's own SQLiteCache is gone, replaced by the same financetoolkit.cache the library uses. Tool responses are still cached whole under their own source, but the data underneath them now benefits from — and contributes to — the shared per-ticker cache, so a tool call is warmed by anything a co-located library session already retrieved. Eviction of tool responses is scoped to that source so it cannot take the accumulated price history down with it.
  • Caching defaults to off when the server is hosted. cache.enabled: auto in config.yaml resolves to on for stdio (a local server is one user on one machine) and off for MCP_TRANSPORT=sse/streamable-http. A hosted server serves every user from one process against one database, where a shared entry would answer one user's request with another subscriber's paid data, and retrieved source data has no eviction policy that would keep the disk bounded. FINANCE_TOOLKIT_CACHE_ENABLED=true|false overrides it either way, and an explicit boolean in config.yaml beats the transport heuristic. When it is off, no database file is opened at all — the Toolkit and Discovery instances the server builds are opted out too, not just the tool-response layer.
  • Six metrics that the toolkit exposes but the server could not reach are now registered, taking the reachable total to 476. get_producer_price_index was missing from the macroeconomics list; get_interest_burden_ratio, get_tax_burden_ratio, get_reinvestment_rate, get_support_resistance_levels and get_volatility_cone were invisible because their tool group discovers its methods by scanning a collect_* helper that doesn't call them. Those groups now list their methods explicitly. collect_bond_statistics was likewise neither exposed nor skipped, and now joins the other collect_* helpers in skip_methods.
  • MCP router tools baked the first-inspected indicator's parameter defaults into the schema shared by the whole group (98 of 2,325 parameter entries were wrong, now 0) financetoolkit-mcp --help previously ignored the flag entirely and started the server instead of printing help, since the entry point never parsed its command-line arguments; both it and the inspector now have a real argument parser.

Method note

Findings were only accepted where they could be demonstrated, not just argued for — against a reference library (TA-Lib, arch, statsmodels/linearmodels, py_vollib) where one exists, against live data from the source (FMP, Yahoo, FRED, OECD, ECB, NY Fed) reconciled to published BLS/BEA/Treasury/Ken French figures, or by hand: Monte Carlo against analytic ground truth, central finite differences of a pricer plus put-call/in-out parity, re-derivation of published coefficients from raw statements, and hand-computed FIFO walkthroughs. Several proposed findings were investigated and rejected rather than fixed: TA-Lib's own ADX disagrees with the toolkit by 18.6, but a line-by-line port of ta_ADX.c and the ta library both agree with the toolkit, so TA-Lib was the outlier there — and the same pattern repeated with CMO, where TA-Lib's Wilder-smoothed version diverges from Chande's own 1994 formula, which is what the toolkit (correctly) implements. The KAMA seeding "fix" proposed during the first audit round was reverted once TA-Lib was found to back the existing code.

Full comparison: v2.1.4...v2.2.0

v2.1.4

14 July 2026

This is one of the larger feature releases to date. It roughly doubles the depth of three modules — Models, Performance, and Risk — and rounds out Technicals, Ratios, and Discovery with metrics that were previously missing.

Two capabilities now cut across nearly the whole toolkit:

  • rolling and trailing windows. Many metrics used to return one value per reporting period. They can now be computed over a sliding window (rolling=<n>) or a trailing sum/average (trailing=<n>), turning a snapshot into a proper time series.
  • standardize (Z-Score). Most get_* methods across Economics, Ratios, Technicals, Risk, Performance, Models, Options, and Fixed Income now accept standardize=True. It converts raw values into standard deviations from their own historical mean, so metrics on completely different scales become directly comparable — useful for ranking, scoring, or spotting an unusual reading at a glance.

On the fix side: swaption prices are discounted correctly now, a case-mismatch bug that was silently zeroing out diluted EPS is gone, and the new Forward P/E / Forward PEG ratios cache analyst estimates properly instead of double-fetching.

Volatility, Excess Return, and Excess Volatility are gone from toolkit.get_historical_data(). Use these instead:

  • toolkit.risk.get_volatility(period=...)
  • toolkit.risk.get_excess_volatility(period=...)
  • toolkit.risk.get_variance(period=...)
  • toolkit.performance.get_excess_return(risk_free_rate=..., cumulative=...)

Every method below hangs off the matching Toolkit sub-module (e.g. toolkit.models.get_graham_number()) or its standalone class (Discovery(...), Economics(...), FixedIncome(...)). Full runnable examples with real output live in the documentation — each section below links to its module's page.

New Features

Standardization (Z-Score)

standardize: bool = False is now available on nearly every controller — Economics, Ratios, Technicals, Risk, Performance, Models, Options, and Fixed Income, roughly 270 methods in total.

Z-Score = (value - mean) / standard deviation

Mean and standard deviation come from each series' own history: per ticker for entity-indexed data like ratios, per column for date-indexed data like economic indicators. With growth=True, it standardizes the growth values instead of the raw ones. Use it to compare metrics that live on incompatible scales, build a quick cross-sectional ranking straight from toolkit output, or spot when a current reading is an unusual number of standard deviations from its own norm.

Financial Models

Call these via toolkit.models.<method>(). Full examples: docs/models.

get_economic_value_added (EVA, economic profit) — whether a company earns more than its true cost of capital, something Net Income alone can't tell you.

  • NOPAT = EBIT × (1 − Effective Tax Rate)
  • Invested Capital = Total Equity + Total Debt (each smoothed as a 2-period average, or a trailing-period average, to soften a single noisy balance-sheet snapshot)
  • EVA = NOPAT − (WACC × Invested Capital)
  • Read it as: positive EVA creates value for capital providers; negative EVA destroys it, even in periods where net income is positive.

get_beneish_m_score (earnings manipulation score) — Messod Beneish's model for flagging likely earnings manipulation, a companion to the Altman Z-Score and Piotroski F-Score already in the toolkit.

  • M-Score = -4.84 + 0.92·DSRI + 0.528·GMI + 0.404·AQI + 0.892·SGI + 0.115·DEPI − 0.172·SGAI + 4.679·TATA − 0.327·LVGI
  • Each of the eight inputs is its own function in beneish_model.py: get_days_sales_in_receivables_index (DSRI — receivables outgrowing sales), get_gross_margin_index (GMI — margin deterioration), get_asset_quality_index (AQI — a rising share of non-core assets), get_sales_growth_index (SGI — fast growth raises manipulation pressure), get_depreciation_index (DEPI — a slowing depreciation rate flatters earnings), get_selling_general_and_administrative_expenses_index (SGAI), get_leverage_index (LVGI), and get_total_accruals_to_total_assets (TATA — the accrual share of earnings, a red flag across most accounting-fraud models).
  • Read it as: above roughly -1.78, manipulation is more likely; below it, less likely. It's probabilistic, not a verdict — pair it with real fundamental analysis. The first period is always NaN since every input needs a prior period to compare against.
  • Reference: Beneish, M. D. "The Detection of Earnings Manipulation." Financial Analysts Journal, Vol. 55, No. 5, 1999, pp. 24-36.

get_sustainable_growth_rate (SGR) — the fastest a company can grow revenue on internal funds alone, without new equity or added leverage.

  • SGR = Return on Equity × (1 − Dividend Payout Ratio)
  • Read it as: growing faster than SGR without outside financing means improving margins, cutting the payout, or taking on more debt — so actual growth versus SGR is a quick tell for how a company is funding its expansion.

get_internal_growth_rate (IGR) — a stricter version of SGR: growth funded from retained earnings only, with no debt added at all.

  • IGR = (ROA × Retention Ratio) / (1 − (ROA × Retention Ratio))
  • Read it as: IGR is always below SGR for a levered company. The gap between them is roughly how much of that company's "sustainable" growth actually depends on debt.

get_graham_number (Graham fair value) — Benjamin Graham's conservative ceiling on what a defensive investor should pay.

  • Graham Number = √(22.5 × EPS × Book Value per Share)
  • Read it as: most useful for stable, profitable companies with positive book value. Negative earnings or book value produce NaN (the square root of a negative number is undefined) — comparing the current price against this number is a quick margin-of-safety check.
Ratios

Call these via toolkit.ratios.<method>(). Full examples: docs/ratios.

Efficiency

  • get_research_and_development_ratio, get_selling_and_marketing_ratio, get_general_and_administrative_ratio — R&D, S&M, and G&A each as a share of Revenue. Most companies only report these lumped into SG&A; splitting them out lets you compare R&D intensity or customer-acquisition spend independent of admin overhead.
  • get_stock_based_compensation_ratio — SBC ÷ Revenue. A high or rising number is a quality-of-earnings flag, since SBC gets added back in cash flow from operations (flattering FCF) while still diluting existing shareholders.
  • get_deferred_revenue_ratio — Deferred Revenue ÷ Revenue. A leading indicator for subscription/SaaS businesses: a growing balance here signals revenue that hasn't hit the income statement yet.

Profitability

  • get_cash_tax_rate — taxes actually paid in cash ÷ Income Before Tax, versus the accrual-based Effective Tax Rate.
  • get_tax_rate_divergence — Cash Tax Rate minus Effective Tax Rate. Persistently positive means more cash tax paid than expensed (e.g. deferred liabilities unwinding); persistently negative can flag aggressive tax deferral.

Solvency

  • get_debt_to_capital_ratio — Total Debt / (Total Debt + Total Equity). Stays between 0 and 1, unlike Debt-to-Equity, which makes capital structure easier to compare across companies.
  • get_preferred_dividend_coverage_ratio — Net Income ÷ |Preferred Dividends|: how many times earnings cover the obligation to preferred shareholders.
  • get_interest_paid_to_expense_ratio — Interest Paid ÷ Interest Expense. Well below 1 suggests interest is being accrued rather than paid (e.g. payment-in-kind debt); well above 1 suggests catch-up payments or a cash/accrual timing gap.

Valuation

  • get_ev_to_free_cash_flow_ratio — Enterprise Value ÷ Free Cash Flow, a multiple that (unlike EV/EBITDA) accounts for capex and working capital.
  • get_buyback_yield — -(Repurchases + Issuances) / Market Cap. Positive means the company is a net repurchaser; negative means it's a net issuer, diluting shareholders.
  • get_shareholder_yield — Dividend Yield + Buyback Yield: total cash returned to shareholders through both channels.
  • get_sbc_adjusted_free_cash_flow — Free Cash Flow minus Stock-Based Compensation, treating SBC as the real cost it is instead of the non-cash add-back FCF normally lets it be.
  • get_forward_price_earnings_ratio (Forward P/E) — Stock Price / Estimated EPS Average, using the analyst consensus estimate for a future period instead of trailing EPS. Needs a Premium FMP subscription; estimates are fetched once per Toolkit instance and cached automatically, so there's no need to call get_analyst_estimates() first.
  • get_forward_price_earnings_growth_ratio (Forward PEG) — Forward P/E / (Estimated EPS Growth Rate × 100), where growth bridges the analyst estimate to the company's most recent actual EPS (get_estimated_eps_growth_rate, its own reusable function) rather than comparing two historical periods the way growth=True does everywhere else. Read it as: near or below 1 is the classic (simplistic) heuristic for fairly priced growth; well above 1 means the market is paying a premium for it.
Technical Indicators

Call these via toolkit.technicals.<method>(). Full examples: docs/technicals.

Overlap

  • get_weighted_moving_average (WMA) — weights recent prices more, so it tracks price more closely than a Simple Moving Average while staying smoother than an Exponential one.
  • get_hull_moving_average (HMA) — combines a half-window WMA, a full-window WMA, and a √window WMA specifically to cut moving-average lag without giving up smoothness.
  • get_volume_weighted_average_price (VWAP) — typical price weighted by volume over a rolling window; the benchmark most execution algorithms are measured against.
  • get_parabolic_sar — a trend-following stop-and-reverse level that flips sides when the trend reverses, with an acceleration factor (af_start/af_increment/af_max, defaults 0.02/0.02/0.2) that speeds convergence as a trend runs longer. Commonly used to trail stop-losses.
  • get_pivot_points — Pivot Point plus Resistance/Support 1-3, derived from the prior period's high/low/close to flag likely next-period levels.

Volatility

  • get_donchian_channels — highest high and lowest low over a rolling window, with the midpoint as the middle line; spots breakouts and shows how wide the recent range has been.
  • get_volatility_cone — the historical percentile spread (min through max, plus current) of annualized realized volatility across several lookback windows ([10, 20, 30, 60, 90, 120] by default). Shows at a glance whether current volatility is cheap or expensive versus its own history — often used before comparing to options-implied volatility.

Breadth (cross-sectional across tickers at a point in time, not per-ticker over time)

  • get_trin (Arms Index) — (Advancing Issues / Declining Issues) / (Advancing Volume / Declining Volume). Below 1 suggests volume conviction is outpacing the number of advancing names (bullish); above 1 suggests the reverse.
  • get_new_highs_new_lows — tickers at a window-period high minus tickers at a window-period low: a read on how broad a market move really is beneath the index-level headline.
Performance

Call these via toolkit.performance.<method>(). Full examples: docs/performance.

  • get_calmar_ratio — Return / |Maximum Drawdown|. Penalizes purely by the single worst peak-to-trough loss, not by volatility the way Sharpe/Sortino do.
  • get_sterling_ratio — Return / (|Average Drawdown| + adjustment) (adjustment defaults to 10%), using the average of all drawdowns rather than just the worst one — softer and less driven by a single event than Calmar.
  • get_burke_ratio — Excess Return / Burke Drawdown Measure, where the measure is √(Σ drawdown²) (new get_burke_drawdown_measure). Squaring before summing penalizes both frequency and depth of drawdowns, so two strategies sharing a max drawdown can still score very differently here.
  • get_upside_capture_ratio / get_downside_capture_ratio — the asset's average return versus the benchmark's, split across periods where the benchmark was positive or negative. Upside capture above 1 and downside capture below 1 is the profile most investors want: gaining more in rallies than losing in selloffs.
  • get_win_rate — the share of periods where the asset beat the benchmark. Simple, distribution-free complement to the capture ratios.
  • get_kappa_ratio (default order=3) — Sortino generalized to a higher-order lower partial moment; Sortino itself is the order=2 case. Higher orders punish larger losses more, making Kappa more tail-sensitive than Sortino.
  • get_omega_ratio (default minimum_acceptable_return=0.0) — gains above a minimum acceptable return divided by losses below it, using the full return distribution rather than just mean and variance — so it captures skew and fat tails that Sharpe/Sortino miss.
  • get_gain_to_pain_ratio — Σ all returns / Σ |losses|. A blunt, easy-to-explain measure of gain earned per unit of pain endured.
  • get_returns / get_excess_return now take a cumulative parameter (pulled out of get_historical_data, see Breaking Changes) — cumulative=True compounds returns into a running index instead of period-over-period values.
  • Rolling variants — get_rolling_alpha, get_rolling_sortino_ratio, get_rolling_m2_ratio, get_rolling_tracking_error, get_rolling_information_ratio, plus rolling support on Beta, CAPM, Jensen's Alpha, and Treynor Ratio. Pass rolling=<window> to see risk-adjusted performance evolve through time instead of getting one backward-looking number.
Risk

Call these via toolkit.risk.<method>(). Full examples: docs/risk.

  • get_conditional_drawdown_at_risk (CDaR) — extends VaR/CVaR from returns to drawdowns: DaR is the alpha-quantile of the drawdown distribution, CDaR is the average of drawdowns at least that severe. Where VaR/CVaR ask "how bad could one period be," CDaR asks "how bad could the cumulative peak-to-trough loss get."
  • get_tail_ratio — |percentile(1-alpha)| / |percentile(alpha)| of returns. Above 1 means best-case gains outsize worst-case losses — a quick complement to skewness that doesn't assume a distribution shape.
  • get_maximum_drawdown_duration — periods between the peak and trough of the single largest drawdown: how long the worst decline took to play out.
  • get_maximum_drawdown_recovery_time — periods from that trough until cumulative return hits a new high (NaN if it hasn't yet). Paired with duration, this gives the full timeline of a strategy's worst stretch.
  • get_downside_deviation (semi-deviation, default minimum_acceptable_return=0.0) — standard deviation of only the returns below a minimum acceptable return, so upside swings no longer count against the metric the way they do in plain standard deviation.
  • get_mean_absolute_deviation (MAD) — mean absolute distance from the mean return. No squaring, so a handful of outliers move it less than they'd move variance.
  • get_coefficient_of_variation (CV, relative standard deviation) — standard deviation / mean of returns, which lets you compare relative volatility across assets with very different average returns — something raw standard deviation can't do.
  • get_ewma_volatility (RiskMetrics volatility, default lambda_=0.94) — EWMA Variance(t) = λ·EWMA Variance(t-1) + (1-λ)·Return(t-1)². Weights recent observations more, so it reacts to a changing volatility regime faster than a fixed rolling window, while staying much simpler than a full GARCH fit.
  • get_autocorrelation (default lags=10) — correlation between a series and its own lagged values; usually the first thing checked before deciding how many AR/MA terms a series needs.
  • get_hurst_exponent (default max_lag=20) — estimated via rescaled range (R/S). H < 0.5 mean-reverting, H = 0.5 random walk, H > 0.5 trending — a single number for whether a series tends to trend or revert.
  • Extreme Value Theory tail modelling — get_value_at_risk(distribution="evt") now fits a Generalized Pareto Distribution to the worst losses via Peak-over-Threshold (new get_var_evt, plus a threshold_percentile parameter, default 0.95, for how much of the tail to fit on). Models the tail's actual shape instead of assuming the whole distribution (Gaussian, Cornish-Fisher, Student-t) represents extreme outcomes well.
  • get_volatility / get_variance / get_excess_volatility are now first-class Risk methods (pulled out of get_historical_data, see Breaking Changes).
  • Rolling variants — get_rolling_var_historic, get_rolling_cvar_historic, get_rolling_variance, get_rolling_volatility, get_rolling_excess_volatility, get_rolling_tail_ratio, get_rolling_conditional_drawdown_at_risk, get_rolling_skewness, get_rolling_kurtosis, get_rolling_downside_deviation, get_rolling_omega_ratio — same sliding-window idea as Performance, across Risk.
Economics

Call these via Economics(...).get_*(), or toolkit.economics.<method>() on a Toolkit instance. Full examples: docs/economics.

  • rolling and trailing parameters now cover essentially the whole module — GDP, CPI, inflation, trade, investment, consumption, confidence indices, government fiscal metrics, interest rates, unemployment, population, and more (45 methods). rolling=<n> smooths noisy monthly/quarterly prints with a simple moving average; trailing=<n> sums over a trailing window (e.g. a trailing 4-quarter sum to annualize a quarterly flow). Both apply before any growth/standardize step.
Discovery & News

Call these via Discovery(...).get_*() / search_*(), or toolkit.discovery.<method>() for the ticker-scoped ones. Full examples: docs/discovery.

  • On the Toolkit itself: get_stock_news(pages, limit) and get_press_releases(pages, limit) — ticker-scoped, filtered automatically to the Toolkit's start_date/end_date.
  • In Discovery, not ticker-scoped: get_stock_news, get_general_news (broad market news), get_press_releases, get_crypto_news, get_forex_news, plus free-text search via search_stock_news, search_press_releases, search_crypto_news, search_forex_news.
  • Corporate events & calendars: get_ipo_calendar, get_ipo_disclosures (SEC pre-IPO filings), get_ipo_prospectuses (S-1/424B4 pricing), get_stock_splits_calendar, get_mergers_acquisitions_latest (recent deals with acquirer/target and a link to the SEC filing).
  • Sector & industry data: get_sector_performance / get_industry_performance and get_sector_pe / get_industry_pe — pass date for a snapshot across everything, or sector/industry for one name's history. Good for checking whether a move was sector-wide or idiosyncratic, or whether a sector looks rich or cheap against its own P/E history.
Fixed Income

Call this via FixedIncome().get_derivative_price(...). Full examples: docs/fixedincome.

  • tenor and payment_frequency parameters on get_derivative_price — see Bug Fixes above; this is what makes swaption pricing account for the underlying swap's full payment schedule instead of treating it as a single-date payout.

Bug Fixes

  1. Swaption pricing was missing the annuity leg. get_black_price and get_bachelier_price used to discount the option payoff with a single factor to the expiration date, as if exercising a swaption paid out once. It doesn't — it grants the right to enter a swap that pays out at every payment date over the swap's tenor. Both functions now multiply by an annuity factor (the sum of discount factors across those payment dates) via a new _get_annuity_factor() helper. Two new parameters, tenor and payment_frequency, let you set the underlying swap's length and payment schedule separately from the option's own expiration. Previously tenor had zero effect on price; now a 1-year option into a 5-year swap correctly prices roughly 5x higher than one into a 1-year swap, since it covers five times as many payment dates.

  2. trailing rolled the wrong axis when combined with show_daily. get_enterprise_value, get_market_cap, and related valuation ratios rolled the trailing window across tickers instead of across dates whenever both parameters were active together.

  3. trailing did nothing in get_market_cap. Its if/else branches were identical, so the parameter was silently ignored.

  4. Cumulative return broke on gappy data. (1 + returns).cumprod() became (1 + returns.fillna(0)).cumprod() in historical_model.py and risk_model.py, with .replace([np.inf, -np.inf], np.nan) added before the product to stop infinities from propagating through the series.

  5. Silenced a pandas FutureWarning. Added future_stack=True to stack() calls in the performance controller ahead of pandas' default-behaviour change.

  6. Fixed a type annotation. pd.PeriodIndex corrected to pd.DatetimeIndex in a helpers.py signature.

  7. Risk methods ignored the requested date range. get_value_at_risk, get_conditional_value_at_risk, get_entropic_value_at_risk, get_conditional_drawdown_at_risk, get_tail_ratio, get_maximum_drawdown, get_maximum_drawdown_duration, get_maximum_drawdown_recovery_time, get_ulcer_index, get_garch, get_skewness, get_kurtosis, and get_variance could silently return data outside start_date/end_date, especially with rolling or within_period set. All now truncate correctly.

  8. A one-character typo zeroed out diluted EPS everywhere. financetoolkit/normalization/income.csv mapped FMP's field as epsdiluted (lowercase), but the stable endpoint actually returns epsDiluted (capital D). Normalization fills any expected-but-missing column with 0 before renaming, so this mismatch meant get_income_statement() always reported "EPS Diluted" as zero — the real column was silently dropped instead of renamed. It stayed invisible until the new Forward PEG ratio started reading that field directly, at which point it returned exactly 0.0 for every ticker, every period. Fixed by correcting the key to epsDiluted.

  9. Forward-looking ratios fetched analyst estimates twice instead of caching once. get_forward_price_earnings_ratio() and get_forward_price_earnings_growth_ratio() are meant to fetch Premium-only analyst estimates once and reuse them. The cache lived on the Ratios instance, but toolkit.ratios builds a brand-new Ratios instance on every access — so calling both methods back to back (exactly what the docs show) fetched estimates twice, doubling Premium API usage for nothing. Fixed by sharing a mutable cache dict from the Toolkit instance into every Ratios instance it builds, so the fetch-once behaviour survives across calls for the life of the Toolkit object.

  10. Log messages were mis-pluralized. "Obtaining %s data for %d tickers" now reads "...for %d ticker(s)", so single-ticker runs no longer say "for 1 tickers".

  11. Local dev setup was missing MCP dependencies. The dev dependency group in pyproject.toml didn't pull in the project's own mcp extra, so a plain uv sync left fastmcp/pydantic and friends missing. Added "financetoolkit[mcp]" to dev plus a [tool.uv.sources] workspace entry.

Test Coverage

New coverage for the Risk module's new metrics (test_cvar_model.py, expanded test_risk_controller.py, test_risk_model.py, test_var_model.py), the new technical indicators (Donchian Channels, Hull Moving Average, New Highs/New Lows, Parabolic SAR, Pivot Points, TRIN, VWAP, Weighted Moving Average, Volatility Cone), and the internal helpers.py split (test_dataframe_model.py, test_requests_model.py, test_statistics_model.py). Added missing snapshot tests for collect_custom_ratios, get_cash_conversion_efficiency, get_effective_tax_rate, get_debt_service_coverage_ratio, get_weighted_dividend_yield, get_reinvestment_rate, get_ev_to_ebit, collect_all_metrics (performance + risk), get_compound_growth_rate, and get_estimated_eps_growth_rate. Updated snapshots for valuation methods affected by the trailing/show_daily axis fix. Added httpx2 as a dev dependency to resolve a StarletteDeprecationWarning in MCP OAuth tests.

MCP Server

  • Tool/category descriptions in config.yaml and parameter descriptions in registry_controller.py updated to cover all of the above: rolling/trailing on Economics, the new standardize/cumulative/threshold_percentile/minimum_acceptable_return params, the new Risk and Performance metrics, and the new Models functions.
  • The valuation tool group now explicitly lists get_forward_price_earnings_ratio and get_forward_price_earnings_growth_ratio via a method_override entry. They're deliberately excluded from the bulk collect_valuation_ratios scan — including them there would trigger a Premium-only analyst-estimates fetch on every bulk request, even for free-tier users — so normal method discovery can't find them on its own.
  • MCPB manifest and build script updated to match.
  • Removed an unused get_stock_quotes function from discovery_model.py — dead code, since fmp_model.get_quote already covers per-ticker real-time quotes.

Full comparison: v2.1.3...v2.1.4

v2.1.3

27 June 2026

Minor release with mostly bug fixes and some minor enhancements.

Bug Fixes

  1. Corrected trailing rolling axis for valuation ratios: The show_daily and trailing combination in get_enterprise_value, get_market_cap, and related valuation ratios was applying the rolling window on the wrong axis (tickers instead of dates), producing incorrect results when both parameters were active simultaneously.

  2. Resolved trailing parameter having no effect in get_market_cap: The if/else branches for trailing were identical, meaning the parameter was silently ignored regardless of what was passed.

  3. Fixed cumulative return calculations for edge case data: Replaced (1 + returns).cumprod() with (1 + returns.fillna(0)).cumprod() across historical_model.py and risk_model.py, and added .replace([np.inf, -np.inf], np.nan) before cumulative product computation to prevent inf propagation when input data contains gaps or anomalies.

  4. Resolved pandas FutureWarning in performance controller: Added future_stack=True to stack() calls in performance_controller.py to silence the upcoming default behaviour change in pandas.

  5. Fixed type annotation in helpers.py: Corrected pd.PeriodIndex to pd.DatetimeIndex in a function signature.

New Features

  1. trailing parameter for Models: Added a trailing parameter to the Models sub-module (e.g. get_weighted_average_cost_of_capital). When supplied, financial statement inputs are rolled over the trailing period before calculation, enabling TTM-style model outputs consistent with the same parameter in Ratios and Performance.

  2. trailing parameter for Ratios: Valuation ratios (P/E, P/B, free cash flow yield, price-to-earnings, etc.) now accept an explicit trailing parameter. Previously, quarterly data defaulted unconditionally to trailing=4; the parameter now allows overriding or disabling that behaviour.

Test Coverage

Added missing snapshot tests for: collect_custom_ratios, get_cash_conversion_efficiency, get_effective_tax_rate, get_debt_service_coverage_ratio, get_weighted_dividend_yield, get_reinvestment_rate, get_ev_to_ebit, collect_all_metrics (performance + risk), and get_compound_growth_rate. Updated snapshots for valuation methods affected by the trailing and show_daily axis fixes. Added httpx2 as a dev dependency to resolve StarletteDeprecationWarning in MCP OAuth tests.

MCP Server

Updated MCPB manifest and build script to reflect the latest configuration. Removed conflicting description remarks from the registry and tools model.

Full comparison: v2.1.2...v2.1.3

v2.1.2

23 June 2026

Added many improvements to the core library but also to the performance of the related MCP server.

Core Additions
  • Included a year more data on each start_date request: this makes it possible to e.g. if you are looking for 2015-2026 data, metrics that are calculated based on the average of two balance sheet statement items (such as Return on Equity) don't have an empty column to start with. Same goes for when calculating growth metrics.
  • Fiscal year → calendar year normalisation: Companies with non-calendar fiscal years are now remapped to the corresponding calendar year, enabling consistent cross-company comparisons when mixing tickers (e.g. a company with a March fiscal year end is assigned to the correct calendar year). This is common practice to allow for company comparisons.
  • Added show_columns filtering: allows to be more selective with your calls e.g. by adding show_columns=['Revenue'] to the income statement call gets you only revenues.
  • Replaced tqdm with logger statements: Progress bars removed across all data-fetching modules (fmp_model, yfinance_model, historical_model, fundamentals_model, currencies_model, portfolio_model, options). Replaced with structured logger.info calls. tqdm removed as a dependency.
MCP Server
  • Changed response from markdown tables to JSON: this strongly improves the speed of the LLM's response given that it can parse these type of tables better.
  • Transformation notes in responses: MCP responses now include a _notes key when data transformations were applied, surfacing fiscal year remapping and currency conversions transparently to the LLM.
  • Column filtering (show_columns): All MCP tools now support a show_columns parameter to narrow the returned columns post-computation, reducing response size and token usage.
  • Removed rounding from MCP layer: Rounding is no longer applied server-side; the LLM is responsible for formatting.
  • Removed SKILL.md routing: Simplified MCP server startup, tool dispatch no longer depends on a SKILL.md file, reducing startup complexity.

v2.1.0

9 June 2026

Many new improvements have been made this release as over 13.000 lines of code are added and 112 files have been changed. See for a complete rundown of all changed files the PR #215.

MCP Server

The Finance Toolkit now ships with a Model Context Protocol (MCP) server, making it possible to use all 200+ financial metrics directly inside AI assistants such as Claude Desktop, Cursor, and any other MCP-compatible client.

What's included:

  • A guided setup wizard (financetoolkit-mcp-setup) that auto-configures Claude Desktop, Cursor, and other clients and stores your API keys securely.
  • An interactive inspector (financetoolkit-mcp-inspector) for testing tools before connecting them to a client.
  • A built-in SKILL prompt that instructs the AI how to call the right tools, chain requests efficiently, and interpret financial results.
  • Improved logging (stderr), cache path handling, and .env auto-loading on startup.

To get started with the MCP server, simply run the following command:

uvx --from "financetoolkit[mcp]" financetoolkit-mcp-setup

Three results of a relatively advanced model (Claude Sonnet 4.6) shows how powerful models can layer in very detailed qualitative analysis and narrative synthesis with the information from the Finance Toolkit MCP.

Compare Apple with Microsoft, what company is the most profitable?

Across the five-year window from 2021 to 2025, Microsoft and Apple present genuinely different profitability profiles depending on the analytical lens applied — a nuance that institutional research rarely collapses into a single verdict. The data below, derived directly from the Finance Toolkit MCP server, covers gross margin, operating margin, and net profit margin across both companies from fiscal year 2021 through fiscal year 2025.

Microsoft commands a structurally superior margin stack at every level of the income statement. Its software and cloud-heavy revenue mix consistently produces gross margins in the 68–70% range, reflecting the near-zero marginal cost of licensing and Azure compute, while Apple's hardware-weighted mix constrains gross margins to the 42–47% band despite meaningful Services segment expansion.

Metric Company 2021 2022 2023 2024 2025
Gross Margin AAPL 41.78% 43.31% 44.13% 46.21% 46.91%
Gross Margin MSFT 68.93% 68.40% 68.92% 69.76% 68.82%
Operating Margin AAPL 29.78% 30.29% 29.82% 31.51% 31.97%
Operating Margin MSFT 41.59% 42.06% 41.77% 44.64% 45.62%
Net Profit Margin AAPL 25.88% 25.31% 25.31% 23.97% 26.92%
Net Profit Margin MSFT 36.45% 36.69% 34.15% 35.96% 36.15%

The margin story, however, is not the complete picture. When shifting from income-statement efficiency to capital deployment efficiency, Apple's financial engineering inverts the comparison dramatically. Apple carries a deliberately compressed equity base — the result of decades of aggressive share repurchases — which mechanically inflates its Return on Equity to levels that appear extraordinary, consistently exceeding 170% in recent years. The following table captures ROE, Return on Invested Capital, and Return on Assets for the same period.

Metric Company 2022 2023 2024 2025
Return on Equity AAPL 175.46% 171.95% 157.41% 171.42%
Return on Equity MSFT 47.15% 38.82% 37.13% 33.28%
Return on Invested Capital AAPL 59.90% 60.68% 60.19% 70.38%
Return on Invested Capital MSFT 38.73% 34.74% 33.71% 30.64%
Return on Assets AAPL 28.36% 27.50% 26.13% 30.93%
Return on Assets MSFT 20.82% 18.63% 19.07% 18.00%

The verdict depends precisely on what one means by "most profitable." On a pure income statement basis — gross, operating, and net margins — Microsoft is unambiguously the more profitable business, generating roughly 22 percentage points more net income per dollar of revenue than Apple in fiscal year 2025 (36.15% vs. 26.92%). This structural advantage reflects Microsoft's software and cloud economics, where incremental revenue has near-zero marginal cost.

Apple, by contrast, leads on every capital efficiency metric: its ROIC of 70.38% in 2025 versus Microsoft's 30.64% indicates that Apple extracts significantly more economic value from each dollar of invested capital. Its ROA advantage (30.93% vs. 18.00%) is similarly consistent across the full sample. The ROE comparison is analytically distorted by Apple's balance sheet structure and is better set aside in favor of ROIC as the cleanest apples-to-apples measure.

For a more complete picture, the analysis could be extended into DuPont decomposition to isolate whether Apple's ROIC lead is driven by asset turnover, operational leverage, or financial leverage — all of which the Finance Toolkit supports natively.

When looking at biggest banks in Europe, which one seems to be the most solvent?

Assessing solvency across Europe's nine largest listed banking groups — HSBC, BNP Paribas (BNPQY), Deutsche Bank (DB), Banco Santander (SAN), Barclays (BCS), UniCredit (UNCRY), Société Générale (SCGLY), ING, and Intesa Sanpaolo (ISNPY) — requires examining leverage in multiple dimensions simultaneously. Because banks operate with inherently high financial leverage by design, the equity multiplier and debt-to-assets ratio are the most discriminating solvency signals, with the debt service coverage ratio providing a cash-flow-based cross-check. Taken together, the data point to UniCredit and Intesa Sanpaolo as the standout names for solvency quality within this cohort.

The debt-to-equity ratio captures the proportion of debt relative to shareholders' equity. A lower reading indicates a more conservative capital structure relative to the equity cushion available to absorb losses. The six-year progression below reveals a clear dispersion across the group, with BNP Paribas and Santander consistently carrying the heaviest debt loads relative to equity, while HSBC and Intesa Sanpaolo trend toward the lower end.

Ticker 2020 2021 2022 2023 2024 2025
ISNPY 1.62 1.58 1.61 2.22 2.24 2.13
HSBC 1.85 1.91 1.10 2.22 1.26 2.68
UNCRY 2.24 2.01 1.82 1.91 1.95 2.57
BCS 2.15 2.38 2.65 2.46 2.56 2.81
DB 3.28 2.30 2.70 1.93 1.91 3.18
SCGLY 2.31 2.13 2.11 2.38 2.30 4.12
ING 1.42 2.12 2.37 2.87 3.34 3.32
SAN 3.53 3.45 4.36 2.98 4.50 4.40
BNPQY 6.40 6.34 2.56 5.23 5.43 6.22

The equity multiplier — total assets divided by equity — provides a balance-sheet-wide view of financial leverage and is a core input into DuPont decomposition. A lower multiplier implies a thicker equity buffer relative to the entire asset base. The 2025 cross-section is particularly telling: UniCredit stands at just 12.6x, the lowest among all nine peers, followed closely by Intesa Sanpaolo at 14.5x and Santander at 16.8x. By contrast, BNP Paribas (20.7x), Société Générale (21.0x), Barclays (20.3x), and ING (20.3x) are meaningfully more leveraged. Importantly, UniCredit's multiplier has compressed steadily from 15.1x in 2021 to 12.6x in 2025, signalling a deliberate and sustained de-leveraging trajectory.

Ticker 2021 2022 2023 2024 2025
UNCRY 15.10 14.09 12.85 12.34 12.64
ISNPY 15.86 16.33 15.46 14.66 14.50
SAN 16.48 17.09 17.49 17.18 16.82
HSBC 14.43 15.11 15.89 15.73 16.57
DB 20.38 18.97 17.99 17.50 17.69
ING 17.11 18.24 18.94 19.27 20.31
BCS 19.97 20.74 21.18 20.75 20.30
BNPQY 23.21 23.24 21.55 20.14 20.67
SCGLY 21.10 20.46 20.33 20.08 20.96

The debt-to-assets ratio corroborates this ranking. HSBC (0.153), Deutsche Bank (0.178), and Intesa Sanpaolo (0.145) hold the smallest debt loads as a share of the total balance sheet in 2025, while BNP Paribas (0.294) and Santander (0.266) are again the outliers on the high end. The debt service coverage ratio provides the critical cash-flow validation: UniCredit (0.228) and Intesa Sanpaolo (0.181) post the highest readings in 2025, meaning their operating earnings are most comfortably covering their debt obligations — a distinction that separates balance-sheet strength from earnings-backed solvency capacity.

Ticker D/A 2025 Equity Mult 2025 DSCR 2025
UNCRY 0.201 12.64 0.228
ISNPY 0.145 14.50 0.181
HSBC 0.153 16.57 0.120
DB 0.178 17.69 0.010
BCS 0.142 20.30 0.013
SCGLY 0.186 20.96 0.012
ING 0.161 20.31 0.011
SAN 0.266 16.82 0.014
BNPQY 0.294 20.67 0.013

Synthesizing across all three dimensions, UniCredit (UNCRY) emerges as the most solvent major European bank. Its equity multiplier of 12.6x is the lowest in the peer group by a meaningful margin, its trend has been consistently improving over six years, and its debt service coverage ratio of 0.228 is the highest in the cohort — confirming that the balance-sheet strength is underpinned by genuine earnings power rather than accounting structure alone. Intesa Sanpaolo (ISNPY) is the clear runner-up, posting the second-best equity multiplier and second-best DSCR. At the other end of the spectrum, BNP Paribas is the most leveraged name across nearly every metric, and Société Générale's equity multiplier spiked to 21.0x in 2025, flagging elevated structural leverage risk in that institution.

Logical extensions of this analysis within the Finance Toolkit ecosystem would include examining capital allocation quality via return on equity and return on invested capital for these same banks, running a rolling volatility and maximum drawdown comparison to understand how solvency strength translates into price resilience, or stress-testing via the Altman Z-Score model where data coverage permits.

Tell me something about the Semiconductor industry, is it overbought?

The following analysis covers eight representative semiconductor names spanning the full value chain — fabless designers (NVDA, AMD, QCOM), integrated device manufacturers (INTC, MU), a pure-play foundry (TSM), a diversified chip infrastructure leader (AVGO), and the European lithography monopoly (ASML) — using RSI momentum, trailing P/E multiples, and risk-adjusted Sharpe ratios sourced entirely from the Finance Toolkit MCP server.

Momentum: The Sector Was Overbought in May — and Has Since Corrected

The most telling technical story of 2026 is a sharp but short-lived overbought surge in May, now substantially unwound as of the June 4 close. The table below presents trailing 14-day RSI readings across the cohort for the last ten trading sessions. Readings above 70 flag overbought conditions; readings below 30 indicate oversold pressure.

Date NVDA AMD INTC QCOM AVGO TSM MU ASML SPY (Benchmark)
2026-05-19 58.45 66.12 60.91 62.48 52.18 49.43 67.19 55.28 67.57
2026-05-20 69.80 68.27 65.02 58.07 50.13 52.43 69.30 58.35 67.79
2026-05-21 66.66 67.75 62.29 62.11 47.27 54.00 69.58 61.87 67.52
2026-05-22 62.51 75.22 66.19 70.96 49.00 51.24 66.21 67.74 71.84
2026-05-26 63.94 77.28 61.71 69.59 47.68 57.60 70.64 64.79 71.48
2026-05-27 54.20 67.28 57.01 62.13 48.42 51.57 70.92 54.65 65.84
2026-05-28 52.51 74.45 59.39 62.11 56.65 55.36 72.68 58.08 71.16
2026-05-29 46.25 66.97 39.94 60.01 57.75 53.26 70.09 52.15 68.77
2026-06-03 41.65 74.14 42.23 61.96 73.63 64.73 74.99 65.57 61.53
2026-06-04 35.85 67.01 45.42 64.32 43.84 61.77 68.09 67.54 59.15

The data paints a diverging picture within the sector. NVDA is the clearest outlier: its RSI has collapsed from a local peak of ~70 in mid-May to 35.85 on June 4, approaching oversold territory and suggesting near-term selling pressure has been substantial. AVGO echoes a similar dynamic, dropping from an intraday peak above 73 to 43.84 in just two sessions, possibly reflecting rotation out of AI-infrastructure adjacent names. In contrast, AMD, QCOM, MU, and ASML remain in the 60–75 band — elevated but not technically overbought as of the last close. The broader SPY benchmark sits at 59.15, meaning several semiconductor names (AMD at 67, QCOM at 64, MU at 68, ASML at 68) are trading with more momentum than the broad market, but not yet at alarming levels. Notably, the sector as a whole touched genuinely overbought readings of 80–89 on INTC, QCOM, and MU in the first two weeks of May, coinciding with the US-China trade truce news and renewed AI capex guidance from hyperscalers. That wave has receded.

Valuation: Multiples Remain Structurally Elevated for AI-Exposed Names

The overbought question cannot be answered through momentum alone — RSI describes the speed of price change, not whether the underlying business justifies the price. The following table presents trailing annual P/E ratios for the cohort from 2021 through 2026 (2026 where available).

Ticker 2021 2022 2023 2024 2025 2026
NVDA 170.5 38.0 284.3 112.5 63.5 44.6
AMD 55.9 77.1 280.5 120.5 80.8
AVGO 44.3 21.1 33.8 187.9 72.6
ASML 49.0 36.3 34.4 34.6 36.9
MU 18.1 6.5 — 120.9 37.6
QCOM 23.2 9.7 22.5 17.1 34.1
TSM 29.1 11.9 19.4 29.0 28.4
INTC 10.6 13.6 125.3 — —

NVDA's P/E compression from its stratospheric 284x in 2023 to 44.6x on a current-year basis is meaningful progress, but at 44x it still prices in enormous earnings growth expectations that leave little room for execution disappointment. AMD at 80.8x and AVGO at 72.6x for 2025 are similarly demanding. In contrast, TSM trades at a comparatively modest 28x, QCOM at 34x, and ASML at 37x — multiples that, while not cheap, are more defensible given their structural moat positions in leading-edge foundry, mobile/auto connectivity, and EUV lithography respectively. INTC remains the sector's distressed outlier, posting deeply negative earnings in 2024 and 2025 as its restructuring and process-technology catch-up remains unresolved.

Risk-Adjusted Returns: The Sector Has Not Rewarded Shareholders Proportionally

Sharpe ratios on an annual basis tell a sobering story. The table below shows risk-adjusted excess return (versus the risk-free rate) for each name since 2021.

Year NVDA AMD INTC QCOM AVGO TSM MU ASML
2021 -0.38 -0.46 -0.70 -0.62 -0.70 -0.66 -0.53 -0.51
2022 -0.79 -0.82 -1.27 -1.03 -1.23 -1.19 -1.04 -0.93
2023 -1.10 -1.20 -1.49 -1.90 -1.77 -1.91 -1.59 -1.90
2024 -1.13 -1.39 -1.40 -1.71 -1.14 -1.53 -1.27 -1.48
2025 -1.32 -1.05 -0.98 -1.75 -1.22 -1.57 -0.94 -1.61
2026 -1.73 -0.74 -0.57 -1.03 -1.41 -1.53 -0.59 -1.24

These uniformly negative Sharpe ratios indicate that, in every period, volatility has outpaced risk-compensated returns across the cohort. NVDA stands out negatively in 2026 with a Sharpe of -1.73, confirming that its recent price drawdown has been accompanied by elevated volatility — consistent with the RSI collapse observed above. AMD and MU register the least-negative 2026 ratios (-0.74 and -0.59 respectively), suggesting comparatively less turbulent price action relative to their returns. QCOM and INTC are also showing improvement in 2026 versus 2025, which aligns with their RSI readings reflecting a less extended momentum condition.

Synthesis: Mixed Signals — Sector Was Overbought, Now Normalizing

The semiconductor sector is not uniformly overbought as of June 4, 2026. The data reveals a sector mid-cycle in a technical correction from a genuine May overbought peak. NVDA and AVGO have unwound their momentum surges most aggressively and now flash caution signals in the opposite direction, with NVDA approaching oversold territory. AMD, MU, QCOM, and ASML remain mildly elevated on momentum but well below the threshold that would warrant an overbought classification. Valuations remain the persistent structural concern: NVDA, AMD, and AVGO carry multiples that require continued AI-driven earnings acceleration to justify, while ASML, QCOM, and TSM offer more moderate entry points from a fundamental standpoint. For investors monitoring the sector, the logical next steps within the Finance Toolkit ecosystem would include drilling into individual-name volatility profiles using GARCH forecasts, running rolling Sharpe analyses to capture momentum-regime shifts, or examining sector-level factor exposures through Fama-French decomposition to isolate whether excess returns are attributable to market beta, size, or value factors.

See an example of the Finance Toolkit MCP server in action in Claude Desktop below:

Demonstration-of-the-Finance-Toolkit-MCP.mp4

Also see the MCP Documentation for full setup instructions and usage examples.


Unified HTTP Request Layer

A single get_request() helper now handles all outbound HTTP calls across the toolkit (FRED, OECD, GMDB, FMP, yFinance fallbacks). This replaces several ad-hoc requests.get() calls scattered across modules and makes timeout handling, error reporting, and future retry logic consistent everywhere.

Fixed Income Improvements
  • All FRED data functions now accept an optional FRED_API_KEY (also readable from the FRED_API_KEY environment variable), unlocking ICE BofA bond index series (option-adjusted spread, effective yield, total return, yield to worst) that previously required a key but had no path to supply one.
  • Fixed a bug where selecting a start and end date on a different time period could result in no data being returned.
  • Fixed floating-point index noise in get_duration and get_derivative_price, np.arange results are now rounded to 10 decimal places, eliminating platform-dependent representations like 0.030000000000000002.
  • Improved robustness when a DataFrame index is not entirely a PeriodIndex.
Test Coverage
  • Added a --live pytest flag. Tests run against pickle fixtures by default; pass --live to hit real APIs (requires valid API keys set as env vars).
  • New test files for the Economics, Fixed Income, and MCP server modules, and significantly expanded coverage for Technicals, Options, Ratios, Models, Risk, and Performance.
  • Fama-French and factor-correlation tests (which download data from Dartmouth) are now skipped in standard CI and only run under --live.
  • Economics tests (which require live OECD/GMDB data) follow the same pattern.
CI / Tooling
  • Migrated from Poetry to uv across all GitHub Actions workflows and pre-commit hooks.
  • Extended the Python version matrix to 3.10 – 3.14.
  • Replaced pylint (not in dev dependencies) with codespell in the linting workflow; added an explicit --config pyproject.toml to the black pre-commit hook.
  • Upgraded action versions: actions/checkout@v4, actions/setup-python@v5, astral-sh/setup-uv@v5.
Documentation & Examples
  • Removed the HTML/CSS button navigation blocks from all 12 example notebooks; replaced with a direct link to jeroenbouma.com/projects/financetoolkit.
  • Fixed a broken /portfolio link and several triple-concatenated URLs that had accumulated in the Discovery and Models notebooks.
  • Updated the README with MCP setup instructions and revised module descriptions.
  • Docstring improvements across the controllers.

Full Changelog: v2.0.7...v2.1.0

v2.0.7

14 March 2026

What's Changed

  • Guard against NaN currency codes in portfolio conversion by @wavebyrd in #201
  • Use approximate float comparison for JSON test records by @wavebyrd in #200

New Contributors

Full Changelog: v2.0.6...v2.0.7

v2.0.6

4 October 2025

This release fixes issue #192 and #193. I've also transitioned from poetry to uv as package manager and builder.

Full Changelog: v2.0.5...v2.0.6

v2.0.5

10 September 2025

As reported by #190, the endpoints used within the Finance Toolkit used a retired version of the FMP API. This led to new API keys not being able to collect any data. I have fixed this issue by changing all endpoints to the stable release. This does mean that the data can be slightly different or certain API calls under the Free plan are more limited.

Furthermore, Option Chains and Implied Volatilty calculations failed. This has now been resolved by using yfinance in these functions.

Full Changelog: v2.0.4...v2.0.5

v2.0.4

10 July 2025

Minor update that adds some more unit tests and fixes an issue with caching not working due to a missing file. I've also worked on better Yahoo Finance error handling given that you'll hit the rate limit much quicker nowadays.

v2.0.3

1 May 2025

With the 2.0.3 release of the Finance Toolkit, I've added in proper support for Yahoo Finance (through yfinance) which serves as a fallback system when data from Financial Modeling Prep is not available. This makes it possible to do any of the calculations regardless of your current Financial Modeling Prep subscription level.

The only downside is that Yahoo Finance only provides 4 years or 5 quarters meaning that for longer periods a subscription with Financial Modeling Prep is still required (get 15% off here). Don't want this behaviour? Use enforce_source='FinancialModelingPrep' to force the use of Financial Modeling Prep data only. If you want to force the use of Yahoo Finance, set enforce_source='YahooFinance'.

For example:

image

If I would now force FinancialModelingPrep, I will not be able to acquire all data:

image

Furthermore, I've introduced daily calculations for ratios that use stock data. As an example:

image

I've also added in proper logging which fixes #181. Furthermore, I've added a lot more robustness to the Finance Toolkit and moved around a bunch of files making some .py files less bulky.

v2.0.2

8 April 2025

A few improvements:

  • All balance sheet items used in the Ratios and Models modules where calculated wrongly when the trailing parameter was used. By default it would take the rolling sum. This is however incorrect as it would sum for example the inventory of four quarters instead of taking the average over the period. This has been corrected!
  • Changed API endpoint to support the collection of Product and Geographic and Product Revenue Segmentations for Free users. This resolves issue #179.
  • Added more error handling for the Historical data which didn't always report the correct error.
  • Limited the dependencies of the Finance Toolkit to only those that are required and nothing else.

v2.0.1

8 April 2025

Added in Python 3.13 support which made sense to include given that all dependencies of the Finance Toolkit added support for this Python release as well.

v2.0.0

1 March 2025

have been working on the v2.0.0 of the Finance Toolkit for a while which features numerous improvements to the code as well as major new additions. Install the Finance Toolkit now to get started with 150+ metrics!

pip install financetoolkit -U

In Python:

from financetoolkit import Toolkit

companies = Toolkit(
    tickers=['GOOGL', 'MSFT', 'AMZN'],
    api_key="FINANCIAL_MODELING_PREP_KEY",
)

Find a variety of How-To Guides including Code Documentation for the FinanceToolkit here.


Portfolio Functionalities

I've added a brand new class to the Finance Toolkit called Portfolio (use from financetoolkit import Portfolio) which allows you to load in your own transactions data and see performance over any period of time (as opposed to some benchmark).

For a full list of details see here. Some things that are now possible:

  • Load in your own transactions data, based on a custom template that is provided automatically when initializing the class.
  • See an overview of your entire portfolio including invested amount, current value, return, benchmark return, alpha, beta and more.
  • Explore individual transactions and see how they have contributed to the overall performance of your portfolio. This also allows you to get a breakdown per period whether it be weekly, monthly, quarterly or yearly.
  • Delve deeper into how your portfolio performed with daily (cumulative) returns, portfolio weights and more.

It is important to note that it requires a specific Excel template to work, see for further instructions the following notebook here.


As a simple example:

from financetoolkit import Portfolio

instance = Portfolio(example=True, api_key="FMP_KEY")

instance.get_portfolio_overview()

The table below shows one of the functionalities of the Portfolio module but is purposely shrunken down given the >30 assets.

Identifier Volume Costs Price Invested Latest Price Latest Value Return Return Value Benchmark Return Volatility Benchmark Volatility Alpha Beta Weight
AAPL 137 -28 38.9692 5310.78 241.84 33132.1 5.2386 27821.3 2.2258 0.3858 0.1937 3.0128 1.2027 0.0405
ALGN 81 -34 117.365 9472.53 187.03 15149.4 0.5993 5676.9 2.1413 0.5985 0.1937 -1.542 1.5501 0.0185
AMD 78 -30 11.9075 898.784 99.86 7789.08 7.6662 6890.3 3.7945 0.6159 0.1937 3.8718 1.6551 0.0095
AMZN 116 -28 41.5471 4791.46 212.28 24624.5 4.1392 19833 1.8274 0.4921 0.1937 2.3118 1.1594 0.0301
ASML 129 -25 33.3184 4273.07 709.08 91471.3 20.4065 87198.3 3.8005 0.4524 0.1937 16.606 1.4407 0.1119
VOO 77 -12 238.499 18352.5 546.33 42067.4 1.2922 23715 1.1179 0.1699 0.1937 0.1743 0.9973 0.0515
WMT 92 -18 17.8645 1625.53 98.61 9072.12 4.581 7446.59 2.4787 0.2334 0.1937 2.1024 0.4948 0.0111
Portfolio 2142 -532 59.8406 128710 381.689 817577 5.3521 688867 2.0773 0.4193 0.1937 3.2747 1.2909 1

In which the weights and returns can be depicted as follows:

image

This is however only minor as opposed to the integration with the Finance Toolkit itself meaning that you are able to use all of the 150+ metrics directly with your own portfolio. It also includes a "Portfolio" ticker which represents the weighted sum over time of your assets in the portfolio. As an example

from financetoolkit import Portfolio

instance = Portfolio(example=True, api_key="FMP_KEY")

profit_margin = instance.toolkit.ratios.get_net_profit_margin()

Which returns when plotted for the Portfolio the following:

image

This makes it so that you can not only evaluate your portfolio through basic OHLC data but also understand the financial health of the companies you are invested in and how this impacts your overall portfolio.

Caching Capabilities

I've had this request a couple of times now and given the ever-growing size of the project it made sense to integrate caching functionalities. When using use_cached_data=True when you initialize the Finance Toolkit any of the core functionalities will automatically be saved to a pickle file (e.g. if you collect a balance sheet statement, these will be saved to the cached folder under balance_sheet_statement.pickle). If you then re-run the Finance Toolkit you will notice the data collection is instant, this is because the data is loaded from the pickle file.

As an example:

image

If I wish to receive this data again, I no longer need an API key or set the tickers and can simply keep use_cached_data=True.

image

Please note that it will force the settings as found in the pickle files so if you wish to use a different time period, you will have to recollect.

image

You can also change the folder by entering a string instead of a boolean for the use_cached_data parameter.

image

Global Macro Database Integration

I've seen the work from Karsten Muller related to the "Global Macro Database" project (see LinkedIn and the GitHub project here) which has Economics metrics going back all the way to the 1800s. An invaluable resource which I've integrated into the Finance Toolkit as well. You will see that the Key Economic Indicators list is therefore greatly expanded.

As an example:

from financetoolkit import Economics

economics = Economics(api_key=API_KEY, start_date="2017-12-31")

economics.get_unemployment_rate()

image

The current list of Economic parameters is:

  • Gross Domestic Product (GDP)
  • Total Consumption
  • Total Investment
  • Total Fixed Investment
  • Exports
  • Imports
  • Current Account Balance
  • Government Debt
  • Government (Tax) Revenue
  • Government Expenditure
  • Government Deficit
  • Trust in Government
  • Consumer Price Index (CPI)
  • Inflation Rate
  • Consumer Confidence Index (CCI)
  • Business Confidence Index (BCI)
  • Composite Leading Indicator (CLI)
  • House Prices
  • Rent Prices
  • Share Prices
  • Exchange Rates
  • Money Supply
  • Central Bank Policy Rate
  • Long Term Interest Rates (10 year)
  • Short Term Interest Rates (3 month)
  • Renewable Energy as % of Total Energy
  • Carbon Footprint
  • Unemployment Rate
  • Labour Productivity
  • Income Inequality
  • Population
  • Poverty Rate

Many Bugfixes and Improvements

I've added better error handling for Bandwidth Limits, more information when data is collected from a different source, numerous minor fixes e.g. recalculating ratios found in the financial statements when applying trailing (#172 and #173) and cleaned up a lot of other details.

The Streamlit Dashboard is also updated with new additions including a brand new Portfolio Dashboard, see below:

image

v1.9.9

12 December 2024

Functionality for the Economics menu broke due to the fact I forgot to include headers into my request towards OECD, thanks for reporting #162. Furthermore, the Close and Adj Close price were the same for data acquired from Yahoo Finance, this has now been fixed and is correct. I've also suppressed Yahoo Finance logging messages as I'll handle all of it myself as well.

v1.9.8

29 September 2024

This release features a fix to issues with Yahoo Finance which is used as a fallback whenever FinancialModelingPrep doesn't have the data or because your plan limits you from accessing this data. E.g. if you have the Free plan you can only get historical data on U.S. listed stocks so all other historical data comes from Yahoo Finance. I used to directly query from Yahoo Finance myself but given that it can break over time, it makes more sense to add in an optional dependency (yfinance). This means that by default this dependency is not installed given that the Finance Toolkit doesn't have to rely on this package if you have the proper FMP plan.

This is what I am referring to (see "The following tickers acquired historical data..")

image

In case you've used pip install financetoolkit -U in a new environment you will receive the following message when you have a Free plan and try to download data on stocks not on U.S. exchanges:

image

As can be read, this can be resolved by using pip install 'financetoolkit[yfinance]' as shown below:

image

v1.9.6

7 September 2024

The last couple of releases were all minor bugfixes therefore it didn't merit a proper release. However, for this one quite a fix things under the hood have changed entirely inside the Economy menu. Given that OECD recently updated their databases, all of the original links broke and therefore needed fixing. This unfortunately also resulted in some functionality being scrapped given that the datapoints were archived altogether.

Furthermore, I am aware of issues with Yahoo Finance's data download. You won't notice any to this when using an API Key from FMP but if you don't, I had built a fallback method that went to Yahoo Finance. Given that Yahoo Finance doesn't officially support the collection of data for now this functionality within the Finance Toolkit won't function (it will return 0s). I have still to consider whether to remove the functionality altogether or come up with a fix (however given that it is unofficial, things can break at any time again). Given that the package yfinance exists, I might introduce it as an add-on if you still wish to have this functionality.

Please let me know if you do.

v1.9.0

29 April 2024

The release of the Finance Toolkit v1.9.0 includes an entirely new Fixed Income module. This module contains a wide variety of fixed income related calculations such as the Effective Yield, the Macaulay Duration, the Modified Duration Convexity, the Yield to Maturity and models such as Black and Bachelier to valuate derivative instruments such as Swaptions.

For example, it is possible to perform Bond Calculations with collect_bond_statistics which can valuate a variety of bonds based on used input:

Bond 1 Bond 2 Bond 3 Bond 4 Bond 5 Bond 6
Par Value 100 250 50 1000 85 320
Coupon Rate 0.05 0.02 0.075 0 0.15 0.015
Years to Maturity 5 10 2 10 3 1
Yield to Maturity 0.08 0.021 0.03 0 0.16 0.04
Frequency 1 1 4 1 2 12
Present Value 88.0219 247.766 54.3518 1000 83.0353 312.171
Current Yield 0.0568 0.0202 0.069 0 0.1535 0.0154
Effective Yield 0.05 0.02 0.0771 0 0.1556 0.0151
Macaulay's Duration 4.5116 9.1576 1.8849 10 2.5667 0.9932
Modified Duration 4.1774 8.9693 1.8709 10 2.3766 0.9899
Effective Duration 4.0677 8.5181 1.8477 9.4713 2.2952 0.9844
Dollar Duration 3.677 22.2228 1.0168 100 1.9734 3.0902
DV01 0.0004 0.0022 0 0.01 0.0001 0
Convexity 22.4017 93.7509 4.0849 110 7.0923 1.0662

This can be done with the following code:

from financetoolkit import FixedIncome

fixedincome = FixedIncome()

# Valuate a specific bond, for example Bond 1
fixedincome.collect_bond_statistics(
    par_value=100,
    coupon_rate=0.05,
    years_to_maturity=5,
    yield_to_maturity=0.08,
    frequency=1,
)

Not only Bonds can be valuated, the module can also be used to valudate derivatives such as Swaptions utilizing the Black and Bachelier models. For example, the Black model can be used to valuate a Swaption:

from financetoolkit import FixedIncome

fixedincome = FixedIncome()

# You can also provide lists of values for the strike rate and years to maturity
# to define your own strike rates and years to maturity to display in the DataFrame
fixedincome.get_derivative_price(model_type='black', forward_rate=0.0325)

This returns a large DataFrame that shows the present value of such a swaption contract at a variety of strike rates and maturities.

Strike Rate 2025-04-21 2026-04-21 2027-04-21 2028-04-20 2029-04-20 2030-04-20 2031-04-20 2032-04-19 2033-04-19 2034-04-19
0.005 0 0 0 0 0 0 0 0 0 0
0.01 0 0 0 0 0 0 0 0 0 0
0.015 0 0 0 0 0 0 0 0 0 0
0.02 0 0 0 0 0 0 0 0 0 0
0.025 0 0 0 0 0 0 0 0 0 0
0.03 0 0 0 0.04 0.25 0.9 2.3 4.68 8.22 12.98
0.035 24200.6 23426.7 22677.6 21952.5 21251.2 20573.2 19918.5 19286.4 18676.5 18088
0.04 72601.7 70280.1 68032.7 65857.2 63751.2 61712.6 59739.2 57828.9 55979.6 54189.6
0.045 121003 117133 113388 109762 106252 102854 99565.3 96381.4 93299.4 90315.9
0.05 169404 163987 158743 153667 148753 143996 139391 134934 130619 126442
0.055 217805 210840 204098 197571 191254 185138 179218 173487 167939 162569
0.06 266206 257694 249453 241476 233754 226280 219044 212039 205259 198695
0.065 314607 304547 294808 285381 276255 267421 258870 250592 242578 234821
0.07 363008 351400 340163 329286 318756 308563 298696 289144 279898 270948
0.075 411410 398254 385518 373191 361257 349705 338522 327697 317218 307074
0.08 459811 445107 430874 417095 403758 390846 378348 366250 354538 343200
0.085 508212 491960 476229 461000 446258 431988 418174 404802 391858 379327
0.09 556613 538814 521584 504905 488759 473130 458000 443355 429177 415453
0.095 605014 585667 566939 548810 531260 514272 497827 481907 466497 451580
0.1 653415 632521 612294 592714 573761 555413 537653 520460 503817 487706
0.105 701816 679374 657649 636619 616262 596555 577479 559012 541137 523832
0.11 750217 726227 703004 680524 658762 637697 617305 597565 578456 559959
0.115 798619 773081 748359 724429 701263 678839 657131 636118 615776 596085
0.12 847020 819934 793715 768334 743764 719980 696957 674670 653096 632211
0.125 895421 866787 839070 812238 786265 761122 736783 713223 690416 668338
0.13 943822 913641 884425 856143 828766 802264 776609 751775 727735 704464

It is also possible to access Government Bond rates from 30+ countries. For example, using get_government_bond_yields(short_term=False, period='monthly'):

Australia Austria Belgium Brazil Bulgaria Canada Chile China Colombia Costa Rica Croatia Czech Republic Denmark Estonia Euro Area 19 Finland France Germany Greece Hungary Iceland India Indonesia Ireland Israel Italy Japan Latvia Lithuania Luxembourg Mexico Netherlands New Zealand Norway Poland Portugal Romania Russia Slovakia Slovenia South Africa South Korea Spain Sweden Switzerland United Kingdom United States
2023-05 0.035 0.0303 0.0304 0.0728 0.0403 0.0305 0.0555 0.0269 0.1111 nan 0.0371 0.045 0.0254 0.0394 0.0321 0.0298 0.0294 0.0234 0.0398 0.0778 nan 0.0701 0.0636 0.0279 0.0379 0.0431 0.0043 0.0383 0.0288 0.0295 0.0876 0.0273 0.0423 0.0323 0.0593 0.0316 0.063 nan 0.0359 0.0315 0.1194 0.034 0.0341 0.0232 0.0085 0.0396 0.0357
2023-06 0.0392 0.0305 0.0305 0.0728 0.0403 0.0334 0.0531 0.0264 0.1015 nan 0.0373 0.0435 0.0257 0.0394 0.0316 0.03 0.0293 0.0238 0.037 0.072 nan 0.0705 0.0622 0.0278 0.0374 0.0407 0.004 0.0379 0.0288 0.0295 0.0857 0.0275 0.0448 0.0348 0.0591 0.0309 0.0611 nan 0.0362 0.0338 0.1194 0.0361 0.034 0.0246 0.0097 0.0437 0.0375
2023-07 0.0403 0.0312 0.0314 0.07 0.0403 0.0345 0.0533 0.0266 0.1022 nan 0.0374 0.0415 0.027 0.0409 0.0327 0.0307 0.0304 0.0246 0.0385 0.071 nan 0.0711 0.0633 0.029 0.0377 0.0416 0.0059 0.0381 0.0288 0.0303 nan 0.0284 0.0465 0.0364 0.0556 0.0323 0.062 nan 0.0369 0.034 0.1172 0.0368 0.035 0.0252 0.0098 0.0444 0.039
2023-08 0.0413 0.0318 0.0322 0.07 0.0403 0.0365 0.0563 0.0256 0.107 nan 0.0393 0.0426 0.0277 0.0415 0.0334 0.0315 0.0311 0.0255 0.0388 0.074 nan 0.0719 0.0636 0.0296 0.0391 0.0422 0.0064 0.0385 0.0288 0.0308 0.091 0.0292 0.049 0.0381 0.0559 0.0331 0.0634 nan 0.038 0.0348 0.1172 0.0386 0.0359 0.0275 0.0095 0.0453 0.0417
2023-09 0.0421 0.0329 0.0332 0.07 0.0403 0.0382 0.0597 0.0268 0.1187 nan 0.0395 0.0449 0.0283 0.0425 0.0351 0.0325 0.0324 0.0266 0.0408 0.0708 nan 0.0717 0.0691 0.0309 0.04 0.0451 0.0076 0.0388 0.0288 0.0316 0.0968 0.0304 0.0505 0.0382 0.0568 0.0345 0.0748 nan 0.0391 0.0347 0.1206 0.0395 0.0372 0.0289 0.0109 0.0442 0.0438
2023-10 0.0463 0.0349 0.0352 0.0655 0.0403 0.0406 0.0653 0.0269 0.1181 nan 0.0418 0.0472 0.0305 0.0409 0.0372 0.0347 0.0345 0.0282 0.043 0.0753 nan 0.0735 0.0705 0.0327 0.0438 0.0488 0.0095 0.0414 0.0288 0.0332 nan 0.0321 0.0546 0.0395 0.0584 0.0359 0.0681 nan 0.0412 0.0367 0.1236 0.0427 0.0395 0.0302 0.0105 0.0457 0.048
2023-11 0.0458 0.0321 0.0323 0.0655 0.0403 0.0371 0.0598 nan 0.1089 nan 0.0393 0.0443 0.0279 0.0367 0.0342 0.032 0.0319 0.026 0.0388 0.0701 nan nan nan 0.0301 0.0427 0.0443 0.0066 0.0398 0.0288 0.0303 0.1023 0.0295 0.051 0.0368 0.0554 nan 0.0675 nan 0.0386 0.0353 0.1179 0.0389 0.0366 0.0276 0.0082 0.0427 0.045

Next to that, the well-known Corporate Bond indices from ICE BofA are also available. For example this shows the Corporate Bond Yield and Option-Adjust Spread (OAS) for a variety of maturities. You can access this data with get_ice_bofa_effective_yield and get_ice_bofa_option_adjusted_spread.

Fixed Income

Central Bank Rates such as the EURIBOR and SOFR rates can be accessed that serve as the reference (or benchmark) rate of a large variety of derivative contracts such as swaps and futures. For example:

from financetoolkit import FixedIncome

fixedincome = FixedIncome(start_date='2023-12-01')

euribor_rates = fixedincome.get_euribor_rates()

Which returns:

1-Month 3-Month 6-Month 12-Month
2023-12 0.0386 0.0393 0.0392 0.0367
2024-01 0.0387 0.0393 0.0389 0.0361
2024-02 0.0387 0.0392 0.039 0.0367

Next to that, I've added in the European Central Banks which include:

  • The main refinancing operations (MRO) rate is the interest rate banks pay when they borrow money from the ECB for one week. When they do this, they have to provide collateral to guarantee that the money will be paid back.
  • The marginal lending facility rate is the interest rate banks pay when they borrow from the ECB overnight. When they do this, they have to provide collateral, for example securities, to guarantee that the money will be paid back.
  • The deposit facility rate which is one of the three interest rates the ECB sets every six weeks as part of its monetary policy. The rate defines the interest banks receive for depositing money with the central bank overnight.

These can be shown by using:

from financetoolkit import FixedIncome

fixedincome = FixedIncome(start_date='2000-01-01')

fixedincome.get_european_central_bank_rates()

Which returns (when plotted):

image

I've also added in the Federal Funds rates which include:

  • The effective federal funds rate (EFFR) which is calculated as a volume-weighted median of overnight federal funds transactions reported in the FR 2420 Report of Selected Money Market Rates.
  • The overnight bank funding rate (OBFR) which is calculated as a volume-weighted median of overnight federal funds transactions, Eurodollar transactions, and the domestic deposits reported as “Selected Deposits” in the FR 2420 Report.
  • The TGCR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon.
  • The BGCR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon as well as GCF Repo transaction data obtained from the U.S. Department of the Treasury’s Office of Financial Research (OFR).
  • The SOFR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon as well as GCF Repo transaction data and data on bilateral Treasury repo transactions cleared through FICC's DVP service, which are obtained from the U.S. Department of the Treasury’s Office of Financial Research (OFR).

These can be shown by using (and defining the rate):

from financetoolkit import FixedIncome

fixedincome = FixedIncome(start_date='2016-01-01')

# Effective Federal Funds Rate
fixedincome.get_federal_reserve_rates(rate='EFFR')

# Secured Overnight Financing Rate
fixedincome.get_federal_reserve_rates(rate='SOFR')

Which returns (when plotted):

image

image

v1.8.5

2 April 2024

This release contains new Fixed Income metrics as part of the Economics module, these contain Option-Adjusted Spreads, Effective Yields, Total Returns and Yield to Worst. For example, see the Option-Adjusted Spread below (see documentation here):

image

The Option-Adjusted Spread (OAS) is the spread relative to a risk-free interest rate, usually measured in basis points (bp), that equates the theoretical present value of a series of uncertain cash flows to the market price of a fixed-income investment. The spread is added to the risk-free rate to compensate for the uncertainty of the cash flows. This is usually a better alternative than the usual Z-spread used to price derivatives.

Furthermore, @northern-64bit (maintainer of scikit-multilearn-ng) introduced new AR and MA models that can be utilised with any type of time series. For more information, see #117. @northern-64bit actually introduced many more models in the Finance Toolkit as seen here.

Furthermore, I've introduced bug fixes solving #128 and #129.

v1.8.3

4 February 2024

This release includes the Binomial Model, a mathematical model for pricing both American as well as European options. The Binomial Model is a discrete-time model that calculates the price of an option by creating a riskless hedge portfolio that replicates the payoff of the option. The model is based on the assumption that the price of the underlying asset follows a binomial distribution. The Binomial Model is a simple and intuitive model that is widely used in practice. It is also the basis for more complex models. See for an elaborate explanation the documentation as found here.

Binomial Tree

For example, when using the following code:

from financetoolkit import Toolkit

companies = Toolkit(["AAPL", "MSFT"], api_key="FINANCIAL_MODELING_PREP_KEY")

companies.options.get_binomial_model(show_input_info=True)

It returns a large DataFrame with the binomial tree for each company and each strike price around the current price (as defined by the start_date parameter).

image

The resulting output is a DataFrame containing the tickers, strike prices and movements as the index and the time to expiration as the columns. The movements index contains the number of up movements and the number of down movements. The output is the binomial tree displayed in a table. E.g. when using 10 time steps, the table for each strike price from each company will contain the actual binomial tree as also depicted in the image as seen below. Find the documentation here.

When selecting for example Apple at a Strike Price of 140 you will get the actual Binomial Tree depicted as a table, this represents the tree you see in the image at the top.

Movement 2024-02-02 2024-03-09 2024-04-15 2024-05-21 2024-06-27 2024-08-02 2024-09-08 2024-10-14 2024-11-20 2024-12-26 2025-02-01
UUUUUUUUUU 54.7747 69.9327 87.4757 107.31 129.344 153.573 180.122 209.208 241.069 275.965 314.18
UUUUUUUUUD nan 39.9569 52.8423 68.2288 86.0206 106.037 128.14 152.365 178.911 207.994 239.852
UUUUUUUUDD nan nan 27.3011 37.7763 50.8718 66.5774 84.6651 104.825 126.925 151.146 177.689
UUUUUUUDDD nan nan nan 16.9659 24.8886 35.4656 48.9066 65.0645 83.4462 103.602 125.698
UUUUUUDDDD nan nan nan nan 9.1158 14.4288 22.208 33.0259 47.083 63.8384 82.2161
UUUUUDDDDD nan nan nan nan nan 3.8311 6.7007 11.4806 19.124 30.5822 45.85
UUUUDDDDDD nan nan nan nan nan nan 0.9669 1.9327 3.8631 7.722 15.4353
UUUDDDDDDD nan nan nan nan nan nan nan 0 0 0 0
UUDDDDDDDD nan nan nan nan nan nan nan nan 0 0 0
UDDDDDDDDD nan nan nan nan nan nan nan nan nan 0 0
DDDDDDDDDD nan nan nan nan nan nan nan nan nan nan 0

The model contains parameters to lengthen the time steps, change the risk-free rate and the dividend yield but more importantly, make it possible to calculate the price of both American and European options as well as Call and Put options. For example, let's calculate the price of a American Put option with a strike price of 140 for Apple again:

from financetoolkit import Toolkit

companies = Toolkit(["AAPL", "MSFT"], api_key="FINANCIAL_MODELING_PREP_KEY")

companies.options.get_binomial_model(
    show_input_info=True,
    put_option=True,
    american_option=True,
    timesteps=12,
    risk_free_rate=0.01)

Which returns the Option valuations for an American Put Option.

Movement 2024-02-02 2024-03-03 2024-04-02 2024-05-03 2024-06-02 2024-07-03 2024-08-02 2024-09-01 2024-10-02 2024-11-01 2024-12-02 2025-01-01 2025-02-01
UUUUUUUUUUUU 2.3581 1.1115 0.4236 0.116 0.0171 0 0 0 0 0 0 0 0
UUUUUUUUUUUD nan 3.7011 1.8524 0.7546 0.2225 0.0355 0 0 0 0 0 0 0
UUUUUUUUUUDD nan nan 5.6933 3.0346 1.3274 0.4238 0.0736 0 0 0 0 0 0
UUUUUUUUUDDD nan nan nan 8.5588 4.8737 2.3002 0.8005 0.1529 0 0 0 0 0
UUUUUUUUDDDD nan nan nan nan 12.5322 7.6463 3.9148 1.4975 0.3173 0 0 0 0
UUUUUUUDDDDD nan nan nan nan nan 17.8023 11.6676 6.518 2.7676 0.6586 0 0 0
UUUUUUDDDDDD nan nan nan nan nan nan 24.4233 17.2193 10.5575 5.0375 1.3671 0 0
UUUUUDDDDDDD nan nan nan nan nan nan nan 32.2051 24.4052 16.5049 8.9884 2.8376 0
UUUUDDDDDDDD nan nan nan nan nan nan nan nan 40.6414 32.9347 24.6074 15.6102 5.89
UUUDDDDDDDDD nan nan nan nan nan nan nan nan nan 48.9936 41.9389 34.3151 26.0772
UUDDDDDDDDDD nan nan nan nan nan nan nan nan nan nan 56.6615 50.2044 43.2257
UDDDDDDDDDDD nan nan nan nan nan nan nan nan nan nan nan 63.702 57.7929
DDDDDDDDDDDD nan nan nan nan nan nan nan nan nan nan nan nan 70.1673

Under the hood of this model the stock prices are simulated based on up and down movements. These can be graphically depicted as a binomial tree and help in understanding the calculated option prices for each node in. More information about these stock price simulations can be found in the documentation here and as follows:

from financetoolkit import Toolkit

companies = Toolkit(["AAPL", "MSFT"], api_key="FINANCIAL_MODELING_PREP_KEY")

companies.options.get_stock_price_simulations(show_input_info=True, timesteps=10)

Which would return for Apple the following graph when plotted:

image

Given that the Finance Toolkit is modular, you do not have to use the Toolkit functionality directly and can also call each functionality of the model separately. For example, this shows the output of using the model directly, specifying each parameter yourself.

image

v1.8.1

22 January 2024

This new release contains intraday historical data which makes it possible to calculate Risk, Performance and Technical metrics based on a 1 min, 5 min, 15 min, 30 min or 1 hour interval. For example, you can obtain the Capital Asset Pricing Model (CAPM) per model in which it calculates the beta for each hour.

Or for example Williams %R on an hourly basis as follows:

image

Next to that, I've done a lot of polishing. A user noticed that there were some issues with working with delisted companies. As Financial Modeling Prep allows you to get data on these companies whereas Yahoo Finance doesn't, I needed to make sure that the Finance Toolkit didn't attempt to query the Yahoo Finance and return an error. This has been resolved (all of these companies are delisted):

image

Furthermore, I've fixed small bugs, updated the documentation and more. All in all it should be a more pleasant experience!

v1.8.0

17 January 2024

It's time for another major release which consists of a full blown Options menu including all First, Second and Third Order Greeks such as Delta, Vega, Gamma, Theta and Ultima. Find the entire list of Greeks here. Update your Finance Toolkit now with:

pip install financetoolkit -U

Based on the Black Scholes formula, it is now possible to get theoretical option prices and greeks for a range of stocks being able to plot charts such as the following:

image

For example, the following code gets you all Greeks for Tesla.

from financetoolkit import Toolkit

toolkit = Toolkit(["TSLA", "MU"], api_key="FINANCIAL_MODELING_PREP_KEY")

all_greeks = toolkit.options.collect_all_greeks(start_date='2024-01-03')

all_greeks.loc['TSLA', '2024-01-04']

Which returns (Stock Price: 238.45, Volatility: 55.4%, Dividend Yield: 0.0% and Risk Free Rate: 3.91%):

Strike Price Delta Dual Delta Vega Theta Rho Epsilon Lambda Gamma Dual Gamma Vanna Charm Vomma Vera Veta PD Speed Zomma Color Ultima
180 1 -0.9999 0 -0.0193 0.4931 -0.6533 4.0782 0 0 -0 0 0 -0 0 0 -0 0 0 0
185 1 -0.9999 0 -0.0198 0.5068 -0.6533 4.4595 0 0 -0 0 0 -0 0 0 -0 0 0 0
190 1 -0.9999 0 -0.0204 0.5205 -0.6533 4.9195 0 0 -0 0 0 -0 0 0 -0 0 0 0
195 1 -0.9999 0 -0.0209 0.5342 -0.6533 5.4853 0 0 -0 0 0 -0 0 0 -0 0 0 0
200 1 -0.9999 0 -0.0214 0.5479 -0.6533 6.1981 0 0 -0 0 0 -0 0.0012 0 -0 0 0 0
205 1 -0.9999 0 -0.022 0.5616 -0.6533 7.1239 0 0 -0 0.0004 0.0003 -0 0.1071 0 -0 0 0.0003 0.0001
210 1 -0.9999 0 -0.0226 0.5753 -0.6533 8.3747 0 0 -0.0002 0.0199 0.0108 -0.0001 4.1973 0 -0 0.0001 0.012 0.0032
215 0.9998 -0.9997 0.0001 -0.0252 0.5889 -0.6532 10.1567 0.0001 0.0001 -0.0041 0.414 0.1838 -0.0027 72.9841 0.0001 -0 0.002 0.198 0.0324
220 0.9974 -0.9971 0.001 -0.0512 0.601 -0.6516 12.8704 0.0012 0.0014 -0.04 4.0384 1.3972 -0.0264 580.934 0.0014 -0.0005 0.0141 1.4208 0.1193
225 0.9783 -0.9767 0.0065 -0.2027 0.6021 -0.6391 17.2415 0.0075 0.0084 -0.1863 18.7659 4.6975 -0.1235 2158.08 0.0084 -0.0022 0.0409 4.115 0.0867
230 0.8966 -0.8912 0.0224 -0.6437 0.5616 -0.5857 24.2406 0.026 0.028 -0.4003 40.2357 6.3078 -0.2677 3809 0.028 -0.0049 0.0261 2.5995 -0.1644
235 0.6987 -0.6885 0.0435 -1.2217 0.4433 -0.4565 34.5702 0.0504 0.0519 -0.3092 30.7944 2.0098 -0.2139 3626.75 0.0519 -0.004 -0.0676 -6.8748 -0.0997
240 0.4187 -0.4074 0.0488 -1.361 0.2679 -0.2735 48.191 0.0565 0.0558 0.1652 -17.2254 0.4231 0.0945 3408.71 0.0558 0.0014 -0.0971 -9.7985 -0.0227
245 0.1798 -0.1722 0.0327 -0.911 0.1156 -0.1174 64.4551 0.0379 0.0359 0.4473 -45.5831 5.1158 0.2833 4082.47 0.0359 0.0049 -0.0092 -0.8794 -0.1971
250 0.0534 -0.0503 0.0136 -0.3769 0.0344 -0.0349 82.5525 0.0157 0.0143 0.322 -32.7 6.4816 0.2066 3305.97 0.0143 0.0036 0.0467 4.7605 -0.0412
255 0.0108 -0.01 0.0036 -0.0992 0.007 -0.0071 101.798 0.0041 0.0036 0.12 -12.1728 3.4389 0.0774 1510.91 0.0036 0.0014 0.0324 3.2868 0.1451
260 0.0015 -0.0014 0.0006 -0.017 0.001 -0.001 121.702 0.0007 0.0006 0.0266 -2.6915 0.9828 0.0172 404.445 0.0006 0.0003 0.0101 1.0246 0.1043
265 0.0001 -0.0001 0.0001 -0.002 0.0001 -0.0001 141.935 0.0001 0.0001 0.0037 -0.3769 0.1682 0.0024 66.8956 0.0001 0 0.0018 0.1826 0.031
270 0 -0 0 -0.0002 0 -0 162.286 0 0 0.0003 -0.0349 0.0183 0.0002 7.148 0 0 0.0002 0.0203 0.0051
275 0 -0 0 -0 0 -0 182.618 0 0 0 -0.0022 0.0013 0 0.5115 0 0 0 0.0015 0.0005
280 0 -0 0 -0 0 -0 202.841 0 0 0 -0.0001 0.0001 0 0.0253 0 0 0 0.0001 0
285 0 -0 0 -0 0 -0 222.899 0 0 0 -0 0 0 0.0009 0 0 0 0 0
290 0 -0 0 -0 0 -0 242.753 0 0 0 -0 0 0 0 0 0 0 0 0
295 0 -0 0 -0 0 -0 262.382 0 0 0 -0 0 0 0 0 0 0 0 0

Here, it automatically creates Strike Prices around the current stock price (or any price in the past if you change the start_date) parameter as well as plots forward for the time to expiration. Things that you can change with ease yourself if you like. For example:

from financetoolkit import Toolkit

toolkit = Toolkit(["MSFT", "ASML"], api_key="FINANCIAL_MODELING_PREP_KEY")

rho = toolkit.options.get_rho(
    start_date="2020-01-02",
    strike_price_range=0.15,
    expiration_time_range=20,
    put_option=True,
    show_input_info=True
)

rho.loc['MSFT']

Which returns:

Based on the period 2013-01-22 to 2024-01-17 the following parameters were used:
Stock Price: ASML (291.79), Benchmark (305.06), MSFT (154.78)
Volatility: ASML (34.77%), Benchmark (17.46%), MSFT (26.99%)
Dividend Yield: MSFT (0.96%), ASML (0.6%)
Risk Free Rate: 1.88%
Strike Price 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10 2020-01-11 2020-01-12 2020-01-13 2020-01-14 2020-01-15 2020-01-16 2020-01-17 2020-01-18 2020-01-19 2020-01-20 2020-01-21
130 -0 -0 -0 -0 -0 -0 -0 -0 -0.0001 -0.0002 -0.0004 -0.0008 -0.0015 -0.0026 -0.0041 -0.0062 -0.0089 -0.0124 -0.0167
135 -0 -0 -0 -0 -0 -0.0001 -0.0003 -0.001 -0.0022 -0.0043 -0.0076 -0.0122 -0.0185 -0.0265 -0.0365 -0.0486 -0.0629 -0.0794 -0.0982
140 -0 -0 -0 -0.0003 -0.0015 -0.0045 -0.0101 -0.0192 -0.0322 -0.0493 -0.0709 -0.0968 -0.1271 -0.1616 -0.2003 -0.2429 -0.2895 -0.3397 -0.3934
145 -0 -0.0004 -0.0047 -0.017 -0.0396 -0.0727 -0.1156 -0.1676 -0.2277 -0.295 -0.3689 -0.4486 -0.5335 -0.6233 -0.7174 -0.8154 -0.917 -1.022 -1.13
150 -0.0055 -0.0485 -0.1251 -0.223 -0.3353 -0.4579 -0.5883 -0.7249 -0.8666 -1.0125 -1.162 -1.3145 -1.4698 -1.6275 -1.7873 -1.949 -2.1125 -2.2776 -2.4442
155 -0.2302 -0.4512 -0.671 -0.8903 -1.1094 -1.3284 -1.5474 -1.7663 -1.9853 -2.2043 -2.4234 -2.6425 -2.8617 -3.081 -3.3004 -3.5198 -3.7393 -3.9589 -4.1785
160 -0.4343 -0.8348 -1.2016 -1.5461 -1.8754 -2.1938 -2.504 -2.8078 -3.1063 -3.4006 -3.6912 -3.9787 -4.2636 -4.5461 -4.8265 -5.1051 -5.382 -5.6574 -5.9314
165 -0.452 -0.9034 -1.35 -1.7871 -2.2125 -2.6264 -3.0295 -3.4229 -3.8077 -4.1848 -4.5552 -4.9194 -5.2782 -5.6322 -5.9817 -6.3272 -6.6691 -7.0076 -7.3431
170 -0.4657 -0.9314 -1.397 -1.8618 -2.3248 -2.7846 -3.2402 -3.6907 -4.1358 -4.5753 -5.0092 -5.4376 -5.8608 -6.2788 -6.6921 -7.1007 -7.5049 -7.9051 -8.3013

Furthermore, each module now has it's own dedicated Jupyter Notebook. Find all of them below or on my website here.

v1.7.4

5 January 2024

This release features the Black Scholes Model, Present Value of Growth Opportunities (PVGO) and a variety of bug fixes.

Starting with the Black Scholes model, I've built in a method that automatically calculates the theoretical options value with strike prices that are near the current stock price and for a lengthy period of time. All of this you can expand yourself if desired with the strike_price_range, strike_step_size and expiration_time_range parameters. By default, the strike prices between 75% and 125% of the current stock price are used and the time to expiration is calculated for the upcoming 30 days.

For example:

from financetoolkit import Toolkit

companies = Toolkit(
    tickers=['GOOGL', "MSFT", 'AAPL'],
    api_key="FMP_KEY",
    start_date='2022-01-01',
    end_date='2023-01-01'
)

companies.risk.get_black_scholes_model()

Which returns:

image

I've also added in the Present Value of Growth Opportunities (PVGO), a metric that uses WACC and Earnings per Share to determine the attractiveness of companies in the near future. This was requested by #88.

from financetoolkit import Toolkit

companies = Toolkit(
    tickers=['GOOGL', "MSFT", 'AAPL'],
    api_key="FMP_KEY",
    quarterly=True
)

companies.models.get_present_value_of_growth_opportunities(calculate_daily=True)

Which returns:

image

Next to that, #94 noted that the Average Shares got adjusted through currency conversions. This has been corrected. Read in the new Q&A why numbers can sometimes deviate from FinancialModelingPrep.

v1.7.3

2 January 2024

Happy New Year Everyone 🍾

This release includes an entirely new class which is the Discovery class. This class will help in discovering new instruments that can be inputted directly into the Finance Toolkit for further analysis. Find the documentation here.

For example, by importing the Discovery module directly, it is possible to obtain a large list of companies.

from financetoolkit import Discovery

discovery = Discovery(api_key="FINANCIAL_MODELING_PREP_KEY")

stock_list = discovery.get_stock_list()

# The total list equals over 60.000 rows
stock_list.iloc[48000:48010]

Which returns:

Symbol Name Price Exchange Exchange Code
RBL.AX Redbubble Limited 0.54 Australian Securities Exchange ASX
RBL.BO Rane Brake Lining Limited 870.05 Bombay Stock Exchange BSE
RBL.NS Rane Brake Lining Limited 870.05 National Stock Exchange of India NSE
RBLAY Robinsons Land Corporation 4.61 Other OTC PNK
RBLBANK.BO RBL Bank Limited 280.9 Bombay Stock Exchange BSE
RBLBANK.NS RBL Bank Limited 280.9 National Stock Exchange of India NSE
RBLN-B.CO Roblon A/S 91.8 Copenhagen CPH
RBLX Roblox Corporation 45.72 New York Stock Exchange NYSE
RBMNF Rugby Resources Ltd. 0.065 Other OTC PNK
RBMS.JK PT Ristia Bintang Mahkotasejati Tbk 50 Jakarta Stock Exchange JKT

It also enables stock screeners:

from financetoolkit import Discovery

discovery = Discovery(api_key="FINANCIAL_MODELING_PREP_KEY")

discovery.get_stock_screener(
    market_cap_higher=1000000,
    market_cap_lower=200000000000,
    price_higher=100,
    price_lower=200,
    beta_higher=1,
    beta_lower=1.5,
    volume_higher=100000,
    volume_lower=2000000,
    dividend_higher=1,
    dividend_lower=2,
    is_etf=False
)

Which returns:

Symbol Name Market Cap Sector Industry Beta Price Dividend Volume Exchange Exchange Code Country
NKE NIKE, Inc. 163403295604 Consumer Cyclical Footwear & Accessories 1.079 107.36 1.48 1045865 New York Stock Exchange NYSE US
SAF.PA Safran SA 66234006559 Industrials Aerospace & Defense 1.339 160.16 1.35 119394 Paris EURONEXT FR
ROST Ross Stores, Inc. 46724188589 Consumer Cyclical Apparel Retail 1.026 138.785 1.34 169879 NASDAQ Global Select NASDAQ US
HES Hess Corporation 44694706090 Energy Oil & Gas E&P 1.464 145.51 1.75 123147 New York Stock Exchange NYSE US

Which then can be directly inputted into the Finance Toolkit:

from financetoolkit import Toolkit

companies = Toolkit(
    tickers=['NKE', 'SAF.PA', 'ROST', 'HES'],
    api_key="FINANCIAL_MODELING_PREP_KEY",
)

companies.ratios.get_price_earnings_ratio()

Which returns:

2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
HES 8.4355 -3.9366 -2.8064 -3.3368 -39.7483 -79.129 -5.4733 25.1712 19.5719
NKE 29.4181 31.0527 21.9158 23.5325 60.6729 39.2127 86.2596 45.9014 30.8813 33.6161
ROST 19.5859 19.8813 21.7047 21.3971 18.6637 24.4335 493.771 22.9419 26.2563
SAF.PA -152.997 -57.6348 14.3119 7.1287 34.6723 24.0264 142.461 686.616 -21.0077

Next to that, I've also grouped the TQDM statements when using Ratios or Models. So instead of 5 bars, it displays just 2. Furthermore, I've extended the custom ratios functionality, see here.

v1.7.2

21 December 2023

Added a lot more economic metrics (over 50) into the Finance Toolkit, find the total list here. For example, get insights into how the United States Government spend their income:

from financetoolkit import Economics

economics = Economics()

central_government_spending = economics.get_central_government_spending()

central_government_spending['United States']

Which returns:

General Public Services Defence Public Order and Safety Economic Affairs Environmental Protection Housing and Community Amenities Health Recreation, Culture and Religion Education Social Protection
2007 0.1578 0.186 0.0148 0.0578 0 0.0192 0.2486 0.0015 0.0222 0.2921
2008 0.1392 0.1861 0.0148 0.069 0 0.0188 0.2369 0.0014 0.0221 0.3117
2009 0.1198 0.1772 0.0148 0.0639 0 0.0406 0.2417 0.0014 0.028 0.3127
2010 0.1211 0.1759 0.0148 0.0585 0 0.0309 0.2416 0.0015 0.0346 0.3211
2011 0.1324 0.1754 0.0149 0.0562 0 0.0271 0.2416 0.0014 0.0337 0.3173
2012 0.1348 0.173 0.0154 0.056 0 0.0216 0.2491 0.0014 0.0296 0.3191
2013 0.1333 0.162 0.0145 0.055 0 0.0172 0.2589 0.0013 0.0281 0.3296
2014 0.135 0.1525 0.0143 0.0524 0 0.0168 0.2765 0.0013 0.0269 0.3244
2015 0.1294 0.1461 0.0141 0.0473 0 0.0161 0.2919 0.0012 0.026 0.3279
2016 0.1321 0.141 0.0141 0.0526 0 0.0156 0.2952 0.0013 0.0244 0.3238
2017 0.1325 0.1408 0.0137 0.0526 0 0.0171 0.2961 0.0013 0.0233 0.3226
2018 0.1407 0.1427 0.0135 0.0519 0 0.014 0.2967 0.0012 0.0226 0.3165
2019 0.1417 0.1461 0.013 0.052 0 0.0133 0.2971 0.0012 0.021 0.3147

Or plotted:

image

Or see the Income Inequality in the Netherlands:

from financetoolkit import Toolkit

toolkit = Toolkit("MSFT")

income_inequality = toolkit.economics.get_income_inequality()

income_inequality['Netherlands']

Which returns:

Gini Coefficient P90/P10 P90/P50 P50/P10 Palma Ratio S80/S20
2013 0.287 3.4 1.8 1.9 1.05 4.3
2014 0.305 3.4 1.8 1.9 1.16 4.6
2015 0.305 3.4 1.8 1.9 1.06 4.4
2016 0.292 3.4 1.8 1.9 1.07 4.4
2017 0.298 3.4 1.8 1.9 1.11 4.5
2018 0.295 3.3 1.8 1.9 1.09 4.4
2019 0.312 3.4 1.8 1.9 1.21 4.7
2020 0.295 3.3 1.8 1.9 1.09 4.4
2021 0.297 3.4 1.8 1.9 1.1 4.5

Or plotted:

image

And so much more!

v1.7.1

18 December 2023

In addition to the many new Economics indicators in the previous release, I've added some new key economic rates.

MarketExpectationsFinanceToolkit

I've added in the European Central Banks which include:

  • The main refinancing operations (MRO) rate is the interest rate banks pay when they borrow money from the ECB for one week. When they do this, they have to provide collateral to guarantee that the money will be paid back.
  • The marginal lending facility rate is the interest rate banks pay when they borrow from the ECB overnight. When they do this, they have to provide collateral, for example securities, to guarantee that the money will be paid back.
  • The deposit facility rate which is one of the three interest rates the ECB sets every six weeks as part of its monetary policy. The rate defines the interest banks receive for depositing money with the central bank overnight.

These can be shown by using:

from financetoolkit import Economics

economics = Economics(start_date='2000-01-01')

economics.get_european_central_bank_rates()

Which returns (when plotted):

image

I've also added in the Federal Funds rates which include:

  • The effective federal funds rate (EFFR) which is calculated as a volume-weighted median of overnight federal funds transactions reported in the FR 2420 Report of Selected Money Market Rates.
  • The overnight bank funding rate (OBFR) which is calculated as a volume-weighted median of overnight federal funds transactions, Eurodollar transactions, and the domestic deposits reported as “Selected Deposits” in the FR 2420 Report.
  • The TGCR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon.
  • The BGCR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon as well as GCF Repo transaction data obtained from the U.S. Department of the Treasury’s Office of Financial Research (OFR).
  • The SOFR which is calculated as a volume-weighted median of transaction-level tri-party repo data collected from the Bank of New York Mellon as well as GCF Repo transaction data and data on bilateral Treasury repo transactions cleared through FICC's DVP service, which are obtained from the U.S. Department of the Treasury’s Office of Financial Research (OFR).

These can be shown by using (and defining the rate):

from financetoolkit import Economics

economics = Economics(start_date='2016-01-01')

# Effective Federal Funds Rate
economics.get_federal_reserve_rates(rate='EFFR')

# Secured Overnight Financing Rate
economics.get_federal_reserve_rates(rate='SOFR')

Which returns (when plotted):

image

image

v1.7.0

12 December 2023

This release features an entirely new module called Economics. This is meant to collect key economic indicators such as the Gross Domestic Product (GDP), Consumer Price Index (CPI) and Long and Short Term Interest Rates for 60+ countries. Find a complete overview here. This module can be called via the Toolkit:

from financetoolkit import Toolkit

companies = Toolkit(tickers=["AAPL", "TSLA"], api_key="FMP_KEY")

companies.economics.get_house_prices()

But also as standalone module (given that it doesn't require a company ticker):

from financetoolkit import Economics

economics = Economics()

economics.get_house_prices()

Both return the same dataset:

Australia Austria Belgium Brazil Bulgaria Canada Chile China Colombia Croatia Czech Republic Denmark EA Estonia Euro Area 17 Finland France Germany Greece Hungary Iceland India Indonesia Ireland Israel Italy Japan Latvia Lithuania Luxembourg Mexico Netherlands New Zealand Norway OECD - Total Poland Portugal Romania Russia Saudi Arabia Slovakia Slovenia South Africa South Korea Spain Sweden Switzerland Turkey United Kingdom United States
2013 84.1065 92.1 98.962 98.269 95.915 89.9958 78.0367 96.4912 85.1748 104.627 93.875 90.0977 98.267 82.2933 98.4009 100.353 103.8 92.5982 113.816 84.87 85.2075 76.6863 88.5178 77.0045 88.8228 109.1 96.148 97.6225 90.645 90.8947 88.6885 95.7715 83.5338 91.75 92.1431 97.4165 93.085 99.26 95.574 nan 93.5868 106.21 87.4525 95.7696 96.2393 80.785 94.867 75.946 87.3505 90.7087
2014 91.7202 95.33 98.417 99.1345 97.29 94.828 88.4455 101.132 91.9212 102.975 96.175 93.4987 98.482 93.5795 98.5693 99.995 101.925 95.499 105.32 88.4275 92.3855 88.032 94.73 89.7232 94.4668 103.95 97.648 103.475 96.47 94.8777 92.4655 96.5565 88.9588 94.25 95.5783 98.4538 97.0375 97.22 97.9095 101.189 94.9068 99.2025 94.146 97.2716 96.5393 88.4025 97.4497 86.1545 94.3388 95.1076
2015 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
2016 105.5 108.532 102.641 100.868 107.02 110.589 106.573 112.23 109.995 100.888 107.15 104.727 104.01 104.745 104.012 101.285 100.925 107.527 97.623 113.377 109.767 106.686 103.159 107.484 107.459 100.25 102.213 108.487 105.4 106.006 107.282 105.052 114.178 107.025 105.352 101.859 107.115 105.95 102.856 95.091 106.703 103.252 105.616 101.622 104.623 108.243 101.627 113.615 106.975 105.586
2017 114.308 114.26 106.373 101.733 116.295 123.751 115.275 126.989 117.332 104.745 119.7 109.378 108.513 110.511 108.454 102.388 103.975 114.104 96.6342 127.24 131.196 115.658 106.415 119.162 111.649 99.175 104.805 118.013 114.797 111.96 115.687 112.978 121.596 112.35 111.13 105.768 117.015 112.355 108.782 88.9675 112.99 111.785 110.064 102.854 111.105 115.427 103.591 125.392 111.834 112.078
2018 112.664 119.64 109.415 102.599 123.955 128.378 126.812 134.268 123.825 111.14 130 114.529 113.668 117.066 113.604 103.335 107.15 121.681 98.379 145.495 142.006 122.248 109.895 131.363 110.724 98.625 106.849 129.3 123.18 119.862 125.951 123.656 125.966 113.975 116.592 112.765 129.032 118.618 116.147 86.4625 121.32 121.547 114.246 104.275 118.58 114.35 106.728 134.891 115.496 118.951
2019 108.084 126.6 113.779 103.464 131.417 129.959 137.5 139.503 130.601 121.103 141.9 117.53 118.641 125.267 118.505 103.77 110.675 128.707 105.481 170.167 148.291 126.309 111.91 134.431 112.812 98.525 108.553 140.875 131.61 131.987 136.739 132.658 129.9 116.8 121.327 122.55 141.882 122.69 119.822 83.5023 132.395 129.69 118.273 103.968 124.715 117.188 110.572 141.024 116.592 124.942
2020 113.916 136.311 118.595 104.332 137.412 138.454 146.659 144.577 133.834 130.38 153.85 123.531 124.813 132.792 124.761 105.595 116.825 138.685 110.223 178.577 157.788 129.465 113.646 134.847 116.261 100.4 108.63 145.768 141.178 151.115 144.687 142.761 143.109 121.775 128.945 135.335 154.327 128.435 144.26 84.833 145.061 135.657 121.228 107.451 127.505 122.11 115.355 173.709 119.904 134.761
2021 133.764 153.262 127.058 105.198 149.333 159.222 164.029 150.101 141.909 139.912 184.225 138.01 134.675 152.778 134.765 110.448 124.625 154.739 118.606 208.037 177.563 132.749 115.27 146 126.076 102.95 115.102 161.645 163.84 172.151 156.073 164.241 180.981 134.525 145.113 147.76 168.84 134.088 175.268 85.7263 154.334 151.317 126.269 116.89 132.195 134.463 123.334 237.534 130.515 157.24
2022 142.65 170.765 134.194 106.063 169.917 177.235 175.906 151.385 152.542 160.685 215.275 137.36 144.219 186.76 144.178 111.745 132.5 162.941 132.69 254.345 214.848 136.925 nan 163.977 147.852 106.875 124.755 184.005 195.048 188.6 169.973 186.321 182.022 141.575 165.45 165.18 190.17 143.697 225.506 87.5558 175.471 173.648 130.758 119.32 141.978 139.25 132.603 601.714 143.214 179.097

It is also possible to plot things such as the Employment Rate as also found in the README:

Economics

Or the Long Term (10 year) and Short Term (3 month) Interest Rates:

output
output2

Or any of the other metrics:

  • Gross Domestic Product (GDP) including Growth and Forecasts
  • Consumer Confidence Index (CCI)
  • Business Confidence Index (BCI)
  • Composite Leading Indicator (CLI)
  • Consumer Price Index (CPI)
  • Producer Price Index (PPI)
  • House and Rent Prices
  • Unemployment Rates
  • Long Term Interest Rates (10 year)
  • Short Term Interest Rates (3 month)
  • Purchasing Power Parity (PPP)
  • Exchange Rates

Are you looking for any specific economic parameter? Let me know and I'll start working on it.

v1.6.6

7 December 2023

This releases introduces the GARCH model including volatility forecasting. Next to that, it includes a bugfix for the currency conversion.

Designed by @northern-64bit (LinkedIn) in #82, this release introduces GARCH (Generalized autoregressive conditional heteroskedasticity) which is stochastic model for time series, which is for instance used to model volatility clusters, stock return and inflation. It is a generalisation of the ARCH models.

It can be found inside the risk module and can be ran with the following code:

from financetoolkit import Toolkit

toolkit = Toolkit(["AMZN", "TSLA"], api_key=FMP_KEY)

toolkit.risk.get_garch()

Which produces the following result:

Date AMZN TSLA Benchmark
2012 0 0 0
2013 0.2038 5.027 0.024
2014 0.4016 10.2307 0.0537
2015 0.53 13.2345 0.0688
2016 0.7664 15.6152 0.079
2017 0.8181 17.5204 0.0887
2018 0.8896 19.0642 0.0997
2019 0.9235 20.2789 0.104
2020 0.9479 21.2567 0.1169
2021 1.0203 27.5585 0.1209
2022 1.0201 27.0986 0.129
2023 1.0445 26.7482 0.1305

You can also forecast in the future for any period and for any interval. For example, the quarterly expected volatility estimations can be shown with:

from financetoolkit import Toolkit

toolkit = Toolkit(["AMZN", "TSLA"], api_key=FMP_KEY)

toolkit.risk.get_garch_forecast(period='quarterly')

Which returns:

AMZN TSLA Benchmark
2024Q1 0 0 0
2024Q2 0 0 0
2024Q3 0.006 0.3185 0.0003
2024Q4 0.0114 0.6051 0.0006
2025Q1 0.0162 0.8631 0.0008
2025Q2 0.0206 1.0953 0.001
2025Q3 0.0245 1.3042 0.0012
2025Q4 0.0281 1.4923 0.0014
2026Q1 0.0312 1.6615 0.0015
2026Q2 0.0341 1.8138 0.0017

Next to that, a bug fix went in related to the currency conversions which makes it more robust when there is data missing. If you didn't know, when you have a Premium FMP plan the Finance Toolkit will now automatically convert currencies that do not match up with the historical data. For more see here: https://github.com/JerBouma/FinanceToolkit/releases/tag/v1.6.3

v1.6.3

4 December 2023

This release features currency conversions. A user noticed that the financial statements are not always in the expected currency (different from the historical data):

image

This could lead to confusion when comparing numbers between companies and or when calculating ratios that require both data from the financial statement and the historical market data. This has now been resolved with an automatic converter that converts the financial statements accordingly. With this, the end of quarter or end of year exchange rate is used.

image

This is also saved in a seperate function called get_exchange_rates as shown below:

image

This is quite a major change given that there are plenty of financial statements that report their financial statements in their local currency while the listed historical prices are in USD. This ensures that those numbers can be compared. This can be disabled by setting convert_currency to False in the Toolkit initialisation. Note that by default it is automatically turned off when using the Free plan of FinancialModelingPrep as it could drain the API calls for that specific day.

I've also added in a parameter that recognises if you are using a Free or Premium plan from FinancialModelingPrep. This is a dependency for the sleep_timer which will wait a maximum of 60 seconds before making a new request to FMP. This is only relevant for the Premium plans since there is a rate limit per minute. For the Free plan it doesn't matter given that you are limited to 250 requests per day. In any case, this should make the Free experience smoother since you are not waiting for no reason. This solves #80.

Note: this consumes 1 API call so if you don't want that, just set sleep_timer to True or False.

if sleep_timer is None:
    # This tests the API key to determine the subscription plan. This is relevant for the sleep timer
    # but also for other components of the Toolkit. This prevents wait timers from occurring while
    # it wouldn't result to any other answer than a rate limit error.
    determine_plan = helpers.get_financial_data(
        url=f"https://financialmodelingprep.com/api/v3/income-statement/AAPL?period=quarter&apikey={api_key}",
        sleep_timer=False,
    )

    self._fmp_plan = "Premium"

    for option in ["NOT AVAILABLE", "LIMIT REACH", "INVALID API KEY"]:
        if option in determine_plan:
            self._fmp_plan = "Free"
            break
else:
    self._fmp_plan = "Premium"

v1.6.0

4 November 2023

I did a new release last week but for everything I've added in it made sense to do another full release. This release includes new models and ESG scores and a lot of the code has been refactored, many new tests have been added and a lot of bug fixes went in. For example, @brianrasmusson noticed in #76 that Apple's data was a bit out of whack. This has now been resolved. I've also added in a lot pretty graphs into the README to show what you can really do with the data, e.g. see this one on the Value of Risk:

Risk

It is now possible to view ESG Scores for any range of companies with get_esg_scores:

image

Next to that, within the Models module, two new models are included. These are Altman Z-Score and Piotroski F-score. The former calculates the chance of bankruptcy based on a set of criteria:

image

The latter scores the financial strength of the company:

image

Furthermore, I've added a performance measurement which shows the period growth rate that has occurred (taking out fluctuations over time as shown in the plot below):

image

Other than that, I've extended the examples and gave more explanation how to add in your own datasets.

v1.5.0

27 October 2023

Introducing the power of Threading into the FinanceToolkit. Update now via pip install financetoolkit -U.

As an example, obtaining the balance sheet statements of 345 different companies for the period 1983 to 2023 takes less than 40 seconds. This makes data collection extremely quick and makes the FinanceToolkit an invaluable tool for any financial specialist.

image

Next to that, given that there are rate limits, these are correctly dealt with through sleep timers. If you have a subscription from FinancialModelingPrep that limits you to 300 requests per minute, the FinanceToolkit will deal with this and will wait until it can make requests again.

Furthermore, if some of the historical data is not available from FinancialModelingPrep it will try YahooFinance instead making sure that you don't lose vital data for your calculations.

image

Of course, all of this extends in all functionality. E.g. see Jensen's Alpha for all 345 tickers on a quarterly basis. Given that the calculations are done by the FinanceToolkit, this takes just a few seconds.

image
It's time to level up. 🚀

v1.4.1

20 October 2023

I've added in the Dividend Calendar which can be shown by get_dividend_calendar():

from financetoolkit import Toolkit

API_KEY = "FINANCIAL_MODELING_PREP_KEY"

# Initialize the Toolkit with company tickers
companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2005-01-01"
)

companies.get_dividend_calendar()

Which returns:

image

Next to that, this release introduces historical data from FinancialModelingPrep. This is enabled by default when you provide an API key but can be changed back by setting historical_source to "YahooFinance" when initialising the Toolkit. When you don't provide an API key it defaults to Yahoo Finance.

This is done to prevent rate limits from becoming an issue when you have purchased a FinancialModelingPrep subscription given that Yahoo Finance will rate limit at some point. It of course makes little sense that you are paying and still get rate limited!

E.g. the following will net you the same result:

from financetoolkit import Toolkit

API_KEY = "FINANCIAL_MODELING_PREP_KEY"

# Use FinancialModelingPrep to obtain Historical Data
companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2005-01-01"
)

companies.get_historical_data()

# Use Yahoo Finance to obtain Historical Data even though you set a FinancialModelingPrep API Key
companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2005-01-01", historical_source='YahooFinance'
)

companies.get_historical_data()

# Use Yahoo Finance to obtain Historical Data without needing to set an API Key
companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], start_date="2005-01-01"
)

companies.get_historical_data()

Which returns:

image

v1.4.0

12 October 2023

This releases includes the Fama and French 5-factor model. Something I've been wanting to add into the Finance Toolkit for some time now. This allows you to understand the explanatory power of the following factors on each ticker included in the Toolkit on any period, let it be yearly, quarterly, monthly or weekly:

  • Market Risk Premium (Mkt-RF): Represents the additional return that investors expect to earn for taking
    on the risk of investing in the overall market as opposed to a risk-free asset.
  • Size Premium (SMB): Reflects the historical excess return of small-cap stocks over large-cap stocks.
  • Value Premium (HML): Captures the historical excess return of value stocks over growth stocks.
  • Profitability (RMW): Measures the historical excess return of high profitability stocks over
    low profitability stocks.
  • Investment (CMA): Quantifies the historical excess return of low investment stocks over
    high investment stocks.

I've added correlation functions that help you understand how factors correlate with each other over time. For example, the following GIF is created with data from the function performance.get_factor_correlations.

Factor Correlations 10-Year Period Finance Toolkit

Next to that, you can perform Linear Regressions on each factor and each factor combination to discover sensitivities of individual assets to each factor (this is not only limited to companies but can also be currencies, commodities, ETFs and more):

from financetoolkit import Toolkit

# Initialize the Finance Toolkit
companies = Toolkit(
    tickers=["MSFT", 'AAPL', 'TSLA', 'GOOG', "AMZN", 'MU'], api_key=FMP_KEY, quarterly=False
)
companies.performance.get_fama_and_french_model()

Which returns regression coefficients for all factors for each individual stock:

image

You have the option to show both the results from a simple linear regression (which is defined as Excess Return = Intercept + Slope * Factor Value + Residuals) or a multi linear regression (which is defined as Excess Return = Intercept + Beta1 * Mkt-RF + Beta2 * SMB + Beta3 * HML + Beta4 * RMW + Beta5 * CMA + Residuals) the latter is the default. E.g. you can show the explanatory power of each individual factor for example for Microsoft as follows:

from financetoolkit import Toolkit

# Initialize the Finance Toolkit
companies = Toolkit(
    tickers=["MSFT"], api_key=FREE_FMP_KEY, quarterly=False
)
result = companies.performance.get_fama_and_french_model(period='quarterly', method='simple')

result['MSFT'].xs('R Squared', level=1, axis=1).plot(figsize=(15, 5), title=f'Factor Sensitivities of Microsoft')

Which returns the following:

image

v1.3.10

7 October 2023

This releases features a couple of Quality of Life improvements and some bug fixes:

  • A user noticed that for some tickers, e.g. currencies, it returned an error since the index wasn't matched up correctly. This has now been corrected by only keeping the first duplicate if any are found. The issue here was that the same index was reported twice (e.g. 2020-05-06 being reported twice in the index) which will cause an issue if you try to combine such a DataFrame with other DataFrames.
  • For all functionality, if the ticker doesn't correspond to the correct type, the Toolkit will mention this to you. E.g. if you would try to obtain an Income Statement from a ticker such as "^GSPC" (which is the S&P 500 index) it will return a well-written error. This also applies to if a subset of your tickers is not marked as an Equity.

If you didn't know, any type of asset class works with the Finance Toolkit (e.g. Equities, Currencies, Cryptocurrencies, ETFs, Mutual Funds, Indices, Money Markets, Commodities and more) which also allows you to obtain detailed calculations such as the Conditional Value at Risk (cVaR).

image

v1.3.9

2 October 2023

This release mainly introduces fixes to existing functionality, most importantly the calculation of trailing ratios. The timing of the trailing ratios was a bit off as it took to the sum of the periods after calculation instead of before. This has now been fixed.

If you didn't know, you can calculate trailing ratios (e.g. revenue TTM, price-to-earnings TTM) and much more by using the trailing parameter. This parameter represents the amount of periods you wish to combine to calculate the trailing ratio, e.g. if you use quarterly=True in the Toolkit initialisation and then set trailing=4 for any ratio, you are able to calculate any TTM ratio.

image

The same can be done for a financial statement.

image

I also noticed that the days used for calculating Efficiency Ratios was set to 365 by default. This is fine for annual calculations but for quarterly calculations it should be divided by 4. This is now done automatically.

image

v1.3.8

26 September 2023

A user of the Finance Toolkit reported some issues with the dividends. Noticed it was unfortunately broken. This has now been fixed. Other than that, I've updated a couple of docstrings.

image

v1.3.7

23 September 2023

This release adds a minor, but important, function (get_historical_statistics) that shows in what currency the historical data is denoted. Besides that, it also gives some insights since when the product was traded and in what timezone it belongs.

image

v1.3.6

19 September 2023

This version introduces ISIN support. If you submit an ISIN, it will find the relevant symbol and use that instead. It will also mention to what symbol it made the conversion so it is clear what ticker to look at. I've also added some dependencies, mostly a clean-up (I was struggling with getting SciPy to work, now this is built in with Pandas). Next to that, I've added the Finance Database as a dependency as in the future the Finance Toolkit will feature functionality from this database.

image

v1.3.5

17 September 2023

This is a minor release getting some bugfixes in and making the code a bit more robust. Less errors should now occur when you do not have the correct API key set and someone noticed that if you call the Statistics functionality before anything else it returns an error. This is now fixed.

If you feel like any functionality is missing, definitely let me know and we can start adding them in!

v1.3.4

12 September 2023

This release introduces two new models which are the Weighted Average Cost of Capital (WACC) and the Intrinsic Valuation.

As an example, see the WACC below. For the method of calculation please see here.

image

Furthermore, the Intrinsic Valuation attempts to calculate the intrinsic value of an asset. This does require some manual input through which are growth, perpetual growth and WACC numbers given that this model is highly subjective and asset dependent.

image

The growth numbers can be specified for each asset individually as well. For the method of calculation please see here.

image

Next to that, I've introduced trailing calculations for the Financial Statements and Ratios. As an example, you can now see the Trailing P/E ratio with the following code. Note that you need to have quarterly=True to get the actual TTM (otherwise you will take the trailing value over 4 years).

image

v1.3.3

10 September 2023

This new release features a whole lot of new features yet again. This includes the following:

Performance Metrics

There is now a large list of performance metrics to be found in the performance class in similar fashion as e.g. ratios. This gets you the following:

  • Alpha
  • Jensen's Alpha
  • Beta
  • Capital Asset Pricing Model (CAPM)
  • Treynor Ratio
  • Sharpe Ratio
  • Sortino Ratio
  • Ulcer Performance Index (UPI)
  • M2 Ratio
  • Tracking Error
  • Information Error

This is an extra powerful class as you can get these ratios "within" periods. This means that if you select the period "quarterly", it will calculate the ratios for the days within each quarter. As an example:

image

Risk Metrics

Not only Performance Metrics are added in but courtesy of @northern-64bit, it is now also possible to observe the following risk metrics:

  • Value at Risk (VaR) with distributions Historical, Gaussian, Student-t, Cornish-Fisher.
  • Conditional Value at Risk (cVaR) with distributions Historical, Gaussian, Laplace, Logistic.
  • Entropic Value at Risk (eVaR) with a Gaussian distribution.
  • Ulcer Index (UI)
  • Maximum Drawdown (MDD)
  • Skewness
  • Kurtosis

Just like with the performance metrics, you can view these for within each period as well. E.g. on a weekly basis:

image

Risk Free Rates and Benchmarks

Within the Toolkit class (upon initialisation) a benchmark can be defined. By default this is set to "^GSPC" which is the S&P 500 index. This benchmark is required to calculate metrics such as CAPM, Beta and (Jensens Alpha) and is very neat to have when you wish to analyze and compare tickers. It is of course possible to change this benchmark ticker to anything (or disable it by setting it to None).

Next to that, it is also possible to define a risk free rate, this can be '13w', '5y', '10y' or '30y' and defaults to '10y'. Both settings will lead to different results for some of the calculations and it is therefore important you set a benchmark and risk free rate that matches your beliefs and analysis. As an example:

image

Other than that, many improvements behind the scenes were made. E.g. it is now really easy to add new ratios since all the data has been prepared properly and some fixes have been made to data that could sometimes mess up in niche scenarios. Next to that, the documentation has been greatly extended: https://www.jeroenbouma.com/projects/financetoolkit/docs.


Find a variety of How-To Guides including Code Documentation for the FinanceToolkit here.


v1.3.2

3 September 2023

This release focusses on numerous smaller enhancements that make the quality of the data better. For example, through grouping of historical data, I've noticed that it resulted in numerous NaN values given that for that particular stock there is no data available. These were minor details but it slightly messed up any form of charting. Next to that, technical indicators falsely calculated with NaN values.

Next to that, I noticed that if you input a ticker that had no data outside of the defined period (with start and end) it gave an error. This has now been tackled. Much more is upcoming with a new Risk class (for Value at Risk, Conditional Value at Risk and much more) currently in the works!

All in all, you can now generate charts like these with relative ease through collecting data from the FinanceDatabase and FinanceToolkit incredibly quickly being able to do really proper investment research.

As an example, these are companies found through the Finance Database:

image

Which, once data is collected through the Finance Toolkit, can return:

image

Also did you notice that really any asset works and not only companies? :)

image

v1.3.1

29 August 2023

This is a massive release to the FinanceToolkit adding a lot more functionality including 30+ technical indicators. These are the key improvements:

Added a technicals class, this has the option to calculate over 30 technical indicators (e.g. Relative Strength Index and Bollinger Bands) with the chosen dataset. Just like other components of the FinanceToolkit, this works very well with any list of tickers. As an example, the following collects all technical indicators:

from financetoolkit import Toolkit

toolkit = Toolkit(tickers=["AAPL", "MSFT", "AMZN"])

toolkit.technicals.collect_all_indicators()

This returns the following:

image

Just like with ratios, it is also possible to show single indicators:

from financetoolkit import Toolkit

toolkit = Toolkit(tickers=["AAPL", "MSFT", "AMZN"])

toolkit.technicals.get_bollinger_bands()
image

This is a major addition as it is now possible to do quantitative research both based on fundamental data and technical indicators further accelerating the package to also become a great place for Machine Learning professionals.

I've expanded the historical dataset with new vital columns. It not only returns Open, High, Low, Close and Returns but also shows Dividends, Volatility, Excess Returns (minus Risk Free Rate), Excess Volatility and Cumulative Returns.

from financetoolkit import Toolkit

toolkit = Toolkit(tickers=["AAPL", "MSFT", "AMZN"])

toolkit.get_historical_data()
image

I've reworked a lot of docstrings. This makes it possible to better understand what a function is providing and what the meaning is of the result. This is also further highlighted on the documentation page here. As an example:

"""
Calculate the debt to equity ratio, a solvency ratio that measures the
proportion of a company's equity that is financed by debt.

The debt to equity ratio, also known as the D/E ratio, indicates the relative
contribution of debt and equity to a company's capital structure. It helps assess
the level of financial risk a company carries due to its debt obligations. A higher
ratio implies a higher reliance on debt to finance the business, which could increase
risk but also potentially lead to higher returns for shareholders.

Args:
    rounding (int, optional): The number of decimals to round the results to. Defaults to 4.
    growth (bool, optional): Whether to calculate the growth of the ratios. Defaults to False.
    lag (int | str, optional): The lag to use for the growth calculation. Defaults to 1.

Returns:
    pd.DataFrame: Debt to equity ratio values.

Notes:
- The method retrieves historical data and calculates the ratio for each asset in the Toolkit instance.
- If `growth` is set to True, the method calculates the growth of the ratio values using the specified `lag`.

As an example:

from financetoolkit import Toolkit

toolkit = Toolkit(["AAPL", "TSLA"], api_key=FMP_KEY)

debt_to_equity_ratios = toolkit.ratios.get_debt_to_equity_ratio()
"""

I've added in a risk free rate. This is based on ^TNX which is the 10-year Treasury Rate. This is relevant for calculations that require a Risk Free Rate such as the Sharpe Ratio. This is hidden in the back-end but can be retrieved (after using get_historical_data) with companies._daily_risk_free_rate. As an example:

from financetoolkit import Toolkit

toolkit = Toolkit(tickers=["AAPL", "MSFT", "AMZN"])

toolkit.get_historical_data()

toolkit._daily_risk_free_rate

Which returns:

image

v1.2.6

24 August 2023

Major release with numerous new functionality and a lot of misc fixes. The major components are:

Calculating custom ratios are greatly improved with a lot of robustness. This now features the following things:

  • Simple operations such as: 'Quick Assets': 'Cash and Short Term Investments + Accounts Receivable'
  • Working with multiple operations: 'Cash Op Expenses':'Cost of Goods Sold + Selling, General and Administrative Expenses - Depreciation and Amortization',
  • Using curly brackets: 'WC / Net Income as %': '(Working Capital / Net Income) * 100',
  • Defining a criteria: 'Large Revenues': 'Revenue > 1000000000',
  • Using actual numbers: 'Daily Cash Op Expenses': 'Cash Op Expenses / 365',
  • Combining earlier defined formulas: 'Defensive Interval':'Quick Assets / Daily Cash Op Expenses'

As an example (also see the README and Notebooks):

image

The historical dataset now calculates OLHC, volumes, returns, cumulative returns and volatility. This also works for different periods (e.g. yearly) to see how volatility moved over the years for example. Next to that, within the backend a bit more data is collected than displayed to overcome issues with incomplete quarters or years.

image

It is possible to view treasury rates over the last 3 months for multiple maturities. This makes it possible to create yield curves for multiple months and can serve as a basis for discounting.

image

Improved the External Datasets usage. Previously, this was a little bit buggy and could result in a lot of errors when things didn't match up right. This has now been corrected and the example is also better explained. Please see the updated Jupyter Notebook here.

v1.2.5

20 August 2023

I've been busy again to improve numerous docstrings, optimize code and ensure that there is better error handling. I've introduced some other features that have been requested which are the following:

An earnings calendar in which all exact earnings dates in the past and in the future are displayed including estimates. It has the option to show the quarterly statement dates or the annual dates and can be shown for any amount of companies.

image

The option to segregate revenue by product. This makes it possible to understand where the revenue is coming from. Note that this is a Professional and Enterprise Subscription feature. As an example, Apple.

image

The option to segregate revenue by geography. This makes it possible to understand from what countries, a company makes its revenue. Note that this is a Professional and Enterprise Subscription feature. As an example, Google.

image

As you can see, both options can be either quarterly or annually.

v1.2.4

17 August 2023

Many many new additions!

  • Introduced a TQDM progress bar for financial statements. This only activates if you have TQDM installed and can also be disabled by setting progress_bar=False in the Toolkit initalization. The purpose of this is to make it more clear how far the data collection is progressing. This fixes #53.
  • Added a sleeper in case you breach the request limit. This is mostly relevant for Premium subscriptions that reach the 300 (or 750) API Calls per minute. On average, this should be almost never an issue. This fixes #52.
  • I've done some number formatting. Ratios or percentages are depicted with 4 decimals and all other values with 2. This made more sense and keeps the data concise.
  • Many QOL updates and Docstring fixes.

I've extended the historical dataset with dividends, returns and cumulative returns. As an example:

image

I've added in the ability to collect Analyst Estimates. This gives insights in how a range of analysts thought about the past and think about the future of each company.

image

The Enterprise functionality is now located in models and is calculated with the available data. This makes it more in line with the rest of the Toolkit. This also shows the new progress bars.

image

v1.2.2

13 August 2023

This release introduces growth metrics. This allows any financial statement, ratio or model to also be viewed as growth metrics. Next to that, with the lag parameter multiple periods can be defined. This is now also updated in the Example files. Lastly, the historical data output now also calculates returns.

For example:

from financetoolkit import Toolkit

API_KEY = "FMP_KEY"

companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2000-01-01"
)

companies.get_income_statement(growth=True)

Which returns:

image

And an example for ratios with multiple lags:

from financetoolkit import Toolkit

API_KEY = "FMP_KEY"

companies = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN"], api_key=API_KEY, start_date="2000-01-01"
)

companies.ratios.collect_all_ratios(growth=True, lag=[1, 2, 3])

Which returns:

image

v1.2.1

11 August 2023

I've updated much of the docstrings to now include examples. These examples and the code documentation in general is now depicted on: https://www.jeroenbouma.com/projects/financetoolkit

Furthermore, I've introduced dividends within the Historical data. This allow you to see annual and quarterly dividend values for each.

It’s good to note the following: the most recent annual and quarterly numbers might differ from what other websites report because this is based on the dividend that actually has been paid and not what is announced.

These are the annual values:
image

And these are the quarterly values:
image

v1.2.0

1 August 2023

This new release has numerous of improvements:

  • Worked on fixing the date formatting, you will now see the correct dates for Quarters (2020Q2, 2020Q3 etc). This fixed an issue where the reporting dates of companies varied. For some the end of June could be Q3 while for others Q1. Now both will be Q2 so comparison makes more sense. See #45
  • Introduced a Statistics statement that includes CIK Codes, reporting dates and financial statement links.
  • It is now possible to calculate custom ratios based on the normalized financial statements. This makes it much easier to calculate ratios that are currently not included. See #47 by @sword134
  • Overall improvements of the code, a big step forward in optimization and error handling. It won't happen that the functions crash but instead will show an error message and continue.
  • Fix issues with values being 0 (divide by zero).

See below output of both the new date naming for quarters as well as the newly defined ratios.

2022Q3 2022Q4 2023Q1 2023Q2
Current Assets Inventory 1.62953e+11 1.62125e+11 1.5967e+11 1.66557e+11
Net Income / Total Assets 0.0388271 0.037299 0.0407344 0.0479527
Quick Ratio Current 2.46977 2.33947 2.31896 2.14334
Quick Ratio Total 1.55744 1.48575 1.4703 1.43704
WC / Net Income 7.19842 7.00932 6.1877 4.95857

v1.1.2

24 July 2023

Added in functionality to set a start and end date. For example:

from financetoolkit import Toolkit

companies = Toolkit(['AAPL', 'MSFT'], api_key="FMP_KEY", start_date='2017-12-31')

# an Enterprise example
enterprise = companies.get_enterprise()

# a Historical example
historical_data = companies.get_historical_data()

# a Financial Statement example
balance_sheet_statement = companies.get_balance_sheet_statement()

# a Ratios example
profitability_ratios = companies.ratios.collect_profitability_ratios()

# Show the profitability ratios for Apple
profitability_ratios.loc['AAPL']

This returns the following output for profitability_ratios.loc['AAPL]. Omitting .loc['AAPL'] will return the result for both AAPL and MSFT.

2018 2019 2020 2021 2022
Gross Margin 0.383437 0.378178 0.382332 0.417794 0.433096
Operating Margin 0.26694 0.24572 0.241473 0.297824 0.302887
Net Profit Margin 0.224142 0.212381 0.209136 0.258818 0.253096
Interest Burden Ratio 1.02828 1.02827 1.01211 1.00237 0.997204
Income Before Tax Profit Margin 0.274489 0.252666 0.244398 0.298529 0.30204
Effective Tax Rate 0.183422 0.159438 0.144282 0.133023 0.162045
Return on Assets (ROA) 0.162775 0.16323 0.177256 0.269742 0.282924
Return on Equity (ROE) 0.555601 0.610645 0.878664 1.50071 1.96959
Return on Invested Capital (ROIC) 0.269858 0.293721 0.344126 0.503852 0.562645
Return on Capital Employed (ROCE) 0.305968 0.297739 0.320207 0.495972 0.613937
Return on Tangible Assets 0.555601 0.610645 0.878664 1.50071 1.96959
Income Quality Ratio 1.30073 1.25581 1.4052 1.09884 1.22392
Net Income per EBT 0.816578 0.840562 0.855718 0.866977 0.837955
Free Cash Flow to Operating Cash Flow Ratio 0.828073 0.848756 0.909401 0.893452 0.912338
EBT to EBIT Ratio 0.957448 0.948408 0.958936 0.976353 0.975982
EBIT to Revenue 0.286688 0.26641 0.254864 0.305759 0.309473

v1.1.0

20 July 2023

This release features numerous enhancements and fixes:

  • Overall robustness fixes to ensure errors are easier to understand. This fixes #38.
  • Ensure that if a ticker has no data, that this is accurately displayed and taken out of the calculation. By default tickers are removed but there is a possibility to stop this behaviour. This fixes #42.
  • Zero Division Errors due to missing data, this was often an issue when data was available for one financial statement but not for the others resulting in zeros. This fixes #39.
  • Add the option to more easily combine DataFrames into the desired format for the Toolkit. Now, with from financetoolkit.base import helpers and then helpers.combine_dataframes it is possible to feed a dictionary with tickers as keys and dataframes as values to create the desired format. This fixes #41.

Full Changelog: https://github.com/JerBouma/FinanceToolkit/commits/v1.1.0