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

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

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 네이티브 파이썬 플레이그라운드입니다. 자동화된 주식 분석 접근 방식이 마음에 드셨다면 한 번 시도해 보세요!
