0Pricing
AI Prompt Engineering · 课时

金融与定量分析提示词

收益分析、风险评分和 SEC 文件提取提示词。

金融与定量分析提示词 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

金融领域提示词背景

金融领域的提示词编写会从非结构化文档中提取结构化数据,例如收益报告、SEC 文件和分析师笔记。准确性至关重要:误读收入数字或颠倒增长方向,可能会在后续流程中造成严重错误。

财报提取提示词

财报通常遵循半标准化的结构。针对性提取提示词可以精准提取关键财务指标,同时处理 GAAP 和非 GAAP 两种口径。

EARNINGS_EXTRACTION_PROMPT = '''Extract the following financial metrics from the earnings report below.
Return ONLY a JSON object with these exact keys.
If a value is not stated, use null.
Do not calculate or derive values — only extract explicitly stated figures.

Required fields:
- revenue_usd_millions: total net revenue (GAAP)
- revenue_yoy_pct: year-over-year revenue growth percentage
- gross_margin_pct: gross margin percentage (GAAP)
- operating_income_usd_millions: GAAP operating income/loss
- ebitda_usd_millions: Adjusted EBITDA (non-GAAP, if reported)
- net_income_usd_millions: GAAP net income/loss
- eps_diluted: diluted EPS (GAAP)
- eps_adj_diluted: adjusted diluted EPS (non-GAAP, if reported)
- guidance_next_quarter_revenue_low: low end of next quarter revenue guidance
- guidance_next_quarter_revenue_high: high end of next quarter revenue guidance
- fiscal_period: e.g. "Q3 FY2024"

Earnings Report:
{report_text}'''

import anthropic, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def extract_earnings(report_text):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=1000,
        messages=[{'role': 'user', 'content':
            EARNINGS_EXTRACTION_PROMPT.format(report_text=report_text)}]
    )
    return json.loads(response.content[0].text)

财务比率计算提示词

当您希望模型计算财务比率时,请明确提供公式。不要假设模型知道确切定义——不同分析师使用的公式可能略有不同。

RATIO_PROMPT = '''Calculate the following financial ratios using the data provided.
Show your work: state the formula, plug in the numbers, and give the result.
Round all ratios to 2 decimal places.

Ratios to calculate:
1. Gross Margin = (Revenue - COGS) / Revenue * 100
2. Operating Margin = Operating Income / Revenue * 100
3. Net Margin = Net Income / Revenue * 100
4. Current Ratio = Current Assets / Current Liabilities
5. Quick Ratio = (Current Assets - Inventory) / Current Liabilities
6. Debt-to-Equity = Total Debt / Total Shareholders Equity
7. Return on Equity (ROE) = Net Income / Average Shareholders Equity * 100
8. EV/EBITDA = Enterprise Value / EBITDA (if EV is provided)

Financial Data:
{financial_data}'''

def calculate_ratios(financial_data):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=2000,
        messages=[{'role': 'user', 'content':
            RATIO_PROMPT.format(financial_data=financial_data)}]
    )
    return response.content[0].text

同比增长提取

YoY 增长可以报告为绝对变化、百分比,或两者兼有。提示词必须处理所有情况,并区分报告口径的增长与固定汇率口径的增长。

YOY_PROMPT = '''From the financial document below, extract year-over-year growth metrics.

For each metric found, provide:
- metric_name: e.g. "Revenue", "Gross Profit", "Operating Income"
- current_period: value and period (e.g. "$4.2B, Q3 2024")
- prior_period: value and period (e.g. "$3.8B, Q3 2023")
- yoy_change_pct: percentage change (positive = growth, negative = decline)
- constant_currency_yoy_pct: if reported, the constant-currency growth rate (else null)
- commentary: any management commentary on drivers of the change

IMPORTANT:
- Do not mix GAAP and non-GAAP figures in the same row.
- Mark each row with gaap: true or false.
- If growth is reported only in narrative form (e.g. "revenue grew 15%"),
  still capture it but set current_period and prior_period to null.

Document:
{document_text}'''

def extract_yoy_growth(document_text):
    import json
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=2000,
        messages=[{'role': 'user', 'content':
            YOY_PROMPT.format(document_text=document_text)}]
    )
    return response.content[0].text

SEC 文件提取模式

SEC 文件(10-K、10-Q)具有标准化的章节标题。使用了解章节结构的提取提示词,针对特定章节进行提取,可以减少上下文窗口的使用并提高精确度。

SEC_EXTRACTION_PROMPT = '''You are analyzing a {filing_type} SEC filing.

From {section_name}, extract the following:
{extraction_targets}

Rules:
1. Quote exact figures as stated — do not round or reformat numbers.
2. Note the fiscal year end and reporting currency.
3. If the section uses tables, extract all rows of the table.
4. Flag any restatements: "[RESTATED from prior filing]".
5. Note any forward-looking statements with [FLS] tag.

Filing Section Text:
{section_text}'''

# Section targets by filing type
SECTION_TARGETS = {
    '10-K': {
        'Item 7 MD&A': 'Revenue breakdown by segment, key cost drivers, liquidity discussion',
        'Item 1A Risk Factors': 'Top 5 risks by category (operational, financial, regulatory, competitive)',
        'Item 8 Financial Statements': 'Consolidated income statement, balance sheet key line items'
    },
    '10-Q': {
        'Item 1 Financial Statements': 'Revenue, operating income, cash flow from operations',
        'Item 2 MD&A': 'Quarter-over-quarter and YoY comparisons'
    }
}

def extract_sec_section(filing_type, section_name, section_text):
    targets = SEC_EXTRACTION_TARGETS = SECTION_TARGETS[filing_type][section_name]
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=3000,
        messages=[{'role': 'user', 'content':
            SEC_EXTRACTION_PROMPT.format(
                filing_type=filing_type, section_name=section_name,
                extraction_targets=targets, section_text=section_text
            )}]
    )
    return response.content[0].text

风险因素摘要

SEC 文件中的风险因素可能超过 50 页。能够对风险进行分类和排序的摘要提示词,可以帮助分析师快速识别最重要的风险。

RISK_FACTOR_PROMPT = '''Summarize the risk factors from this SEC filing.

Categories to use:
1. Financial Risks (liquidity, debt, interest rate, FX)
2. Operational Risks (supply chain, technology, key personnel)
3. Regulatory / Legal Risks (compliance, litigation, government action)
4. Market / Competitive Risks (competition, market conditions, pricing)
5. Macroeconomic Risks (recession, inflation, geopolitical)

For each risk:
- Title: 5-8 word summary
- Category: one of the 5 above
- Materiality: HIGH / MEDIUM / LOW (based on language used: "could significantly...",
  "may adversely affect...", "could result in material...")
- Summary: 2-3 sentence description

Sort each category by Materiality descending.
Limit to top 3 risks per category (15 total max).

Risk Factors Section:
{risk_factors_text}'''

def summarize_risk_factors(risk_factors_text):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=3000,
        messages=[{'role': 'user', 'content':
            RISK_FACTOR_PROMPT.format(risk_factors_text=risk_factors_text)}]
    )
    return response.content[0].text

分析师笔记生成

提取并分析财务数据后,请生成一份分析师风格的笔记,总结分析结果。提示词必须强制规定结构和专业金融研究所要求的客观语气。

ANALYST_NOTE_PROMPT = '''Write an equity research analyst note for the earnings results below.

STRUCTURE (required sections):
1. Headline: one sentence (include ticker, period, key takeaway, and target price if updated)
2. Investment Thesis: 2-3 sentences on the core bull/bear case
3. Earnings Summary: revenue, gross margin, EPS vs consensus estimates
4. Key Positives: 3 bullet points
5. Key Risks/Concerns: 3 bullet points
6. Guidance Commentary: management outlook, consensus vs guidance delta
7. Valuation: brief note on current multiple vs historical and peers
8. Recommendation: OUTPERFORM / MARKET PERFORM / UNDERPERFORM with 12-month target

TONE: Professional, data-driven, third person. Attribute claims to the company
("Management guided...", "The company reported...").
Do not use vague language — state numbers.

DISCLAIMER: This is AI-generated analysis for informational purposes only.
It does not constitute investment advice. Past performance is not indicative
of future results.

Earnings Data:
{earnings_data}'''

财务免责声明模式

与法律和医疗工具一样,金融人工智能工具也必须包含免责声明。请在应用层注入免责声明,确保其不会被遗漏。

FINANCIAL_DISCLAIMER = (
    '\n\n---\n'
    'DISCLAIMER: This content is generated by an AI system for informational '
    'and educational purposes only. It does not constitute investment advice, '
    'a solicitation to buy or sell any security, or a recommendation to invest. '
    'Financial data extracted by AI may contain errors — always verify against '
    'primary source filings. Past performance does not guarantee future results. '
    'Consult a licensed financial advisor before making investment decisions.'
)

def get_financial_analysis(prompt):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=2000,
        messages=[{'role': 'user', 'content': prompt}]
    )
    raw = response.content[0].text
    return raw + FINANCIAL_DISCLAIMER

# Always use get_financial_analysis() rather than calling the API directly
# to ensure disclaimer is never accidentally omitted

GAAP 与非 GAAP 消歧

财务提取中最常见的错误之一,是混淆 GAAP 和非 GAAP 数据。提示词必须明确要求模型标注每个数字,并标记不一致之处。

GAAP_PROMPT = '''Extract all income statement figures from the text below.
For every number:
- Label it as GAAP or Non-GAAP (Adjusted/Pro Forma)
- If the company reports both, show both on separate rows
- Never combine GAAP and Non-GAAP in a single calculation

Common non-GAAP labels to watch for:
"Adjusted", "Non-GAAP", "Pro Forma", "Normalized", "Underlying",
"Core", "Recurring", "Organic" (for revenue)

Output as a table:
| Metric | GAAP Value | Non-GAAP Value | Period |
|--------|------------|----------------|--------|

Also note in a separate section any reconciliation items between GAAP and Non-GAAP:
- Stock-based compensation
- Amortization of acquired intangibles
- Restructuring charges
- Any other adjustments

Document:
{document_text}'''

print('Always verify GAAP/Non-GAAP labels against the company\'s own reconciliation tables.')

多期趋势分析

单期提取只能提供一个快照。趋势分析提示词会比较多个时期的指标,从而发现发展轨迹以及加速或减速模式。

TREND_PROMPT = '''Analyze the financial trend for {company_name} using the multi-period data below.

1. Create a summary table with these columns:
   | Period | Revenue | Rev Growth YoY | Gross Margin | Op Margin | Net Margin |

2. Identify trends:
   - Is revenue growth accelerating, decelerating, or stable?
   - Margin expansion or compression trend?
   - Any notable inflection points (period where trend changed direction)?

3. Key observations (5 bullet points max):
   - Focus on directional changes, not just absolute numbers
   - Note any seasonality patterns if visible in quarterly data

4. Risks in the trend:
   - Flag any deterioration that management has not addressed
   - Note if guidance implies trend continuation or reversal

Data ({num_periods} periods):
{multi_period_data}'''

def analyze_trend(company_name, multi_period_data, num_periods):
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=2000,
        messages=[{'role': 'user', 'content':
            TREND_PROMPT.format(
                company_name=company_name,
                multi_period_data=multi_period_data,
                num_periods=num_periods
            )}]
    )
    return response.content[0].text

验证:交叉核对提取的数字

财务提取错误可能造成严重后果。请构建一个验证步骤,利用会计恒等式交叉核对提取的数字(例如,毛利润 = 收入 - COGS),以检测模型幻觉或提取错误。

def validate_financials(extracted):
    errors = []

    # Check revenue consistency
    if extracted.get('revenue_usd_millions') and extracted.get('cogs_usd_millions'):
        calc_gp = extracted['revenue_usd_millions'] - extracted['cogs_usd_millions']
        stated_gp = extracted.get('gross_profit_usd_millions')
        if stated_gp and abs(calc_gp - stated_gp) > 1:  # $1M tolerance
            errors.append(
                f'Gross profit mismatch: calculated {calc_gp:.1f}M '
                f'vs stated {stated_gp:.1f}M'
            )

    # Check gross margin consistency
    if extracted.get('revenue_usd_millions') and extracted.get('gross_profit_usd_millions'):
        calc_gm = (extracted['gross_profit_usd_millions'] /
                   extracted['revenue_usd_millions']) * 100
        stated_gm = extracted.get('gross_margin_pct')
        if stated_gm and abs(calc_gm - stated_gm) > 0.5:  # 0.5 pp tolerance
            errors.append(
                f'Gross margin mismatch: calculated {calc_gm:.1f}% '
                f'vs stated {stated_gm:.1f}%'
            )

    return errors

# Always run validation after extraction
errors = validate_financials(extracted_data)
if errors:
    print('Validation errors — manually verify:', errors)
else:
    print('Validation passed')

快速检查

从财报中提取财务指标时,模型返回的毛利率为 45%,但根据收入和 COGS 数据计算出的毛利率为 51%。您应该怎么做?

财务提示词总结

财务和定量提示词需要精确性、标注和验证:

  • 提取提示词:指定确切的字段名称,并返回 JSON 以便机器处理
  • 明确公式:计算比率时始终提供确切公式
  • GAAP 与非 GAAP:标注每个数字——计算时绝不混用
  • SEC 章节:针对特定 Item 章节以减少噪声
  • 验证:使用会计恒等式进行交叉核对,以检测提取错误
  • 免责声明:始终在应用层注入投资免责声明

常见问题解答

「金融与定量分析提示词」课时是免费的吗?

是的 — 「金融与定量分析提示词」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「金融与定量分析提示词」这节课中我会学到什么?

收益分析、风险评分和 SEC 文件提取提示词。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「金融与定量分析提示词」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 法律领域的提示词模式
  2. 医学与临床提示词
  3. 金融与定量分析提示词
  4. 领域术语表与本体注入
← 返回 AI Prompt Engineering