我用 Python(使用 yfinance)构建了一个“Peter Lynch”股票分析器
Source: Dev.to

彼得·林奇,这位传奇的 Fidelity Magellan 基金经理,提出了一套他称为 “2‑Minute Drill.” 的系统化股票分析方法。他的体系将股票划分为六类,并为每一类应用特定的指标。
虽然林奇当年是用铅笔和纸手工完成这些工作,但我们可以使用 Python 和 yfinance 库来实现全自动化。
在本文中,我将展示如何构建 “The Lynchpad”——一个 Python 脚本,能够自动获取实时市场数据,并对你的投资组合运行林奇的决策树。
什么是彼得·林奇的决策树?
林奇的方法将股票分为六类:
| 类别 | 描述 | 关键指标 |
|---|---|---|
| 快速增长股 | 高增长公司(年增长率 20 %+) | PEG 比率,P/E |
| 慢速增长股 | 成熟公司,派发稳定股息 | 股息率 |
| 稳健股 | 大型、稳定的公司 | 合理的 P/E 比率 |
| 周期股 | 与经济周期相关的公司 | 库存与销售增长 |
| 转机股 | 正在恢复的困境公司 | 债务水平 |
| 资产类股 | 资产被低估的公司 | 账面价值 |
林奇最重要的自动检查是 “库存警告”——如果库存增长速度快于销售,这表明需求在放缓,是一个红色警示。
用例:“Lynchpad”
此脚本演示了使 Python 成为投资分析理想工具的三大关键能力:
- 外部库 – 导入
yfinance自动获取实时股票数据。 - 逻辑与自动化 – 自动应用 Lynch 复杂的“库存 vs. 销售”逻辑。
- 人机交互 – 你在字典中定义股票代码和“故事”,代码负责完成计算。

Lynchpad 实时分析 FIG、DUOL、Z 和 KO 的表现
完整代码
将此代码复制到您的 Python 环境中。它会从 Yahoo Finance 获取实时数据,并自动应用林奇的决策树逻辑:
# ==========================================
# 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}%")
超越彼得·林奇
虽然此示例遵循林奇的方法论,但实时 Python 环境适用于任何策略:
- 价值投资 – 实现 DCF 模型以计算内在价值。
- 动量交易 – 计算移动平均线、价格趋势。
- 股息投资 – 分析派息率和股息增长。
- 技术分析 – 计算 RSI、MACD、布林带等。
本文使用 CoilPad 编写,这是一个原生 macOS Python Playground。如果你喜欢这种自动化的股票分析方法,快来试试吧!
