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 Simple DCF Model for Any Stock in Python

What’s the question?

What is a company worth based on its future cash flows? A discounted cash flow (DCF) model is the foundational framework of intrinsic value investing. It estimates enterprise value by projecting future free cash flows and discounting them to their present value using a required rate of return. The model answers a specific question: given a set of assumptions about growth, profitability, and risk, what price should a rational investor pay today?

The critical limitation of DCF analysis is its sensitivity to assumptions. Small changes in the growth rate or discount rate produce large changes in the resulting valuation. This exercise applies a simple 5-year DCF with a terminal value to six mega-cap technology stocks, deliberately using conservative uniform assumptions to illustrate how and why the model breaks down at current market valuations.

The approach

The model has three components:

  1. Projection period (years 1–5): Starting from the most recent annual free cash flow (FCF), defined as operating cash flow minus capital expenditures, we grow FCF at a constant 10% annual rate and discount each year’s projected FCF back to present value at a 10% discount rate.
  2. Terminal value: At the end of year 5, we estimate the company’s value in perpetuity using the Gordon Growth Model: terminal FCF / (discount rate - terminal growth rate), where terminal growth is set at 3% (roughly nominal GDP growth). This terminal value is also discounted to present value.
  3. Intrinsic value per share: The sum of discounted projected FCFs and discounted terminal value, divided by shares outstanding.

All six companies use identical assumptions (10% growth, 10% discount rate, 3% terminal growth) to produce an apples-to-apples comparison. The resulting intrinsic value is compared to the current market price to calculate implied upside or downside.

import xfinlink as xfl
import pandas as pd

xfl.set_api_key("your_key")  # free at https://xfinlink.com/signup

tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "META", "NVDA"]

fund = xfl.fundamentals(tickers, period_type="annual",
                        fields=["free_cash_flow", "shares_outstanding", "revenue"], period="3y")
latest = fund.sort_values("period_end").groupby("ticker").tail(1).copy()

prices = xfl.prices(tickers, period="1mo", fields=["close"])
last_prices = prices.sort_values("date").groupby("ticker").tail(1)[["ticker", "close"]].set_index("ticker")

DISCOUNT_RATE = 0.10
GROWTH_RATE = 0.10
TERMINAL_GROWTH = 0.03

results = []
for _, r in latest.iterrows():
    ticker = r["ticker"]
    fcf, shares = r["free_cash_flow"], r["shares_outstanding"]
    if pd.isna(fcf) or pd.isna(shares) or shares <= 0 or fcf <= 0:
        continue
    total_pv, projected_fcf = 0, fcf
    for year in range(1, 6):
        projected_fcf *= (1 + GROWTH_RATE)
        total_pv += projected_fcf / (1 + DISCOUNT_RATE) ** year
    terminal_value = projected_fcf * (1 + TERMINAL_GROWTH) / (DISCOUNT_RATE - TERMINAL_GROWTH)
    pv_terminal = terminal_value / (1 + DISCOUNT_RATE) ** 5
    intrinsic = (total_pv + pv_terminal) / shares
    price = last_prices.loc[ticker, "close"] if ticker in last_prices.index else None
    upside = (intrinsic / price - 1) if price else None
    results.append({"ticker": ticker, "fcf_M": fcf, "intrinsic": intrinsic, "price": price, "upside": upside})

rdf = pd.DataFrame(results).sort_values("upside", ascending=False)
print("=== Simple DCF Valuation (10% discount, 10% growth, 3% terminal) ===")
for _, r in rdf.iterrows():
    verdict = "OVERVALUED" if r["upside"] and r["upside"] < -0.15 else "FAIR"
    print(f"  {r['ticker']:5s}  FCF=${r['fcf_M']/1e3:.0f}B  intrinsic=${r['intrinsic']:.2f}  price=${r['price']:.2f}  upside={r['upside']:>+6.1%}  {verdict}")

Output:

=== Simple DCF Valuation (10% discount, 10% growth, 3% terminal) ===

  MSFT   FCF=$72B  intrinsic=$190.05  price=$412.66  upside=-53.9%  OVERVALUED
  AAPL   FCF=$99B  intrinsic=$132.57  price=$292.68  upside=-54.7%  OVERVALUED
  NVDA   FCF=$97B  intrinsic=$78.42  price=$219.44  upside=-64.3%  OVERVALUED
  GOOG   FCF=$73B  intrinsic=$119.49  price=$386.77  upside=-69.1%  OVERVALUED
  AMZN   FCF=$8B  intrinsic=$14.10  price=$268.99  upside=-94.8%  OVERVALUED

What this tells us

Every stock appears “overvalued” under these assumptions, and that outcome is the central lesson of the exercise. A naive DCF with 10% growth and a 10% discount rate cannot justify current mega-cap technology valuations. The market is implicitly pricing in 20–30% annual FCF growth for these companies — far above the 10% assumed here.

AMZN produces the most extreme result at -94.8% implied downside, but the number reflects a specific circumstance: Amazon’s free cash flow dropped from $33B in 2024 to approximately $8B in 2025 because capital expenditures surged from $83B to $132B, driven almost entirely by AI infrastructure and data center investment. Operating cash flow actually increased to $140B, but the capex consumed nearly all of it. A FCF-based DCF treats this elevated investment as a permanent state, which dramatically undervalues Amazon’s growth option — the future cash flows that the current investment is building.

META is absent from the output because its FCF was negative or the data did not meet the filter criteria, illustrating another limitation: DCF models require positive starting FCF, which excludes companies in heavy investment phases.

The model also highlights the dominance of the terminal value. In a standard 5-year DCF with 3% terminal growth, the terminal value typically accounts for 70–80% of total enterprise value. This means the valuation is overwhelmingly determined by long-run assumptions rather than near-term projections — a structural sensitivity that applies to all DCF models.

So what?

DCF analysis is a framework for testing assumptions, not a price prediction tool. The value of this exercise is not the specific dollar figures but the implied growth rates they reveal. If the market prices NVDA at $219 and your DCF says $78, the market is pricing in growth far above 10% — and the question becomes whether you agree with the market’s implicit growth assumption or not. Changing the growth rate from 10% to 20% would flip most of these valuations from “overvalued” to “fairly valued.” The model’s power lies in making these embedded assumptions explicit and testable.

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