
Stock Analyzer
- 531 installs
- 27 repo stars
- Updated February 22, 2026
- feiyuggg/openclaw-stock-analyzer
stock-analyzer is an OpenClaw agent skill that helps developers add stock and market analysis steps into AI agent workflows.
About
stock-analyzer is an agent skill from feiyuggg/openclaw-stock-analyzer aimed at developers building OpenClaw-based automations that need securities analysis hooks. The catalog lists it under AI and agent building, and the skill name signals equity scanning or interpretation as part of a larger agent pipeline. With no bundled readme excerpt or manifest metadata in the source record, treat capabilities as integration-oriented scaffolding rather than a full standalone trading terminal. Reach for stock-analyzer when you already run OpenClaw agents and want a named skill slot for market-analysis prompts, tool routing, or downstream decision steps. Skip it when you need verified quote feeds, broker execution, or a documented API surface—the public record here does not enumerate datasets, indicators, or CLI commands.
- stock-analyzer
- AI & Agent Building
- AI-coding skill
Stock Analyzer by the numbers
- 531 all-time installs (skills.sh)
- Ranked #1,709 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 24, 2026 (Skillselion catalog sync)
npx skills add https://github.com/feiyuggg/openclaw-stock-analyzer --skill stock-analyzerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 531 |
|---|---|
| repo stars | ★ 27 |
| Last updated | February 22, 2026 |
| Repository | feiyuggg/openclaw-stock-analyzer ↗ |
How do you add stock analysis to OpenClaw agents?
Helps with ai & agent building tasks.
Who is it for?
Developers already using OpenClaw who want a dedicated stock-analysis skill hook in agent orchestration.
Skip if: Teams needing documented market data providers, broker APIs, or production trading execution guarantees from the skill record alone.
When should I use this skill?
User mentions OpenClaw stock analysis, equity agent workflows, or feiyuggg/openclaw-stock-analyzer integration.
What you get
OpenClaw agent runs with stock-analysis skill routing and market-oriented task handling.
Files
Stock Analyzer Skill
价值投资导向的股票分析工具,融合巴菲特和段永平的投资理念。
✅ 当前脚本已内置:巴菲特/段永平定性评估 + 五维价值投资框架,输出按统一模板自动生成。
核心理念
💡 买公司,不是买股票 —— 段永平
💡 和时间做朋友 —— 长期持有优质企业
💡 左侧交易 —— 在别人恐惧时贪婪
📚 分析方法论
详细的五维价值投资分析方法论请参见: [METHODOLOGY.md](./METHODOLOGY.md)
该方法论包含:
- 🧭 巴菲特 + 段永平「好公司」定性评估(业务/盈利模式/公司文化)
- 📊 市场环境与事件驱动分析
- 🗓️ 市场时钟(中期选举周期 / 节假日效应 / 月份季节性)
- 🛡️ 下跌阶段防御股观察池(按行业给出可投资标的)
- 📞 期权现金流规则:虚值 Long Call 分层布局,浮盈 50%-100% 分批减仓并回流正股
- 🏰 段永平五维护城河评分模型
- 💰 每股现金流 (FCF/OCF) 深度分析框架
- 📈 前瞻P/E与PEG多维度估值
- 🎯 三阶段DCF模型与敏感性分析
- 📝 标准化分析报告模板(含公司业务、盈利模式、公司文化)
两个分析工具
1. analyze-stock - 基础分析
# 快速分析
analyze-stock AAPL
analyze-stock AMZN
# 保存报告
analyze-stock TSLA --save
# 不同格式
analyze-stock NVDA --format json2. analyze-value - 价值投资分析 (推荐)
# 价值投资深度分析
analyze-value AMZN
analyze-value AAPL
analyze-value 1810.HK
# 保存详细报告
analyze-value TSLA --save
analyze-value META --format md3. analyze-earnings - 财报解读工作流(官方源优先)
# 生成任意公司的财报解读工作流报告(可复用)
analyze-earnings COIN
analyze-earnings AAPL --out /tmp/aapl-earnings.md
# 同时输出原始JSON,方便后续自动化处理
analyze-earnings MSFT --json
# 指定公司名(用于IR入口候选URL)
analyze-earnings BRK.B --company "Berkshire Hathaway"analyze-value 特色功能
0. 巴菲特 + 段永平好公司评估(新增)
- 公司业务: 用一句话说清公司卖什么、客户是谁、增长来自哪里
- 盈利模式: 收入结构、利润结构、现金流来源、Capex属性
- 公司文化: 管理层长期主义、资本配置纪律、组织执行文化
- 四问四看: 巴菲特四问 + 段永平四看,先判断“是不是好公司”
1. 前瞻市盈率 (Forward P/E) 详细分析
- 当前P/E: 具体数值 + 行业对比
- 历史P/E区间: TTM vs Forward
- 估值评价: 6级评分体系(显著低估→严重高估)
- 行业对比: 相对行业均值的百分比
2. 现金流详细分析
- FCF计算过程: OCF - CapEx = FCF
- 每股FCF: 具体数值 + P/FCF比率
- FCF收益率: 与国债收益率对比
- 现金流质量: 4级评价体系
3. 基本面五维分析
- ROE/ROA: 资本回报效率
- 毛利率/净利率: 盈利能力
- 资产负债率: 财务健康度
- 经营现金流/净利润: 现金流质量
4. 每股自由现金流 (FCF per share)
- 年度FCF: 总额 + 每股计算
- P/FCF估值: 与行业对比
- 历史趋势: 近3年变化
- 分红能力: FCF/净利润比率
5. PEG估值详细分析
- PEG计算: Forward P/E ÷ EPS增长率
- 多时间维度: 1年/2年PEG对比
- 基准对比: 以PEG=1.0为基准
- 投资价值评级: 5级评分体系
6. DCF估值详细分析
- 三阶段模型: 高成长(3年)→中成长(2年)→永续增长
- 参数透明: FCF基础值、增长率、WACC、永续增长率
- 敏感性分析: 9种情景组合
- 估值区间: 最低-最高-平均内在价值
7. 未来1-5年价值估算
• 1年后: $XXX (年化回报: +XX%) → 评价
• 3年后: $XXX (年化回报: +XX%) → 评价
• 5年后: $XXX (年化回报: +XX%) → 评价8. 左侧交易执行计划
目标仓位: 5-10%
• 第一批 (试仓20%): $价格区间 + 条件
• 第二批 (加仓30%): $价格区间 + 条件
• 重仓区 (35%): $价格区间 + 条件
• 极端区 (15%): <$价格 + 条件9. "时间是朋友"持有逻辑
自动生成巴菲特/段永平风格的投资理由:
- 护城河保护长期竞争力
- ROE显示资本回报能力
- 自由现金流创造价值
- 安全边际充足
- 长期持有复合增长
10. 短期期权与隐含波动率分析(新增)
- 最近到期期权的 Call/Put 成交量
- Put/Call 成交量比 与 持仓量比
- ATM 附近平均隐含波动率(IV)
- 用于辅助判断短期情绪与波动风险
11. 期权现金流策略(用户规则)
- 通过虚值 Long Call 做分层布局(默认 10% / 20% OTM 两档)
- 到期结构:至少 6 个月,优先 12 个月以上(可使用 LEAPS)
- 输出要求:给出具体合约价位(到期日 + 行权价),不只给区间
- 当 Long Call 浮盈达到 +50%:分批减仓(约30%-50%)锁定现金流
- 当 Long Call 浮盈达到 +100%:进一步减仓至底仓或全部止盈
- 止盈所得优先回流到正股左侧建仓区,形成“期权现金流 → 正股再投资”闭环
示例输出
$ analyze-value AMZN
🔍 正在进行价值投资分析: AMZN...
💡 理念: 买公司,不是买股票 | 和时间做朋友 | 左侧交易
============================================================================
📊 Amazon.com Inc (AMZN) 价值投资分析报告
============================================================================
【核心数据】
• 股价: $205.5 | 市值: $2206.0B
• 52周区间: $164.4 - $246.6
• Forward P/E: 22.1x
【巴菲特式估值】
• DCF内在价值: $280.5
• 安全边际: +36.5%
✅ 安全边际充足 (>20%),符合巴菲特标准
【护城河分析】(段永平五维)
• 网络效应: ⭐⭐⭐⭐⭐
• 品牌护城河: ⭐⭐⭐⭐
• 技术护城河: ⭐⭐⭐⭐
• 成本优势: ⭐⭐⭐⭐⭐
• 切换成本: ⭐⭐⭐⭐⭐
• 综合评级: 极宽护城河 (4.4/5.0)
【未来1-5年价值估算】
• 1年后: $224.5 (年化回报: +9.2%)
• 3年后: $290.3 (年化回报: +12.1%)
• 5年后: $368.8 (年化回报: +12.4%)
【五维评分】
1. 估值/安全边际: ⭐⭐⭐⭐⭐
2. 护城河: ⭐⭐⭐⭐⭐
3. 现金流: ⭐⭐⭐⭐
4. 盈利能力: ⭐⭐⭐⭐⭐
5. 增长潜力: ⭐⭐⭐⭐
综合评分: 4.4/5.0
【投资评级】
🎯 BUY ⭐⭐⭐⭐⭐
【左侧交易执行计划】
• 第一批 (试仓20%): $195-$215
• 第二批 (加仓30%): $175-$195
• 重仓区 (35%): $165-$175
• 极端区 (15%): <$165
【"时间是朋友"持有逻辑】
1. 极宽护城河保护企业长期竞争力
2. ROE 22.3% 显示优秀的资本回报能力
3. $32.2B 年自由现金流,为股东创造价值
4. 以低于内在价值 36% 的价格买入,安全边际充足
5. 持有3-5年,让企业价值复合增长五维评分体系
| 维度 | 权重 | 评估标准 |
|---|---|---|
| 估值/安全边际 | 20% | DCF内在价值 vs 当前价 |
| 护城河 | 20% | 五维护城河评分 |
| 现金流 | 20% | FCF健康度 |
| 盈利能力 | 20% | ROE、ROA、利润率 |
| 增长潜力 | 20% | EPS增长预期 |
投资评级标准
| 综合评分 | 安全边际 | 评级 | 操作建议 |
|---|---|---|---|
| ≥4.5 | >20% | STRONG BUY ⭐⭐⭐⭐⭐ | 重仓买入 |
| ≥4.0 | >10% | BUY ⭐⭐⭐⭐ | 分批建仓 |
| ≥3.5 | - | HOLD ⭐⭐⭐ | 持有观望 |
| <3.5 | - | AVOID ⭐⭐ | 回避 |
安装
# 确保依赖已安装
pip install yahooquery
# 添加到 PATH
export PATH="$HOME/.openclaw/workspace/skills/stock-analyzer:$PATH"数据来源
- Yahoo Finance (通过 yahooquery)
- SEC EDGAR submissions API(用于最新8-K/10-Q/10-K清单;如被限流会在报告中标注)
- 公司 Investor Relations 页面(通过工作流中的候选入口 + 浏览器人工核验)
- 实时股价、财务数据、分析师预测
免责声明
本工具基于价值投资理念提供分析参考,不构成投资建议。投资有风险,入市需谨慎。
请记住:
- 任何估值模型都有局限性
- DCF依赖于对未来增长的假设
- 请结合自身风险承受能力决策
- 长期持有需要对企业有深入理解
---
🕰️ "时间是优秀企业的朋友,是平庸企业的敌人。" — 沃伦·巴菲特
#!/usr/bin/env python3
"""
Earnings Workflow Analyzer
Usage: analyze-earnings <TICKER> [--company "Company Name"] [--out report.md]
"""
import argparse
import datetime as dt
import json
import re
from pathlib import Path
from typing import Dict, Any, List, Optional
import requests
def _safe_get(d: Dict[str, Any], *keys, default=None):
cur = d
for k in keys:
if not isinstance(cur, dict):
return default
cur = cur.get(k)
if cur is None:
return default
return cur
def fetch_yahoo_block(ticker: str) -> Dict[str, Any]:
try:
from yahooquery import Ticker
except ImportError as e:
raise RuntimeError("yahooquery is required: pip install yahooquery") from e
t = Ticker(ticker)
price = t.price.get(ticker, {})
profile = t.asset_profile.get(ticker, {})
stats = t.key_stats.get(ticker, {})
fin = t.financial_data.get(ticker, {})
cal = t.calendar_events.get(ticker, {})
trend = t.earnings_trend.get(ticker, {})
earnings_date = _safe_get(cal, "earnings", "earningsDate", default=[])
if isinstance(earnings_date, list):
earnings_date = earnings_date[0] if earnings_date else None
trend_items = trend.get("trend", []) if isinstance(trend, dict) else []
return {
"meta": {
"company_name": price.get("longName") or price.get("shortName")
},
"price": {
"current": price.get("regularMarketPrice"),
"previous_close": price.get("regularMarketPreviousClose"),
"day_high": price.get("regularMarketDayHigh"),
"day_low": price.get("regularMarketDayLow"),
"high_52w": price.get("fiftyTwoWeekHigh"),
"low_52w": price.get("fiftyTwoWeekLow"),
"market_cap": price.get("marketCap"),
"currency": price.get("currency") or "USD",
},
"valuation": {
"forward_pe": stats.get("forwardPE"),
"trailing_pe": stats.get("trailingPE"),
"price_to_book": stats.get("priceToBook"),
"peg": stats.get("pegRatio"),
"beta": stats.get("beta"),
},
"financial": {
"revenue_growth": fin.get("revenueGrowth"),
"gross_margin": fin.get("grossMargins"),
"operating_margin": fin.get("operatingMargins"),
"profit_margin": fin.get("profitMargins"),
"free_cashflow": fin.get("freeCashflow"),
"operating_cashflow": fin.get("operatingCashflow"),
"total_cash": fin.get("totalCash"),
"total_debt": fin.get("totalDebt"),
"roe": fin.get("returnOnEquity"),
},
"earnings": {
"earnings_date": earnings_date,
"trend": trend_items,
},
}
def fetch_sec_block(ticker: str) -> Dict[str, Any]:
headers = {"User-Agent": "openclaw-earnings-workflow/1.0 (contact: local-user)"}
try:
m = requests.get("https://www.sec.gov/files/company_tickers.json", headers=headers, timeout=30)
m.raise_for_status()
ticker_map = m.json()
except Exception as e:
return {"error": f"SEC ticker map fetch failed: {e}"}
cik = None
company = None
for _, row in ticker_map.items():
if str(row.get("ticker", "")).upper() == ticker.upper():
cik = int(row["cik_str"])
company = row.get("title")
break
if cik is None:
return {"error": f"Ticker {ticker} not found in SEC ticker map"}
cik_padded = str(cik).zfill(10)
sub_url = f"https://data.sec.gov/submissions/CIK{cik_padded}.json"
try:
s = requests.get(sub_url, headers=headers, timeout=30)
s.raise_for_status()
sub = s.json()
except Exception as e:
return {
"company": company,
"cik": cik,
"submissions_url": sub_url,
"error": f"SEC submissions fetch failed: {e}",
}
recent = sub.get("filings", {}).get("recent", {})
forms = recent.get("form", [])
acc = recent.get("accessionNumber", [])
filing_dates = recent.get("filingDate", [])
report_dates = recent.get("reportDate", [])
primary_docs = recent.get("primaryDocument", [])
descriptions = recent.get("primaryDocDescription", [])
wanted = {"8-K", "10-Q", "10-K", "6-K", "20-F"}
rows: List[Dict[str, Any]] = []
for i, f in enumerate(forms):
if f not in wanted:
continue
accession = acc[i]
accession_nodash = accession.replace("-", "")
primary = primary_docs[i]
filing_date = filing_dates[i]
report_date = report_dates[i] if i < len(report_dates) else None
desc = descriptions[i] if i < len(descriptions) else ""
filing_link = f"https://www.sec.gov/ixviewer/ix.html?doc=/Archives/edgar/data/{cik}/{accession_nodash}/{primary}"
archive_link = f"https://www.sec.gov/Archives/edgar/data/{cik}/{accession_nodash}/{primary}"
rows.append(
{
"form": f,
"filing_date": filing_date,
"report_date": report_date,
"description": desc,
"filing_link": filing_link,
"archive_link": archive_link,
}
)
rows.sort(key=lambda x: x.get("filing_date") or "", reverse=True)
return {
"company": company,
"cik": cik,
"submissions_url": sub_url,
"filings": rows[:15],
}
def _fmt_num(v: Optional[float], pct=False, bn=False) -> str:
if v is None:
return "N/A"
if pct:
return f"{v * 100:.1f}%"
if bn:
return f"${v / 1e9:.2f}B"
if isinstance(v, (int, float)):
return f"{v:.2f}" if abs(v) < 1000 else f"{v:,.0f}"
return str(v)
def _ir_candidates(ticker: str, company_name: Optional[str]) -> List[str]:
base = (company_name or ticker).lower()
base = re.sub(r"[^a-z0-9]+", "-", base).strip("-")
return [
f"https://investor.{base}.com",
f"https://ir.{base}.com",
f"https://www.{base}.com/investors",
f"https://www.{base}.com/investor-relations",
]
def build_report(ticker: str, company_name: Optional[str], yb: Dict[str, Any], sec: Dict[str, Any]) -> str:
now = dt.datetime.now().strftime("%Y-%m-%d %H:%M")
resolved_name = company_name or _safe_get(yb, "meta", "company_name") or sec.get("company") or ticker
lines = []
lines.append(f"# {resolved_name} ({ticker.upper()}) Earnings Analysis Workflow Report")
lines.append("")
lines.append(f"Generated: {now}")
lines.append("")
lines.append("## 1) Market Snapshot")
p = yb.get("price", {})
v = yb.get("valuation", {})
lines += [
f"- Price: {_fmt_num(p.get('current'))} {p.get('currency', 'USD')}",
f"- Previous Close: {_fmt_num(p.get('previous_close'))}",
f"- Day Range: {_fmt_num(p.get('day_low'))} - {_fmt_num(p.get('day_high'))}",
f"- 52W Range: {_fmt_num(p.get('low_52w'))} - {_fmt_num(p.get('high_52w'))}",
f"- Market Cap: {_fmt_num(p.get('market_cap'), bn=True)}",
f"- Forward P/E: {_fmt_num(v.get('forward_pe'))}",
f"- Trailing P/E: {_fmt_num(v.get('trailing_pe'))}",
f"- PEG: {_fmt_num(v.get('peg'))}",
f"- Beta: {_fmt_num(v.get('beta'))}",
]
lines.append("")
lines.append("## 2) Latest Earnings Timing & Street Expectations")
e = yb.get("earnings", {})
lines.append(f"- Latest/Next Earnings Date (Yahoo feed): {e.get('earnings_date') or 'N/A'}")
trend = e.get("trend", [])
for t in trend[:3]:
period = t.get("period")
ee = t.get("earningsEstimate", {})
re = t.get("revenueEstimate", {})
lines.append(
f"- {period}: EPS est avg {ee.get('avg', 'N/A')} | Revenue est avg {_fmt_num(re.get('avg'))}"
)
lines.append("")
lines.append("## 3) Official Filings (Primary Source)")
if sec.get("error"):
lines.append(f"- SEC lookup error: {sec['error']}")
else:
lines.append(f"- SEC Submissions API: {sec.get('submissions_url')}")
for r in sec.get("filings", [])[:10]:
lines.append(
f"- {r['filing_date']} | {r['form']} | {r.get('description') or 'N/A'} | report date: {r.get('report_date') or 'N/A'}"
)
lines.append(f" - ixviewer: {r['filing_link']}")
lines.append(f" - archive: {r['archive_link']}")
lines.append("")
lines.append("## 4) Investor Relations Source Discovery (Manual Verification)")
lines.append("Use browser to verify the latest shareholder letter / earnings release / webcast deck:")
for u in _ir_candidates(ticker, resolved_name):
lines.append(f"- {u}")
lines.append("")
lines.append("## 5) Financial Quality Quick Checks")
f = yb.get("financial", {})
lines += [
f"- Revenue Growth: {_fmt_num(f.get('revenue_growth'), pct=True)}",
f"- Gross Margin: {_fmt_num(f.get('gross_margin'), pct=True)}",
f"- Operating Margin: {_fmt_num(f.get('operating_margin'), pct=True)}",
f"- Profit Margin: {_fmt_num(f.get('profit_margin'), pct=True)}",
f"- ROE: {_fmt_num(f.get('roe'), pct=True)}",
f"- Operating Cash Flow: {_fmt_num(f.get('operating_cashflow'), bn=True)}",
f"- Free Cash Flow: {_fmt_num(f.get('free_cashflow'), bn=True)}",
f"- Total Cash: {_fmt_num(f.get('total_cash'), bn=True)}",
f"- Total Debt: {_fmt_num(f.get('total_debt'), bn=True)}",
]
lines.append("")
lines.append("## 6) Standardized Earnings Interpretation Checklist")
lines.append("- [ ] Revenue vs consensus (beat/miss, quality of growth)")
lines.append("- [ ] EPS vs consensus (GAAP / non-GAAP split)")
lines.append("- [ ] Gross / Operating margin trend and drivers")
lines.append("- [ ] FCF / OCF quality (one-off adjustments?)")
lines.append("- [ ] Guidance (next quarter + full year) and confidence")
lines.append("- [ ] Capital allocation (buyback, debt, M&A, dilution)")
lines.append("- [ ] Management commentary & risk flags")
lines.append("- [ ] Valuation reset after earnings (P/E, PEG, DCF impact)")
lines.append("")
lines.append("## 7) Final Output Template")
lines.append("- Investment Rating: BUY / HOLD / AVOID + stars")
lines.append("- Left-side entry plan: 4 tranches with price zones")
lines.append("- Options plan: Sell Put / Vertical / Covered Call")
lines.append("- 3-year target range + key assumptions")
lines.append("- Risks that can invalidate thesis")
lines.append("")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description="Run a reusable earnings-analysis workflow for any listed company")
parser.add_argument("ticker", help="Ticker, e.g. COIN, AAPL, MSFT")
parser.add_argument("--company", help="Optional company name override", default=None)
parser.add_argument("--out", help="Output markdown path", default=None)
parser.add_argument("--json", help="Also dump raw json next to report", action="store_true")
args = parser.parse_args()
ticker = args.ticker.upper().strip()
yahoo_block = fetch_yahoo_block(ticker)
sec_block = fetch_sec_block(ticker)
report = build_report(ticker, args.company, yahoo_block, sec_block)
if args.out:
out_path = Path(args.out).expanduser().resolve()
else:
out_path = Path.cwd() / f"{ticker.lower()}-earnings-workflow.md"
out_path.write_text(report, encoding="utf-8")
print(f"✅ Report generated: {out_path}")
if args.json:
raw = {
"ticker": ticker,
"yahoo": yahoo_block,
"sec": sec_block,
}
json_path = out_path.with_suffix(".json")
json_path.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"✅ Raw JSON generated: {json_path}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Stock Analyzer - 自动化股票五维投资价值分析
Usage: analyze-stock <TICKER> [options]
"""
import sys
import json
from datetime import datetime
from typing import Dict, Optional
def summarize_short_term_options(option_chain, current_price: float) -> Dict:
"""汇总近端到期(最短期限)期权成交量与隐含波动率"""
try:
if option_chain is None or getattr(option_chain, 'empty', True):
return {"available": False}
df = option_chain.reset_index().copy()
if df.empty or 'expiration' not in df.columns:
return {"available": False}
# 选最近到期
exp_dates = sorted(df['expiration'].dropna().unique())
if not exp_dates:
return {"available": False}
nearest_exp = exp_dates[0]
near_df = df[df['expiration'] == nearest_exp].copy()
if near_df.empty:
return {"available": False}
near_df['volume'] = near_df['volume'].fillna(0)
near_df['openInterest'] = near_df['openInterest'].fillna(0)
near_df['impliedVolatility'] = near_df['impliedVolatility'].fillna(0)
calls = near_df[near_df['optionType'] == 'calls']
puts = near_df[near_df['optionType'] == 'puts']
call_vol = float(calls['volume'].sum()) if not calls.empty else 0.0
put_vol = float(puts['volume'].sum()) if not puts.empty else 0.0
call_oi = float(calls['openInterest'].sum()) if not calls.empty else 0.0
put_oi = float(puts['openInterest'].sum()) if not puts.empty else 0.0
# ATM附近IV(距离现价最近的5个合约)
near_df['moneyness_dist'] = (near_df['strike'] - current_price).abs()
atm = near_df.nsmallest(5, 'moneyness_dist')
atm_iv = float(atm['impliedVolatility'].mean()) if not atm.empty else 0.0
# 成交量最大合约
top = near_df.sort_values('volume', ascending=False).head(3)
top_contracts = []
for _, r in top.iterrows():
top_contracts.append({
'contract': r.get('contractSymbol'),
'type': r.get('optionType'),
'strike': float(r.get('strike', 0) or 0),
'volume': int(r.get('volume', 0) or 0),
'iv': float(r.get('impliedVolatility', 0) or 0),
})
return {
'available': True,
'nearest_expiration': str(nearest_exp),
'call_volume': int(call_vol),
'put_volume': int(put_vol),
'put_call_volume_ratio': round((put_vol / call_vol), 2) if call_vol > 0 else None,
'call_open_interest': int(call_oi),
'put_open_interest': int(put_oi),
'put_call_oi_ratio': round((put_oi / call_oi), 2) if call_oi > 0 else None,
'atm_iv': round(atm_iv, 4),
'top_contracts': top_contracts,
}
except Exception:
return {"available": False}
def analyze_stock(ticker: str, save: bool = False, format_type: str = "text") -> Dict:
"""分析股票并返回结果字典"""
try:
from yahooquery import Ticker
except ImportError:
print("Error: yahooquery not installed. Run: pip install yahooquery")
sys.exit(1)
print(f"🔍 正在分析 {ticker}...")
# 获取数据
stock = Ticker(ticker)
price_data = stock.price.get(ticker, {})
stats_data = stock.key_stats.get(ticker, {})
financial = stock.financial_data.get(ticker, {})
profile = stock.asset_profile.get(ticker, {})
cashflow = stock.cash_flow(frequency='a')
earnings_trend = stock.earnings_trend
recommendations = stock.recommendation_trend
option_chain = stock.option_chain
# 基础数据
current_price = price_data.get('regularMarketPrice', 0)
market_cap = price_data.get('marketCap', 0)
shares = stats_data.get('sharesOutstanding', 0)
high_52w = price_data.get('fiftyTwoWeekHigh', current_price * 1.2)
low_52w = price_data.get('fiftyTwoWeekLow', current_price * 0.8)
# 短期期权情绪与波动
options_summary = summarize_short_term_options(option_chain, current_price)
# 估值指标
forward_pe = stats_data.get('forwardPE', 0)
trailing_pe = stats_data.get('trailingPE', 0)
pb = stats_data.get('priceToBook', 0)
ev_ebitda = stats_data.get('enterpriseToEbitda', 0)
# 盈利能力
gross_margin = financial.get('grossMargins', 0)
operating_margin = financial.get('operatingMargins', 0)
net_margin = financial.get('profitMargins', 0)
roe = financial.get('returnOnEquity', 0)
roa = financial.get('returnOnAssets', 0)
# FCF
fcf = 0
if cashflow is not None and not cashflow.empty:
for col in cashflow.columns:
fcf_val = cashflow.loc['FreeCashFlow', col] if 'FreeCashFlow' in cashflow.index else None
if fcf_val and fcf_val == fcf_val: # not NaN
fcf = fcf_val
break
fcf_per_share = fcf / shares if shares else 0
p_fcf = current_price / fcf_per_share if fcf_per_share else 0
# 盈利预测
eps_growth = 0
revenue_growth = 0
if earnings_trend:
trend_data = earnings_trend.get(ticker, {}).get('trend', [])
for item in trend_data:
if item.get('period') == '0y':
eps_growth = item.get('growth', 0)
revenue_growth = item.get('revenueEstimate', {}).get('growth', 0)
break
# PEG
peg = forward_pe / (eps_growth * 100) if eps_growth else 0
# 分析师评级
target_mean = financial.get('targetMeanPrice', 0)
target_high = financial.get('targetHighPrice', 0)
target_low = financial.get('targetLowPrice', 0)
# 52周位置
position_pct = ((current_price - low_52w) / (high_52w - low_52w) * 100) if high_52w != low_52w else 0
drop_from_high = ((high_52w - current_price) / high_52w * 100) if high_52w else 0
# DCF 简化计算
fcf_current = fcf if fcf else market_cap * 0.02 # 估算
wacc = 0.09
growth_5y = 0.15
growth_terminal = 0.025
# 简化DCF: 5年增长 + 终值
pv_5y = 0
fcf_proj = fcf_current
for year in range(1, 6):
fcf_proj *= (1 + growth_5y)
pv_5y += fcf_proj / ((1 + wacc) ** year)
terminal_fcf = fcf_proj * (1 + growth_terminal)
terminal_value = terminal_fcf / (wacc - growth_terminal)
pv_terminal = terminal_value / ((1 + wacc) ** 5)
intrinsic_value = (pv_5y + pv_terminal) / shares if shares else 0
upside = ((intrinsic_value - current_price) / current_price * 100) if current_price else 0
# 五维评分
score_valuation = 4 if position_pct < 50 else 3 # 估值位置
score_fundamental = 5 if roe > 0.2 else 4 if roe > 0.15 else 3 # 基本面
score_fcf = 4 if fcf > 0 else 3 # FCF
score_peg = 5 if peg < 1 else 4 if peg < 1.5 else 3 # PEG
score_dcf = 4 if upside > 15 else 3 if upside > 0 else 2 # DCF
total_score = (score_valuation + score_fundamental + score_fcf + score_peg + score_dcf) / 5
# 投资评级
if total_score >= 4.5:
rating = "STRONG BUY ⭐⭐⭐⭐⭐"
elif total_score >= 4:
rating = "BUY ⭐⭐⭐⭐"
elif total_score >= 3:
rating = "HOLD ⭐⭐⭐"
else:
rating = "SELL ⭐⭐"
# 构建结果
result = {
"ticker": ticker,
"name": profile.get('shortName', ticker),
"date": datetime.now().strftime("%Y-%m-%d"),
"price": {
"current": round(current_price, 2),
"market_cap_b": round(market_cap / 1e9, 2),
"week_52_high": high_52w,
"week_52_low": low_52w,
"position_pct": round(position_pct, 1),
"drop_from_high": round(drop_from_high, 1),
},
"valuation": {
"forward_pe": round(forward_pe, 1),
"trailing_pe": round(trailing_pe, 1) if trailing_pe else None,
"pb": round(pb, 2),
"ev_ebitda": round(ev_ebitda, 1),
"peg": round(peg, 2),
},
"profitability": {
"gross_margin": round(gross_margin * 100, 1) if gross_margin else None,
"operating_margin": round(operating_margin * 100, 1) if operating_margin else None,
"net_margin": round(net_margin * 100, 1) if net_margin else None,
"roe": round(roe * 100, 1) if roe else None,
"roa": round(roa * 100, 1) if roa else None,
},
"cashflow": {
"fcf_b": round(fcf / 1e9, 2) if fcf else None,
"fcf_per_share": round(fcf_per_share, 2),
"p_fcf": round(p_fcf, 1),
},
"growth": {
"eps_growth": round(eps_growth * 100, 1),
"revenue_growth": round(revenue_growth * 100, 1),
},
"analyst": {
"target_mean": round(target_mean, 2),
"target_high": round(target_high, 2),
"target_low": round(target_low, 2),
"upside": round((target_mean - current_price) / current_price * 100, 1) if target_mean else None,
},
"options": options_summary,
"dcf": {
"intrinsic_value": round(intrinsic_value, 2),
"upside": round(upside, 1),
},
"scores": {
"valuation": score_valuation,
"fundamental": score_fundamental,
"fcf": score_fcf,
"peg": score_peg,
"dcf": score_dcf,
"total": round(total_score, 1),
},
"rating": rating,
"sector": profile.get('sector', 'N/A'),
"industry": profile.get('industry', 'N/A'),
}
return result
def print_report(data: Dict):
"""打印文本格式报告"""
print("\n" + "=" * 70)
print(f"📊 {data['name']} ({data['ticker']}) 投资分析报告")
print("=" * 70)
# 核心数据
print("\n【核心数据】")
print(f"• 股价: ${data['price']['current']}")
print(f"• 市值: ${data['price']['market_cap_b']:.1f}B")
print(f"• 52周位置: {data['price']['position_pct']}% (距高点 -{data['price']['drop_from_high']}%)")
print(f"• Forward P/E: {data['valuation']['forward_pe']}x")
print(f"• PEG: {data['valuation']['peg']}")
if data['analyst']['target_mean']:
print(f"• 分析师目标价: ${data['analyst']['target_mean']} ({data['analyst']['upside']:+.1f}%)")
# 短期期权与IV
if data.get('options', {}).get('available'):
o = data['options']
print(f"\n【短期期权与隐含波动率】(最近到期: {o.get('nearest_expiration')})")
print(f"• Call成交量: {o.get('call_volume')} | Put成交量: {o.get('put_volume')} | P/C成交量比: {o.get('put_call_volume_ratio')}")
print(f"• Call持仓量: {o.get('call_open_interest')} | Put持仓量: {o.get('put_open_interest')} | P/C持仓比: {o.get('put_call_oi_ratio')}")
print(f"• ATM附近平均IV: {round(o.get('atm_iv', 0) * 100, 2)}%")
# 五维评分
print("\n【五维评分】")
print(f"1. 投资点位: {'⭐' * data['scores']['valuation']}")
print(f"2. 基本面/护城河: {'⭐' * data['scores']['fundamental']}")
print(f"3. FCF: {'⭐' * data['scores']['fcf']}")
print(f"4. PEG: {'⭐' * data['scores']['peg']}")
print(f"5. DCF: {'⭐' * data['scores']['dcf']}")
# 投资评级
print("\n【投资评级】")
print(f"🎯 {data['rating']}")
print(f"📈 DCF内在价值: ${data['dcf']['intrinsic_value']} (Upside: {data['dcf']['upside']:+.1f}%)")
# 入场策略
print("\n【左侧交易建议】")
current = data['price']['current']
low = data['price']['week_52_low']
if data['price']['position_pct'] < 30:
print(f"✅ 当前处于低位区域,建议建仓")
elif data['price']['position_pct'] < 60:
print(f"⏸️ 当前处于合理区间,可分批建仓")
else:
print(f"⚠️ 当前处于高位区域,建议等待回调")
print(f"• 第一批: ${current*0.95:.0f}-${current*1.02:.0f} (试仓20%)")
print(f"• 第二批: ${current*0.85:.0f}-${current*0.95:.0f} (加仓30%)")
print(f"• 重仓区: ${low:.0f}-${low*1.1:.0f} (重仓35%)")
print("\n" + "=" * 70)
def save_report(data: Dict, filename: str = None):
"""保存为Markdown报告"""
if not filename:
filename = f"./{data['ticker']}-analysis-{data['date']}.md"
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"# {data['name']} ({data['ticker']}) 投资分析报告\n\n")
f.write(f"**分析日期**: {data['date']}\n\n")
f.write("## 核心数据\n\n")
f.write(f"- **股价**: ${data['price']['current']}\n")
f.write(f"- **市值**: ${data['price']['market_cap_b']:.1f}B\n")
f.write(f"- **行业**: {data['industry']}\n")
f.write(f"- **Forward P/E**: {data['valuation']['forward_pe']}x\n")
f.write(f"- **ROE**: {data['profitability']['roe']}%\n")
if data.get('options', {}).get('available'):
f.write(f"- **短期期权P/C成交量比**: {data['options'].get('put_call_volume_ratio')}\n")
f.write(f"- **短期期权ATM IV**: {round(data['options'].get('atm_iv', 0) * 100, 2)}%\n")
f.write("\n")
f.write("## 五维评分\n\n")
f.write(f"| 维度 | 评分 |\n")
f.write(f"|------|------|\n")
f.write(f"| 投资点位 | {'⭐' * data['scores']['valuation']} |\n")
f.write(f"| 基本面/护城河 | {'⭐' * data['scores']['fundamental']} |\n")
f.write(f"| FCF | {'⭐' * data['scores']['fcf']} |\n")
f.write(f"| PEG | {'⭐' * data['scores']['peg']} |\n")
f.write(f"| DCF | {'⭐' * data['scores']['dcf']} |\n")
f.write(f"| **综合** | **{data['scores']['total']}** |\n\n")
f.write(f"## 投资评级\n\n")
f.write(f"**{data['rating']}**\n\n")
f.write(f"- DCF内在价值: ${data['dcf']['intrinsic_value']} ({data['dcf']['upside']:+.1f}%)\n")
if data['analyst']['target_mean']:
f.write(f"- 分析师目标价: ${data['analyst']['target_mean']} ({data['analyst']['upside']:+.1f}%)\n")
print(f"\n💾 报告已保存: {filename}")
def main():
if len(sys.argv) < 2:
print("Usage: analyze-stock <TICKER> [options]")
print("Options:")
print(" --save Save report to file")
print(" --format md Output as markdown")
print(" --format json Output as JSON")
print("\nExamples:")
print(" analyze-stock AAPL")
print(" analyze-stock 1810.HK --save")
print(" analyze-stock AMZN --format json")
sys.exit(1)
ticker = sys.argv[1].upper()
save = '--save' in sys.argv
format_md = '--format md' in sys.argv or '-f md' in sys.argv
format_json = '--format json' in sys.argv or '-f json' in sys.argv
try:
result = analyze_stock(ticker, save=save)
if format_json:
print(json.dumps(result, indent=2, ensure_ascii=False))
elif format_md:
save_report(result, f"{ticker}-analysis.md")
else:
print_report(result)
if save:
save_report(result)
except Exception as e:
print(f"Error analyzing {ticker}: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
价值投资分析方法论 (Value Investing Analysis Methodology)
核心理念: 巴菲特 + 段永平投资哲学
分析框架: 五维价值投资分析体系
数据来源: 财报 + 基本面 + 市场事件 + 技术面
---
📋 分析流程 (Analysis Workflow)
第一步:巴菲特 + 段永平「好公司」定性评估(新增,必做)
目标: 先判断是不是“值得长期持有的公司”,再谈估值与买点。
1.1 公司业务(Business)
- [ ] 公司主要卖什么产品/服务(1-2句话说清)
- [ ] 核心客户是谁(ToC/ToB,地域结构)
- [ ] 行业位置(龙头/追赶者/细分强者)
- [ ] 增长驱动来自哪里(量、价、新市场、并购)
1.2 盈利模式(Business Model)
- [ ] 收入结构(一次性/订阅/佣金/广告/金融)
- [ ] 利润结构(毛利率、经营杠杆、净利率)
- [ ] 现金流来源(经营现金流是否稳定,FCF是否可持续)
- [ ] 资本开支属性(维持性Capex vs 增长性Capex)
1.3 公司文化与管理层(Culture & Management)
- [ ] 管理层是否诚实、透明、长期主义(巴菲特)
- [ ] 资本配置能力(回购/分红/并购/负债纪律)
- [ ] 组织文化是否支持长期竞争力(客户导向、工程文化、执行力)
- [ ] 是否符合“能不能睡得着觉”标准(段永平)
1.4 巴菲特四问(Checklist)
1. 业务是否简单可理解(能力圈) 2. 是否有可持续护城河 3. 管理层是否可信且会配置资本 4. 当前价格是否有安全边际
1.5 段永平四看(Checklist)
1. 是不是好生意(长期需求 + 定价权) 2. 是不是好公司(治理 + 文化 + 执行) 3. 是不是好价格(左侧分批,估值匹配) 4. 能不能长期拿得住(风险可控)
---
第二步:市场环境与事件驱动分析
目标: 理解当前市场情绪与基本面错配机会
1.1 关键事件识别
- [ ] 最新财报发布 (季度/年度)
- [ ] 重大资本开支计划 (Capex)
- [ ] 管理层指引变化 (Guidance)
- [ ] 行业政策/监管动态
- [ ] 宏观经济影响 (利率/通胀)
- [ ] 中期选举/总统选举周期位置(政策预期切换)
- [ ] 节假日效应(Thanksgiving-Christmas / 暑期出行 / 开学季)
- [ ] 特定月份季节性(如 9-10 月波动高发、11-12 月年末效应)
1.2 市场情绪评估
股价波动幅度 = (当前价 - 事件前价格) / 事件前价格 × 100%
解读标准:
• < -10%: 市场恐慌,可能存在逆向机会
• -5% ~ -10%: 适度担忧,观望
• -5% ~ +5%: 市场反应中性
• > +5%: 市场乐观,警惕高估1.3 事件影响拆解
| 事件类型 | 短期影响 | 中长期影响 | 投资策略 |
|---|---|---|---|
| Capex激增 | 利润承压 | 产能/技术领先 | 左侧布局 |
| 营收增速放缓 | 估值下杀 | 市场份额稳固 | 等待拐点 |
| 新市场扩张 | 投入期亏损 | 第二增长曲线 | 观察验证 |
| 监管利空 | 情绪恐慌 | 商业模式受损 | 谨慎回避 |
1.4 下跌阶段防御股筛选(新增)
在季节性弱势窗口(尤其 8-10 月)或选举不确定期,固定输出“防御股观察池”:
- 行业优先级: 公用事业 / 必选消费 / 医疗现金牛 / 能源龙头 / 国防军工
- 财务门槛: FCF Yield > 3%、净负债可控、分红/回购纪律稳定
- 估值门槛: Forward P/E 不显著高于行业,PEG 不失真
- 候选示例: PG、KO、PEP、JNJ、ABBV、XOM、CVX、LMT、NEE、DUK
---
第三步:五维价值投资分析
维度1️⃣: 投资点位与期权策略
1.1 估值位置评估
52周位置 = (当前价 - 52周低点) / (52周高点 - 52周低点) × 100%
左侧交易区间:
• < 30%: 深度价值区 (重仓)
• 30% - 50%: 合理偏低区 (建仓)
• 50% - 70%: 合理偏高区 (观望)
• > 70%: 高估区 (回避)1.2 建仓策略 (金字塔法)
| 层级 | 价格区间 | 仓位比例 | 累计仓位 | 操作逻辑 |
|---|---|---|---|---|
| 第一批 | 当前价 ±5% | 20% | 20% | 试探性建仓 |
| 第二批 | 回调10-15% | 30% | 50% | 确认趋势加仓 |
| 第三批 | 回调20-25% | 30% | 80% | 重仓区域 |
| 极端区 | 回调>30% | 20% | 100% | 恐慌买入 |
1.3 期权增强策略 (Sell Put)
适用条件: 优质公司 + 短期超跌 + 愿意长期持有
# Sell Put 策略评估
if 隐含波动率(IV) > 历史均值 + 20% and 股息率 > 2%:
策略 = "卖出Cash-Secured Put"
行权价 = 当前价 × 0.90 # 10%虚值
期限 = "12-18个月"
预期收益 = "权利金年化12-15%"1.4 期权现金流策略(新增:OTM Long Call 纪律)
目标: 用小仓位虚值 Long Call 获得弹性,并在趋势兑现时回收现金流,继续投入正股。
- 建仓方式:默认两档虚值行权价(约 10% OTM / 20% OTM)
- 到期选择:至少 6 个月,优先 12 个月以上(LEAPS 可选)
- 输出格式:必须给出可执行的具体合约(到期日 + 行权价 + 对应仓位)
- 止盈纪律:
- 浮盈达到 +50% → 减仓约 30%-50%
- 浮盈达到 +100% → 继续减仓至底仓或全部止盈
- 现金流回投:止盈资金优先回流正股左侧建仓区
- 风险控制:若 45-60 天内趋势未验证,评估滚动或止损,避免时间价值快速损耗
风险评级:
- ⭐⭐⭐⭐⭐: 低风险的优质蓝筹
- ⭐⭐⭐⭐: 中等风险的成长股
- ⭐⭐⭐: 高波动需警惕
---
维度2️⃣: 基本面与护城河分析 (段永平五维)
2.1 护城河五维评分模型
| 护城河类型 | 评估指标 | 评分标准 | 权重 |
|---|---|---|---|
| 网络效应 | 用户规模、平台双边市场、生态粘性 | 5/4/3/2/1 | 20% |
| 品牌护城河 | 品牌认知度、定价权、用户忠诚度 | 5/4/3/2/1 | 20% |
| 技术护城河 | 专利壁垒、R&D投入、技术领先性 | 5/4/3/2/1 | 20% |
| 成本优势 | 规模经济、运营效率、单位成本 | 5/4/3/2/1 | 20% |
| 切换成本 | 数据沉淀、服务依赖、迁移难度 | 5/4/3/2/1 | 20% |
评级标准:
- 4.5-5.0: 极宽护城河 ⭐⭐⭐⭐⭐
- 4.0-4.4: 宽阔护城河 ⭐⭐⭐⭐
- 3.0-3.9: 中等护城河 ⭐⭐⭐
- <3.0: 护城河狭窄 ⭐⭐
2.2 核心财务指标分析
盈利能力指标:
├── ROE (净资产收益率)
│ ├── >20%: 优秀 (巴菲特标准)
│ ├── 15-20%: 良好
│ ├── 10-15%: 一般
│ └── <10%: 较差
│
├── ROA (总资产收益率)
│ ├── >10%: 优秀
│ ├── 5-10%: 良好
│ └── <5%: 较差
│
├── 毛利率
│ ├── >50%: 高毛利商业模式
│ ├── 30-50%: 中等毛利
│ └── <30%: 低毛利
│
└── 净利率
├── >20%: 极强盈利能力
├── 10-20%: 良好
└── <10%: 受成本/竞争影响2.3 增长质量分析
营收增长拆解:
营收增长 = 量价齐升 (优质)
= 量增价跌 (竞争加剧)
= 量跌价增 (高端化)
= 量价齐跌 (衰退)利润增长拆解:
利润增长 = 营收增长 + 效率提升 (优质)
= 成本削减 (不可持续)
= 一次性收益 (质量差)
= 财务操作 (警惕)---
维度3️⃣: 每股现金流 (FCF Per Share) 深度分析
3.1 现金流三表联动
经营现金流 (OCF)
├── 净利润
├── + 折旧摊销
├── + 营运资本变动
└── = OCF
自由现金流 (FCF) = OCF - 资本支出 (CapEx)
├── 维持性CapEx: 维持当前业务所需
└── 增长性CapEx: 扩张/新业务投资
每股FCF = FCF / 总股本3.2 现金流质量评估
| 指标 | 计算公式 | 健康标准 | 分析意义 |
|---|---|---|---|
| FCF/净利润 | FCF ÷ 净利润 | >70% | 盈利含金量 |
| OCF/营收 | OCF ÷ 营收 | >15% | 营收变现能力 |
| CapEx/OCF | CapEx ÷ OCF | <50% | 再投资强度 |
| P/FCF | 股价 ÷ 每股FCF | <20x | FCF估值水平 |
| FCF Yield | 每股FCF ÷ 股价 | >5% | FCF回报率 |
3.3 特殊情形处理 (如亚马逊)
Capex激增期的分析框架:
当 FCF 为负但 OCF 强劲时:
真实盈利能力 = OCF - 维持性CapEx
= OCF × 70% (估算)
调整后市盈率 = 股价 ÷ (每股OCF × 0.7)
vs 同业P/OCF:
• 低于历史均值: 被低估
• 低于同业均值: 相对价值
• 处于历史低位: 黄金买点---
维度4️⃣: 前瞻市盈率 (Forward P/E) 与 PEG 估值
4.1 Forward P/E 分析框架
Forward P/E = 当前股价 / 未来12个月预期EPS
估值区间判断:
• <15x: 深度价值区
• 15-25x: 合理成长区
• 25-35x: 高成长溢价区
• >35x: 高估泡沫区
行业对比:
• vs 行业均值: 相对估值
• vs 历史均值: 历史分位
• vs 无风险利率: 风险补偿4.2 PEG 估值模型
PEG = Forward P/E ÷ 预期盈利增长率 (g)
其中 g 的选择:
• 保守: 使用1年预期增长率
• 中性: 使用2-3年CAGR
• 乐观: 使用长期可持续增长率
PEG评价标准:
• <0.8: 严重低估 ⭐⭐⭐⭐⭐
• 0.8-1.0: 低估 ⭐⭐⭐⭐
• 1.0-1.2: 合理 ⭐⭐⭐
• 1.2-1.5: 偏高 ⭐⭐
• >1.5: 高估 ⭐
多时间维度PEG:
• 1年PEG: 短期估值压力
• 2年PEG: 中期成长匹配
• 3年PEG: 长期价值锚定4.3 增长率质量评估
增长质量 = f(增长来源, 可持续性, 资本效率)
优质增长:
✓ 内生增长 (organic growth)
✓ 单位经济模型改善
✓ 高ROIC再投资
✓ 市场份额提升
劣质增长:
✗ 并购驱动 (M&A)
✗ 价格战换取
✗ 低ROIC扩张
✗ 一次性收益---
维度5️⃣: DCF 未来现金流折现估值
5.1 三阶段DCF模型
企业价值 = PV(阶段1) + PV(阶段2) + PV(阶段3)
阶段1: 高成长 (3-5年)
增长率: g1 = min(历史增速, 行业增速, 管理层指引)
阶段2: 中成长 (3-5年)
增长率: g2 = g1 × 0.6 (线性递减)
阶段3: 永续增长
增长率: g3 = 2-3% (GDP增速)5.2 关键参数设定
| 参数 | 设定方法 | 保守值 | 基准值 | 乐观值 |
|---|---|---|---|---|
| WACC | 加权平均资本成本 | 10% | 9% | 8% |
| g1 | 高成长阶段增速 | 15% | 20% | 25% |
| g2 | 中成长阶段增速 | 8% | 10% | 12% |
| g3 | 永续增长率 | 2% | 2.5% | 3% |
| 基准FCF | 当前年化FCF | 最近财年 | 平均3年 | 调整后 |
5.3 敏感性分析
内在价值矩阵:
| 永续增长率
WACC | 2.0% | 2.5% | 3.0%
---------|-------|-------|-------
8.0% | $XXX | $XXX | $XXX
9.0% | $XXX | $BASE | $XXX
10.0% | $XXX | $XXX | $XXX
安全边际 = (内在价值 - 当前价) / 内在价值 × 100%
买入标准 (巴菲特):
• 安全边际 > 30%: 强烈买入
• 安全边际 20-30%: 建议买入
• 安全边际 10-20%: 可试探
• 安全边际 < 10%: 等待---
🎯 投资决策矩阵
综合评分体系
| 维度 | 权重 | 评分 | 加权得分 |
|---|---|---|---|
| 投资点位 | 20% | 1-5⭐ | _ |
| 护城河 | 20% | 1-5⭐ | _ |
| FCF质量 | 20% | 1-5⭐ | _ |
| PEG估值 | 20% | 1-5⭐ | _ |
| DCF安全边际 | 20% | 1-5⭐ | _ |
| 综合 | 100% | 1-5⭐ | _/5.0 |
投资评级
| 综合评分 | 安全边际 | 评级 | 操作策略 |
|---|---|---|---|
| 4.5-5.0 | >25% | ⭐⭐⭐⭐⭐ STRONG BUY | 重仓买入 |
| 4.0-4.4 | >15% | ⭐⭐⭐⭐ BUY | 分批建仓 |
| 3.5-3.9 | >5% | ⭐⭐⭐ HOLD | 持有观望 |
| 3.0-3.4 | -5~5% | ⭐⭐ REDUCE | 减仓观望 |
| <3.0 | <-5% | ⭐ SELL | 清仓回避 |
---
📝 输出模板 (Output Template)
标准化分析报告结构
## 📊 [公司名] ([代码]) 价值投资分析报告
**分析日期**: YYYY-MM-DD
**当前模型**: [模型名称]
---
### 0. 巴菲特 + 段永平「好公司」评估(新增必填)
#### 0.1 公司业务
- 公司做什么:
- 核心客户/地区:
- 行业位置:
#### 0.2 盈利模式
- 收入来源结构:
- 毛利/净利结构:
- 现金流来源与稳定性:
#### 0.3 公司文化与管理层
- 管理层风格(诚实/透明/长期主义):
- 资本配置能力(回购/分红/并购/负债纪律):
- 组织文化(客户导向/工程导向/执行力):
#### 0.4 巴菲特四问 / 段永平四看结论
- 巴菲特四问结论:
- 段永平四看结论:
---
### 1. 市场环境与关键事件
- 最新财报: [要点总结]
- 股价反应: [涨跌幅及市场情绪]
- 核心矛盾: [基本面 vs 市场预期的错配]
### 1.5 市场时钟(中期选举 / 节假日 / 月份季节性)
- 当前月份效应: [强/中/弱]
- 选举周期位置: [中期选举年/非中期选举年]
- 节假日窗口影响: [风险偏好/消费链/流动性]
- 下跌期防御观察池: [3-8只标的]
---
### 2. 投资点位与期权策略
**当前价位**: $XX.XX
**52周位置**: XX% [深度价值区/合理偏低/合理偏高/高估区]
**建仓策略**:
| 层级 | 价格 | 仓位 | 逻辑 |
**期权策略**: [Sell Put参数及预期收益]
---
### 3. 基本面与护城河
**五维护城河评分**: [详细评分表]
**核心财务指标**:
- ROE: XX% [优秀/良好/一般]
- 毛利率: XX%
- 营收增速: XX%
**2000亿买的是什么?** [Capex投向拆解]
---
### 4. 每股现金流 (OCF/FCF)
- OCF: $XXB (每股 $X.XX)
- FCF: $XXB (每股 $X.XX)
- P/OCF: XX.x [vs 历史/同业]
- FCF Yield: X.X%
---
### 5. Forward P/E 与 PEG
- Forward P/E: XX.x [低估/合理/高估]
- 1年 PEG: X.XX [短期压力]
- 2年 PEG: X.XX [中期价值]
---
### 6. DCF 估值
| 情景 | 每股价值 | vs 现价 | 核心假设 |
**敏感性分析**: [WACC/g矩阵]
---
### 🎯 投资评级: [RATING] ⭐⭐⭐⭐⭐
**综合评分**: X.X/5.0
**操作建议**:
- 立即: [行动]
- 回调至$XX: [加仓]
- 3年目标: $XXX (年化XX%)
**"时间是朋友"持有逻辑**:
1. [护城河]
2. [盈利能力]
3. [现金流]
4. [安全边际]
5. [长期复利]---
🔧 工具集成 (Tool Integration)
数据获取
# 基础数据
analyze-stock <TICKER>
# 价值投资深度分析
analyze-value <TICKER> --save
# 对比分析
analyze-compare <TICKER1> <TICKER2>自动报告生成
# 生成标准化报告
analyze-report <TICKER> --template value-investing --output md---
📚 参考资料
经典理论
- 巴菲特: "以合理价格买入优秀公司"
- 段永平: "买公司不是买股票,和时间做朋友"
- 格雷厄姆: "安全边际是价值投资的核心"
关键指标来源
- 财报数据: Yahoo Finance / SEC EDGAR
- 分析师预期: Bloomberg / FactSet
- 行业对比: Damodaran行业数据
---
⚠️ 免责声明
本方法论基于价值投资理念提供分析框架,不构成投资建议。投资有风险,入市需谨慎。
核心原则: 1. 任何模型都有局限性 2. 过去表现不代表未来收益 3. 请结合自身风险承受能力决策 4. 长期持有需要对企业有深入理解
---
🕰️ "时间是优秀企业的朋友,是平庸企业的敌人。" — 沃伦·巴菲特
版本: v1.0 更新日期: 2026-02-12 作者: 小天才 (Qwen Coder)
Stock Analyzer Skill
自动化股票五维投资价值分析工具。
安装
# 确保 yahooquery 已安装
pip install yahooquery
# 添加到 PATH
export PATH="$HOME/.openclaw/workspace/skills/stock-analyzer:$PATH"使用方法
快速分析
analyze-stock AAPL
analyze-stock AMZN
analyze-stock 1810.HK # 港股保存报告
analyze-stock TSLA --save
# 生成 TSLA-analysis-2024-02-11.md不同格式
analyze-stock NVDA --format json # JSON格式
analyze-stock META --format md # Markdown格式分析维度
1. 投资点位
- 52周区间位置
- 分析师目标价对比
- 入场策略建议
2. 基本面
- Forward P/E、PEG
- ROE、毛利率、净利率
- 护城河评估
3. 自由现金流 (FCF)
- FCF计算
- P/FCF估值
- FCF增长率
4. PEG估值
- PEG计算
- 增长预期分析
5. DCF估值
- 简化DCF模型
- 内在价值估算
示例输出
📊 Apple Inc. (AAPL) 投资分析报告
======================================================================
【核心数据】
• 股价: $185.92
• 市值: $2865.4B
• 52周位置: 78.5% (距高点 -12.3%)
• Forward P/E: 28.5x
• PEG: 1.85
• 分析师目标价: $200.0 (+7.6%)
【五维评分】
1. 投资点位: ⭐⭐⭐
2. 基本面/护城河: ⭐⭐⭐⭐⭐
3. FCF: ⭐⭐⭐⭐
4. PEG: ⭐⭐⭐
5. DCF: ⭐⭐⭐
【投资评级】
🎯 HOLD ⭐⭐⭐⭐ (4星)
📈 DCF内在价值: $195.5 (Upside: +5.1%)
【左侧交易建议】
⏸️ 当前处于合理区间,可分批建仓
• 第一批: $182-$190 (试仓20%)
• 第二批: $167-$182 (加仓30%)
• 重仓区: $161-$177 (重仓35%)特点
- ✅ 自动化数据获取 (Yahoo Finance)
- ✅ 五维评分系统
- ✅ DCF内在价值估算
- ✅ 分析师目标价对比
- ✅ 支持美股、港股、A股
- ✅ 可导出 Markdown/JSON
免责声明
本工具仅供参考,不构成投资建议。投资有风险,入市需谨慎。
Related skills
How it compares
Pick stock-analyzer for OpenClaw-specific agent hooks; choose broker-CLI market skills when you need documented live quotes and scanners.
FAQ
What is stock-analyzer in OpenClaw?
stock-analyzer is a skill entry in feiyuggg/openclaw-stock-analyzer that tags agent workflows for stock and market analysis tasks. The catalog describes AI and agent building use; confirm exact tools and data sources in the repository before relying on it in production.
Does stock-analyzer include live market data APIs?
The Skillselion source record for stock-analyzer does not document quote providers, broker endpoints, or indicator libraries. Developers should read the repo README and manifests locally to see whether live feeds or analysis logic are actually implemented.