Python(yfinance 사용)으로 'Peter Lynch' 주식 분석기를 만들었습니다

발행: (2026년 1월 3일 오후 11:07 GMT+9)
5 min read
원문: 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.

피터 린치의 의사결정 트리는 무엇인가?

Lynch의 접근법은 주식을 여섯 가지 유형으로 구분합니다:

카테고리설명핵심 지표(s)
Fast Growers연간 20 % 이상 성장하는 고성장 기업PEG ratio, P/E
Slow Growers안정적인 배당을 제공하는 성숙 기업Dividend yield
Stalwarts규모가 크고 안정적인 기업Reasonable P/E ratios
Cyclicals경기 순환에 연동된 기업Inventory vs. sales growth
Turnarounds부실에서 회복 중인 기업Debt levels
Asset Plays저평가된 자산을 보유한 기업Book value

Lynch가 가장 중요하게 여기는 자동 체크는 “Inventory Warning” – 재고가 매출보다 빠르게 증가하면 수요가 둔화되고 있다는 위험 신호입니다.

사용 사례: “The Lynchpad”

  1. 외부 라이브러리yfinance를 가져와 실시간 주식 데이터를 자동으로 가져옵니다.
  2. 논리 및 자동화 – Lynch의 복잡한 “재고 대비 매출” 로직을 자동으로 적용합니다.
  3. Human‑in‑the‑Loop – 티커와 “스토리”를 딕셔너리로 정의하면, 코드는 수학적 계산을 처리합니다.

CoilPad가 Lynchpad 주식 분석 스크립트를 실행하는 모습

Lynchpad 작동 중 – FIG, DUOL, Z, KO를 실시간 데이터로 분석

전체 코드

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}%")

피터 린치를 넘어서

  • 가치 투자 – 내재 가치를 위한 DCF 모델을 구현합니다.
  • 모멘텀 트레이딩 – 이동 평균 및 가격 추세를 계산합니다.
  • 배당 투자 – 배당 지급 비율 및 배당 성장률을 분석합니다.
  • 기술적 분석 – RSI, MACD, 볼린저 밴드 등을 계산합니다.

이 게시물은 CoilPad를 사용해 작성되었습니다, macOS 네이티브 파이썬 플레이그라운드입니다. 자동화된 주식 분석 접근 방식이 마음에 드셨다면 한 번 시도해 보세요!

Back to Blog

관련 글

더 보기 »

데이터 사이언스 스킬 향상 38일 차

데이터 시각화 새해 복 많이 받으세요 🥂 데이터 시각화에서 나는 단순히 “차트를 그리는” 것이 아니었습니다. 데이터 가져오기 나는 관계형 데이터베이스에 발을 들였습니다: > Insert relationa...

주피터 노트북

!Jupyter Notebook의 표지 이미지https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.am...

문제 8: 모음 세기

여러분, 안녕하세요! 👋 오늘은 문자열 조작 문제인 모음 개수 세기를 다룹니다. 목표는 주어진 문자열에서 모음의 개수를 세는 함수를 작성하는 것입니다.