I built a 'Peter Lynch' Stock Analyzer in Python (using yfinance)

Published: (January 3, 2026 at 09:07 AM EST)
4 min read
Source: Dev.to

Source: Dev.to

Cover image for I built a “Peter Lynch” Stock Analyzer in Python (using yfinance)

Nick Chen

Peter Lynch, the legendary Fidelity Magellan fund manager, developed a systematic approach to stock analysis that he called the “2‑Minute Drill.” His methodology categorizes stocks into six types and applies specific metrics to each category.

While Lynch did this manually with pencil and paper, we can automate the entire process using Python and the yfinance library.

In this post, I’ll show you how to build “The Lynchpad”—a Python script that automatically fetches live market data and runs Lynch’s decision tree against your portfolio.

What is Peter Lynch’s Decision Tree?

Lynch’s approach categorizes stocks into six types:

CategoryDescriptionKey Metric(s)
Fast GrowersHigh‑growth companies (20 %+ annual growth)PEG ratio, P/E
Slow GrowersMature companies with steady dividendsDividend yield
StalwartsLarge, stable companiesReasonable P/E ratios
CyclicalsCompanies tied to economic cyclesInventory vs. sales growth
TurnaroundsDistressed companies recoveringDebt levels
Asset PlaysCompanies with undervalued assetsBook value

Lynch’s most important automated check is the “Inventory Warning” – if inventory is growing faster than sales, it’s a red flag that demand is slowing.

The Use Case: “The Lynchpad”

This script demonstrates three key capabilities that make Python perfect for investment analysis:

  1. External Libraries – Import yfinance to fetch live stock data automatically.
  2. Logic & Automation – Apply Lynch’s complex “inventory vs. sales” logic automatically.
  3. Human‑in‑the‑Loop – You define the tickers and the “Story” in a dictionary; the code handles the math.

CoilPad running the Lynchpad stock analysis script

The Lynchpad in action – analyzing FIG, DUOL, Z, and KO with live data

The Complete Code

Copy this code into your Python environment. It fetches live data from Yahoo Finance and applies Lynch’s decision‑tree logic automatically:

# ==========================================
#  THE LYNCHPAD: AUTOMATED STOCK CHECKLIST
# ==========================================
# 1. Install dependency if needed: pip install yfinance
import yfinance as yf
import pandas as pd

# --- USER INPUT SECTION ---
# Define your portfolio and the "Story" (Lynch's 2‑minute drill)
portfolio = {
    "FIG": {"category": "Fast Grower", "story": "Monopoly on design, AI integration coming."},
    "DUOL": {"category": "Fast Grower", "story": "Strong user retention, expanding to Math/Music."},
    "Z": {"category": "Turnaround", "story": "Housing market recovery play."},
    "KO": {"category": "Slow Grower", "story": "Defensive dividend play."},
}

def analyze_lynch_metrics(ticker_symbol, category):
    """Fetches data and checks specific Lynch warnings based on category."""
    stock = yf.Ticker(ticker_symbol)
    info = stock.info

    # 1. Basic Data
    price = info.get("currentPrice", 0)
    pe = info.get("trailingPE", 0)
    peg = info.get("pegRatio", 0)
    div_yield = (info.get("dividendYield", 0) or 0) * 100

    # 2. The "Cyclical/Inventory" Check (most important Lynch automated check)
    # Warning if Inventory is growing faster than Sales
    inventory_warning = "✅ OK"
    try:
        bs = stock.quarterly_balance_sheet
        fin = stock.quarterly_financials

        # Growth calculations (Current vs Previous Quarter)
        inv_curr, inv_prev = bs.loc["Inventory"].iloc[0], bs.loc["Inventory"].iloc[1]
        sales_curr, sales_prev = fin.loc["Total Revenue"].iloc[0], fin.loc["Total Revenue"].iloc[1]

        inv_growth = (inv_curr - inv_prev) / inv_prev
        sales_growth = (sales_curr - sales_prev) / sales_prev

        if inv_growth > sales_growth:
            inventory_warning = (
                f"⚠️ WARNING: Inv up {inv_growth:.1%} > Sales up {sales_growth:.1%}"
            )
    except Exception:
        inventory_warning = "N/A (No Inventory Data)"

    # 3. Category‑Specific Logic
    notes = []

    if category == "Fast Grower":
        if peg > 2.0:
            notes.append("❌ PEG is high (>2.0)")
        if pe > 40:
            notes.append("⚠️ P/E is very high")

    elif category == "Slow Grower":
        if div_yield < 2:
            notes.append("⚠️ Low dividend yield")
        else:
            notes.append("✅ Healthy dividend")

    # Add more category logic here as needed …

    return {
        "Ticker": ticker_symbol,
        "Price": f"${price}",
        "Category": category,
        "P/E": f"{pe:.1f}" if pe else "-",
        "PEG": peg,
        "Inv Warning": inventory_warning,
        "Auto‑Notes": "; ".join(notes),
    }

# --- EXECUTION ---
# Example usage (prints a summary for each ticker)
for ticker, data in portfolio.items():
    result = analyze_lynch_metrics(ticker, data["category"])
    print(result)
# The following fragment was present in the original article but appears incomplete.
# It is retained here unchanged for reference.

print(f"{'TICKER': 30:
        warnings.append("⚠️ High P/E")
    if price > 150:
        warnings.append("⚠️ Expensive")

    # Auto‑generated notes
    notes = []
    if eps and eps > 5:
        notes.append(f"✅ Strong EPS: {eps:.2f}")
    if pe and pe  20:
    notes.append(f"✅ Strong margins: {profit_margin:.1f}%")

Beyond Peter Lynch

While this example follows Lynch’s methodology, a live Python environment works for any strategy:

  • Value Investing – implement DCF models for intrinsic value.
  • Momentum Trading – compute moving averages, price trends.
  • Dividend Investing – analyze payout ratios and dividend growth.
  • Technical Analysis – calculate RSI, MACD, Bollinger Bands, etc.

This post was written using CoilPad, a native macOS Python playground. If you enjoyed this automated approach to stock analysis, give it a try!

Back to Blog

Related posts

Read more »

Jupyter NoteBook

!Cover image for Jupyter NoteBookhttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.am...