Finance Toolkit

by jerbouma

413 downloads
Not rated
GitHub

About

The Finance Toolkit gives AI assistants access to 200+ financial metrics, all calculated transparently from raw financial statements, not pulled from third-party endpoints.

Details

Author
jerbouma
Downloads
413
Categories
Finance, Developer Tools

- 200+ financial metrics calculated from raw statements.
- Core data: income, balance sheet, cash flow statements.
- 80+ profitability, solvency, liquidity, valuation ratios.
- 30+ momentum, volatility, breadth technical indicators.
- 20+ performance, factor models, VaR, GARCH metrics.
- 50+ macro indicators, government data, fixed income.

Authenticate once with your Financial Modeling Prep (FMP) API key via OAuth; no key is stored on the server. The server automatically falls back to Yahoo Finance when FMP data acquisition is unsuccessful.

While browsing a variety of websites, I repeatedly observed significant fluctuations in the same financial metric among different sources. Similarly, the reported financial statements often didn't line up, and there was limited information on the methodology used to calculate each metric.

For example, Microsoft's Price-to-Earnings (PE) ratio on the 6th of May, 2023 is reported to be 28.93 (Stockopedia), 32.05 (Morningstar), 32.66 (Macrotrends), 33.09 (Finance Charts), 33.66 (Y Charts), 33.67 (Wall Street Journal), 33.80 (Yahoo Finance) and 34.4 (Companies Market Cap). All of these calculations are correct, however the method of calculation varies leading to different results. Therefore, collecting data from multiple sources can lead to wrong interpretation of the results given that one source could apply a different definition than another. And that is, if that definition is even available as often the underlying methods are hidden behind a paid subscription.

This is why I designed the FinanceToolkit, this is an open-source toolkit in which all relevant financial methods (500+) are written down in the most simplistic way allowing for complete transparency of the method of calculation (proof). This enables you to avoid dependence on metrics from other providers that do not provide their methods. With a large selection of financial statements in hand, it facilitates streamlined calculations, promoting the adoption of a consistent and universally understood methods and formulas.

Beyond Equities, it supports Options, Currencies, Cryptocurrencies, ETFs, Mutual Funds, Indices, Money Markets, Commodities, Key Economic Indicators and more, allowing you to obtain historical data as well as important performance and risk measurements such as the Sharpe Ratio and Value at Risk.

Complementing this is theFinance Database 🌎, a database featuring 300.000+ symbols containing Equities, ETFs, Funds, Indices, Currencies, Cryptocurrencies and Money Markets. By utilising both, it is possible to do a fully-fledged competitive analysis with the tickers found from the FinanceDatabase inputted into the FinanceToolkit.

🔌 The Finance Toolkit is also available as anMCP Server

Query 500+ methods from Claude, Copilot, Cursor, Windsurf or any MCP-compatible client without writing code.

- Hosted:connect tohttps://financetoolkit.jeroenbouma.com/mcp— OAuth handles the rest on first use.
- Local:uvx --from "financetoolkit
[mcp]" financetoolkit-mcp-setup— sets up your client config and API key automatically. SeeMCP Server Documentationfor manual setup.

Also onSmithery,Glama,MCP Serversand more.
-
Installation
-
Functionality
-
MCP Server
-
Questions & Answers
-
Contributing
-
Mentions
-
Contact

Before installation, consider starring the project on GitHub which helps others find the project as well.

To install the Finance Toolkit it simply requires the following:

from financetoolkit import Toolkit companies = Toolkit( tickers=['AAPL', 'MSFT'], api_key="FINANCIAL_MODELING_PREP_KEY", # replace with your actual API key )

To be able to get started, you need to obtain an API Key from FinancialModelingPrep. This is used to gain access to 30+ years of financial statement both annually and quarterly. Note that the Free plan is limited to 250 requests each day, 5 years of data and only features companies listed on US exchanges.

By default, the Finance Toolkit prioritizes Financial Modeling Prep for data retrieval. If data acquisition from Financial Modeling Prep is unsuccessful (e.g., due to plan restrictions or API key issues), the toolkit automatically switches to Yahoo Finance as a secondary source.To disable this fallback behavior and exclusively use Financial Modeling Prep, setenforce_source="FinancialModelingPrep"during Toolkit initialization. This configuration ensures that an error is raised if Financial Modeling Prep data cannot be accessed. Alternatively, you can setenforce_source="YahooFinance"to exclusively use Yahoo Finance as the data source.

The sameenforce_sourceargument is also accepted per call onget_historical_data,get_treasury_dataand the four statement functions (get_balance_sheet_statement,get_income_statement,get_cash_flow_statementandget_statistics_statement), where it overrides whatever the Toolkit was initialised with.

This section is an introduction to the Finance Toolkit. Find with the link below fully-fledged code documentation as well as Jupyter Notebooks in which you can see many examples ranging from basic examples to creating custom ratios to working with your own datasets.

A basic example of how to use the Finance Toolkit is shown below. Every code snippet in the sections that follow builds on this samecompaniesinstance.

from financetoolkit import Toolkit # Initialize the Toolkit for Apple and Microsoft companies = Toolkit(["AAPL", "MSFT"], api_key=API_KEY, start_date="2017-12-31")

Each ratio, indicator and metric has a corresponding function that can be called directly, for exampleratios.get_return_on_equityortechnicals.get_relative_strength_index. Every module also has one or morecollect_functions that return a whole category at once, e.g.ratios.collect_profitability_ratios, useful when you want everything in one call instead of assembling it metric by metric.

Three capabilities cut across nearly the whole toolkit:

- rollingandtrailingwindows.Many metrics return one value per reporting period by default. Passrolling=<n>to compute the metric over a sliding window instead, ortrailing=<n>for a trailing sum/average (e.g. a trailing 4-quarter sum to annualize a quarterly flow) — turning a snapshot into a proper time series.
- growthandlag.Passgrowth=Trueon almost anyget_orcollect_function to return the period-over-period growth instead of the raw value.lag(anintor list ofints, default1) controls how many periods back that growth is measured against, e.g.lag=4for year-over-year growth on quarterly data. Combine withtrailing(e.g.trailing=4, growth=True) to get TTM growth.
- standardize(Z-Score).Mostget_*methods across Economics, Ratios, Technicals, Risk, Performance, Models, Options and Fixed Income acceptstandardize=True, converting raw values into standard deviations from their own historical mean/std. Useful for ranking, scoring, or spotting an unusual reading across metrics that otherwise live on incompatible scales.

Every module below also has aHow-To Guide notebookand fullcode documentation(formulas, parameters, worked examples) linked in its own section, see thedocumentation hubfor the complete index.

Before analyzing a ticker you often need to find it. The Discovery module is standalone and covers among other things lists of companies, cryptocurrencies, forex, commodities, ETFs and indices.

from financetoolkit import Discovery # Initialize the standalone Discovery module discovery = Discovery(api_key="FINANCIAL_MODELING_PREP_KEY") # Screen for stocks matching a set of criteria discovery.get_stock_screener( market_cap_higher=1000000, price_higher=100, price_lower=200, beta_higher=1, beta_lower=1.5, dividend_higher=1, )

Furthermore, you can find in this modulestock screeners,sector/industry performanceandnews feedsand more.Find the Notebookhereand the full instrument discovery documentationhere.

Obtainhistorical dataon a daily, weekly, monthly or yearly basis. This includes OHLC, volumes, dividends, returns and cumulative returns for each corresponding period.

# Obtain historical market data for all tickers historical_data = companies.get_historical_data() # Select the results for Apple historical_data.xs('AAPL', axis=1, level=1)

For example, a portion of the historical data for Apple is shown below.

And below the cumulative returns are plotted which include the S&P 500 as benchmark:

Metrics such asVolatility,Excess ReturnandExcess Volatilityare calculated as dedicatedRiskandPerformancemethods rather than columns on this table to create more efficient and flexible functionalities.Find the Notebookhereand the full historical data documentationhere.

Obtain anIncome Statementon an annual or quarterly basis. This can also be abalance statementorcash flow statement.

# Obtain the Income Statement for all tickers income_statement = companies.get_income_statement() # Select the results for Apple income_statement.loc['AAPL']

For example, the first 5 rows of the Income Statement for Apple are shown below.

And below the Earnings Before Interest, Taxes, Depreciation and Amortization (EBITDA) are plotted for both Apple and Microsoft.Find the Notebookhereand the full financial statement documentationhere.

GetProfitability Ratiosbased on the inputted balance sheet, income and cash flow statements. This can be any of the 80+ ratios within theratiosmodule.

# Collect all Profitability Ratios for all tickers profitability_ratios = companies.ratios.collect_profitability_ratios() # Select the results for Microsoft profitability_ratios.loc['MSFT']

For example, see some of the profitability ratios of Microsoft below.

And below a few of the profitability ratios are plotted for Microsoft.

The 80+ ratios are divided into five categories:Efficiency(asset/inventory/receivables turnover, cash conversion cycle, R&D/SG&A/SBC-to-revenue),Liquidity(current, quick and cash ratios, working capital),Profitability(margins, ROE/ROA/ROIC, cash vs. effective tax rate),Solvency(debt-to-equity, debt-to-capital, interest and dividend coverage) andValuation(P/E, PEG, Forward P/E, EV multiples, buyback and shareholder yield). It's also possible to define fullycustom ratioscalculated automatically from the balance sheet, income and cash flow statements.Find the Notebookhereand the full ratio-by-ratio documentationhere.

Get anExtended DuPont Analysisbased on the inputted balance sheet, income and cash flow statements.

# Get the Extended DuPont Analysis for all tickers extended_dupont_analysis = companies.models.get_extended_dupont_analysis() # Select the results for Apple extended_dupont_analysis.loc['AAPL']

For example, this shows the Extended DuPont Analysis for Apple:

And below each component of the Extended Dupont Analysis is plotted including the resulting Return on Equity (ROE).

Themodelsmodule covers 10+ models in total, for exampleDuPont Analysis,WACC,Economic Value Added (EVA),Altman Z-Score,Beneish M-Scoreand theGraham Number.Find the Notebookhereand the full model-by-model documentationhere.

Get theBlack Scholes Modelfor both call and put options including the relevant Greeks, in this caseDelta,Gamma,ThetaandVega. This can be any of the First, Second or Third Order Greeks.

# Get Delta for all tickers across strikes and expirations delta = companies.options.get_delta(expiration_time_range=180) # Select the results for Apple delta.loc['AAPL']

For example, see the delta of the Call options for Apple for multiple expiration times and strike prices below (Stock Price: 185.92, Volatility: 31.59%, Dividend Yield: 0.49% and Risk Free Rate: 3.95%):

Which can also be plotted together with Gamma, Theta and Vega as follows:

Theoptionsmodule is divided into four categories:Option Pricing(Black-Scholes, Binomial Model, Implied Volatility),First-Order Greeks(Delta, Vega, Theta, Rho),Second-Order Greeks(Gamma, Vanna, Charm, Vomma) andThird-Order Greeks(Speed, Zomma, Color, Ultima).Find the Notebookhereand the full option pricing and Greeks documentationhere.

Get the correlations with thefactors as defined by Fama-and-French. These include market, size, value, operating profitability and investment. The beauty of all functionality here is that it can be based on any period as the function accepts the periodintraday,weekly,monthly,quarterlyandyearly.

# Get the Fama-French factor correlations for all tickers, quarterly factor_asset_correlations = companies.performance.get_factor_asset_correlations(period="quarterly") # Select the results for Apple factor_asset_correlations['AAPL']

For example, this shows the quarterly correlations for Apple:

And below the correlations with each factor are plotted over time for both Apple and Microsoft.

Beyond Beta, CAPM and the Fama-French factors, theperformancemodule covers around 20+ metrics in total, for exampleSharpe Ratio,Sortino Ratio,Calmar Ratio,Omega Ratioand theCorrelation Matrix. Most of these also supportrolling=<n>for a value that evolves through time instead of one number per period.Find the Notebookhereand the full performance metric documentationhere.

Get theValue at Riskfor each week. Here, the days within each week are considered for the Value at Risk. This makes it so that you can understand within each period what is the expected Value at Risk (VaR) which can again be any period but also based on distributions such as Historical, Gaussian, Student-t, Cornish-Fisher, or a Peak-over-Threshold Extreme Value Theory (distribution="evt") fit for the tail.

# Get the weekly Value at Risk for all tickers companies.risk.get_value_at_risk(period="weekly")

And below the Value at Risk (VaR) for Apple, Microsoft and the benchmark (S&P 500) are plotted also demonstrating the impact of COVID-19.

Beyond VaR/CVaR/Entropic VaR, theriskmodule covers around 20+ metrics in total, for exampleConditional Drawdown at Risk,Maximum Drawdown Duration,EWMA Volatilityand theHurst Exponent. Most of these supportrolling=<n>for a value that evolves through time instead of one number per period.Find the Notebookhereand the full risk metric documentationhere.

Get theIchimoku Cloudparameters based on the historical market data. This can be any of the 40+ technical indicators within thetechnicalsmodule.

# Get the Ichimoku Cloud for all tickers ichimoku_cloud = companies.technicals.get_ichimoku_cloud() # Select the results for Apple ichimoku_cloud.xs('AAPL', axis=1, level=1)

For example, see some of the parameters for Apple below:

And below the Ichimoku Cloud parameters are plotted for Apple and Microsoft side-by-side.

The 40+ indicators are divided into four categories:Breadth(McClellan Oscillator, Advancers/Decliners, OBV, ADL, Chaikin Oscillator, TRIN, New Highs - New Lows),Momentum(RSI, MACD, Stochastic, Williams %R, Aroon, CCI, ADX and more),Overlap(SMA, EMA, DEMA, TRIX, WMA, Hull MA, VWAP, Parabolic SAR, Pivot Points, Support/Resistance) andVolatility(ATR, Keltner Channels, Bollinger Bands, Donchian Channels, Volatility Cone).Find the Notebookhereand the full technical indicator documentationhere.

Get access to theICE BofA Corporate Bondbenchmark indices and a variety of other bond and derivative related valuations within thefixedincomemodule.

# Get the ICE BofA Effective Yield for each Credit Rating companies.fixedincome.get_ice_bofa_effective_yield(maturity=False)

For example, see the Effective Yield for the ICE BofA Corporate Bond Index below for each Credit Rating:

And below a variety of Fixed Income metrics are shown all acquired from the Fixed Income module.

Beyond ICE BofA benchmarks, thefixedincomemodule coversBond Valuations(Present Value, Macaulay/Modified Duration, Convexity, Yield to Maturity),Derivative Valuations(Black and Bachelier models for Swaptions),Government Bonds(3-month and 10-year yields) andCentral Bank rates(Euribor,ECBandFederal Reserve ratesincl. SOFR). It can be called viacompanies.fixedincomeor standalone throughfrom financetoolkit import FixedIncome.Find the Notebookhereand the full fixed income documentationhere.

Get insights for 60+ countries into key economic indicators such as theConsumer Price Index (CPI),Gross Domestic Product (GDP),Unemployment Ratesand3-monthand10-yearGovernment Interest Rates. This is done through theeconomicsmodule and can be used as a standalone module as well by usingfrom financetoolkit import Economics.

# Get the Unemployment Rate for a selection of countries companies.economics.get_unemployment_rate()

For example see a selection of the countries below:

And below these Unemployment Rates are plotted over time:

The 40+ indicators are divided into five categories:Government(GDP, government debt/revenue/expenditure/deficit, trust in government),Economy(CPI, inflation, consumer/business confidence, house/rent/share prices),Finance(money supply, central bank policy rate, short/long-term interest rates),Environment(renewable energy, carbon footprint) andJobs & Society(unemployment, labour productivity, income inequality, population, poverty rate).Find the Notebookhereand the full economic indicator documentationhere.

Through a custom XLSX, XLS or CSV file you are able to load in your own portfolio directly into the Finance Toolkit. This allows you to view your positions and performance (over time) versus a benchmark and other positions as well as your PnL development over time. Furthermore, the portfolio can be directly loaded in the core functionality of the Finance Toolkit as well making it possible to calculate all metrics and ratios for your portfolio (which is a time-weighted sum of all positions). The portfolio module is a standalone module and can be used as such by usingfrom financetoolkit import Portfolio.Find the the full portfolio documentationhere.

from financetoolkit import Portfolio # Initialize the Portfolio module with your own dataset portfolio = Portfolio(example=True, api_key="FINANCIAL_MODELING_PREP_KEY") # Get an overview of all positions portfolio.get_positions_overview()

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

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

Theeconometricsmodule providesregression,hypothesis testing,unit root and cointegration,Granger causalityandpanel datamethods built onstatsmodelsandlinearmodels. It requires the optionalfinancetoolkit[econometrics]extra (pip install financetoolkit[econometrics]) and can be used viacompanies.econometrics.

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.