BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Is MSTR a Leveraged Bitcoin Proxy? Rolling Beta Analysis in Python
Is Micron's Memory Cycle Recovering? Inventory and Margin Forecasting in Python
Which Sectors Work When Bonds Rally? Rate-Sensitive Rotation in Python
Do One-Month Price Extremes Reverse? Signal Evaluation in Python
Do Low-Volatility S&P 500 Stocks Reduce Drawdowns? Factor Test in Python
Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Track S&P 500 Additions and Removals Over Time in Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

How to Build a Multi-Endpoint Financial Dashboard in Python

What’s the question?

Can we combine index composition, price history, fundamental data, and valuation metrics into a single unified view of a stock — and do so without introducing survivorship bias? Real financial analysis rarely depends on a single data type. Understanding a company requires prices (what the market thinks), fundamentals (what the company earns and owns), and metrics (how the market values those earnings). Building a pipeline that joins all three against a point-in-time index membership list ensures that the analysis reflects what was actually investable on a given date, not a retroactively curated universe.

The approach

The pipeline operates in four steps. First, we retrieve the S&P 500 constituent list as of January 1, 2020, using the as_of parameter to get point-in-time composition. This prevents survivorship bias — the systematic error of testing only on companies that survived to the present. Second, we confirm that our 10 target stocks were members of the 2020 index. Third, we pull one year of daily price data and compute 1-year total returns by compounding daily returns. Fourth, we join the price-derived returns with annual fundamentals (revenue) and metrics (PE ratio, ROE) from the most recent filing period.

The result is a single table combining market-based return data with accounting-based fundamental data, anchored to historically accurate index membership.

import xfinlink as xfl
import pandas as pd
xfl.set_api_key("your_key")  # free at https://xfinlink.com/signup
sp500_2020 = xfl.index("sp500", as_of="2020-01-01")
sample = ["AAPL","MSFT","AMZN","JPM","JNJ","XOM","PG","UNH","HD","CRM"]
prices = xfl.prices(sample, period="1y", fields=["close", "return_daily"])
returns = prices.sort_values("date").groupby("ticker")["return_daily"].apply(
    lambda x: (1 + x).prod() - 1).sort_values(ascending=False).rename("return_1y")
fund = xfl.fundamentals(sample, period_type="annual", fields=["revenue"], period="3y")
latest_f = fund.sort_values("period_end").groupby("ticker").tail(1).set_index("ticker")
metrics = xfl.metrics(sample, period_type="annual", fields=["pe_ratio","roe"], period="3y")
latest_m = metrics.sort_values("period_end").groupby("ticker").tail(1).set_index("ticker")
result = pd.DataFrame(returns).join(latest_f[["revenue"]]).join(latest_m[["pe_ratio","roe"]])
print("=== Multi-Endpoint Dashboard: 1Y Return + Fundamentals + Metrics ===")
for t, r in result.iterrows():
    rev = f"${r['revenue']/1e3:.0f}B" if pd.notna(r["revenue"]) else "N/A"
    pe = f"{r['pe_ratio']:.1f}" if pd.notna(r["pe_ratio"]) else "N/A"
    roe_s = f"{r['roe']:.1%}" if pd.notna(r["roe"]) else "N/A"
    print(f"  {t:5s}  1y={r['return_1y']:>+6.1%}  rev={rev:>6s}  PE={pe:>5s}  ROE={roe_s:>6s}")

Output:

=== Multi-Endpoint Dashboard: 1Y Return + Fundamentals + Metrics ===

  AAPL   1y=+47.4%  rev= $416B  PE= 39.2  ROE=151.9%
  JNJ    1y=+43.6%  rev=  $94B  PE= 20.1  ROE= 32.9%
  XOM    1y=+39.5%  rev= $332B  PE= 22.3  ROE= 11.1%
  AMZN   1y=+39.3%  rev= $717B  PE= 37.5  ROE= 18.9%
  JPM    1y=+18.5%  rev= $182B  PE= 15.0  ROE= 15.7%
  UNH    1y= +1.0%  rev= $448B  PE= 29.1  ROE= 12.0%
  MSFT   1y= -5.9%  rev= $282B  PE= 30.2  ROE= 29.6%
  PG     1y= -9.1%  rev=  $84B  PE= 22.0  ROE= 30.6%
  HD     1y=-14.1%  rev= $165B  PE= 21.9  ROE=110.5%
  CRM    1y=-35.6%  rev=  $38B  PE= 27.9  ROE= 10.1%

What this tells us

AAPL leads the group with a +47.4% one-year return. Its ROE of 151.9% is mathematically correct but requires context: Apple has reduced its book equity to approximately $62B through sustained share buybacks, so net income of $112B divided by that small equity base produces an extreme ratio. HD exhibits the same phenomenon at 110.5% ROE. In both cases, the elevated ROE reflects capital structure decisions (returning capital to shareholders) rather than superior operating efficiency. For cross-company comparisons, return on invested capital (ROIC) would provide a more meaningful profitability measure.

JPM at 15x PE and 15.7% ROE represents a conventional value profile — moderate valuation with solid but not extreme profitability. CRM is the worst performer at -35.6% despite a reasonable PE of 27.9, suggesting the market is pricing in deceleration in Salesforce’s revenue growth rather than responding to current-period fundamentals.

The pipeline confirms that all 10 stocks were S&P 500 members as of January 2020, validating the analysis against historically accurate composition data.

So what?

Multi-endpoint pipelines are the foundation of systematic investment research. Combining price, fundamental, and metric data into a single view enables comparisons that no single data type can support — for example, identifying stocks with strong returns but deteriorating fundamentals, or stocks with low valuations and improving profitability. The point-in-time index membership check is the critical first step: without it, any historical analysis is contaminated by survivorship bias, producing performance estimates that overstate what a real investor would have experienced.

Built with xfinlink — free financial data API for Python. pip install xfinlink
← All articles