DEV Community

Cover image for I built a 'Peter Lynch' Stock Analyzer in Python (using yfinance)
Nick Chen
Nick Chen

Posted on • Originally published at coilpad.com

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

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 this 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:

  • Fast Growers: High-growth companies (20%+ annual growth). Watch PEG ratio and P/E.
  • Slow Growers: Mature companies with steady dividends. Focus on dividend yield.
  • Stalwarts: Large, stable companies. Look for reasonable P/E ratios.
  • Cyclicals: Companies tied to economic cycles. Watch inventory vs. sales growth.
  • Turnarounds: Distressed companies recovering. Check debt levels.
  • Asset Plays: Companies with undervalued assets. Analyze book 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:

  • External Libraries: Import yfinance to fetch live stock data automatically.
  • Logic & Automation: Apply Lynch's complex "inventory vs. sales" logic automatically.
  • Human-in-the-Loop: You define the tickers and the "Story" in a dictionary, and 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 automated logic:

# ==========================================
#  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)
# This shows how code mixes manual notes with automated data.
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 (The 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:
        inventory_warning = "N/A (No Inventory Data)"

    # 3. Category Specific Logic
    verdict = "Hold/Neutral"
    notes = []

    if category == "Fast Grower":
        if peg < 1.0: notes.append("✅ PEG is attractive (<1.0)")
        elif 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 < 3.0: notes.append("❌ Yield is low for this category")
        else: notes.append("✅ Good Yield")

    elif category == "Turnaround":
        debt_equity = info.get('debtToEquity', 0)
        if debt_equity > 100: notes.append("⚠️ High Debt Load")
        else: notes.append("✅ Debt manageable")

    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 ---
print(f"{'TICKER':<8} {'PRICE':<8} {'CAT':<12} {'WARNINGS & NOTES'}")
print("-" * 80)

for ticker, data in portfolio.items():
    res = analyze_lynch_metrics(ticker, data['category'])
    print(f"{res['Ticker']:<8} {res['Price']:<8} {res['Category'][:10]:<12} {res['Inv Warning']} {res['Auto-Notes']}")
Enter fullscreen mode Exit fullscreen mode

Why This Approach Shines

1. "Live" Scratchpad

Unlike a static Excel sheet, this script pulls fresh data every time you run it. You can wake up, hit "Run", and see if metrics have changed overnight.

2. Context + Code = Investment Journal

You aren't just running a script; you are maintaining the portfolio dictionary at the top. This effectively turns the code block into your Investment Journal. You can write comments right next to the ticker logic:

"FIG": {
    "category": "Fast Grower",
    "story": "Holding until $100. Watch out for Adobe competition."
}  # <-- Your personal notes live in the code
Enter fullscreen mode Exit fullscreen mode

3. Complex Logic Hidden

The analyze_lynch_metrics function contains all the ugly API parsing and calculation logic, keeping your main execution loop clean and focused on the results.

Customizing for Your Portfolio

The beauty of the Lynchpad is its flexibility. You can easily customize it for your own investment strategy:

Add Custom Metrics

Want to track free cash flow or profit margins? The yfinance library provides access to hundreds of financial metrics:

# Add to the analyze_lynch_metrics function:
fcf = info.get('freeCashflow', 0)
profit_margin = info.get('profitMargins', 0) * 100

if profit_margin > 20:
    notes.append(f"✅ Strong margins: {profit_margin:.1f}%")
Enter fullscreen mode Exit fullscreen mode

Beyond Peter Lynch

While this example focuses on Lynch's methodology, a live Python environment is perfect for implementing any investment strategy:

  • Value Investing: Calculate intrinsic value using DCF models
  • Momentum Trading: Track price trends and moving averages
  • Dividend Investing: Analyze payout ratios and dividend growth
  • Technical Analysis: Calculate RSI, MACD, and other indicators

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

Top comments (0)