0Pricing
AI Prompt Engineering · Lección

Prompts financieros y cuantitativos

Análisis de resultados financieros, puntuación de riesgos y prompts para extraer información de informes de la SEC.

Prompts financieros y cuantitativos es una lección gratuita de AI Prompt Engineering en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Prompt Engineering, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Prompt Engineering incluye 4 lecciones en total.

Contexto del prompting financiero

El prompting financiero extrae datos estructurados de documentos no estructurados — informes de resultados, documentos presentados ante la SEC y notas de analistas. La precisión es fundamental: interpretar mal una cifra de ingresos o invertir la dirección del crecimiento puede causar errores graves en etapas posteriores.

Prompt de extracción de informes de resultados

Los informes de resultados siguen una estructura semiestandarizada. Un prompt de extracción específico obtiene con precisión las métricas financieras clave y gestiona tanto las variantes GAAP como las no 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)

Prompt para calcular ratios financieros

Cuando desee que el modelo calcule ratios financieros, proporcione la fórmula explícitamente. No dé por sentado que el modelo conoce la definición exacta: distintos analistas utilizan fórmulas ligeramente diferentes.

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

Extracción del crecimiento interanual

El crecimiento interanual puede expresarse como variación absoluta, porcentaje o ambos. El prompt debe contemplar todos los casos y distinguir entre el crecimiento declarado y el crecimiento en moneda constante.

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

Patrón de extracción de documentos presentados ante la SEC

Los documentos presentados ante la SEC (10-K, 10-Q) tienen encabezados de sección estandarizados. Dirija los prompts de extracción teniendo en cuenta las secciones específicas para reducir el uso de la ventana de contexto y mejorar la precisión.

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

Resumen de factores de riesgo

Los documentos presentados ante la SEC pueden tener más de 50 páginas de factores de riesgo. Un prompt de resumen que categorice y clasifique los riesgos permite a los analistas identificar rápidamente los más relevantes.

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

Generación de notas de analista

Después de extraer y analizar los datos financieros, genere una nota con estilo de analista que resuma los hallazgos. El prompt debe imponer la estructura y el tono objetivo propios de la investigación financiera profesional.

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}'''

Patrones de avisos de exención de responsabilidad financiera

Al igual que las herramientas jurídicas y médicas, las herramientas financieras de IA requieren avisos de exención de responsabilidad obligatorios. Introdúzcalos en la capa de aplicación para asegurarse de que nunca se omitan.

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

Desambiguación entre GAAP y no GAAP

Uno de los errores más comunes al extraer datos financieros es mezclar cifras GAAP y no GAAP. Los prompts deben exigir explícitamente que el modelo etiquete cada cifra y señale las discrepancias.

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.')

Análisis de tendencias de varios periodos

La extracción de un solo periodo ofrece una instantánea. Un prompt de análisis de tendencias compara las métricas de varios periodos para revelar la trayectoria y los patrones de aceleración o desaceleración.

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

Validación: comprobación cruzada de cifras extraídas

Los errores de extracción financiera son peligrosos. Incorpore un paso de validación que compruebe las cifras extraídas mediante identidades contables (p. ej., beneficio bruto = ingresos - COGS) para detectar alucinaciones o errores de extracción.

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')

Comprobación rápida

Al extraer métricas financieras de un informe de resultados, el modelo devuelve un margen bruto del 45 %, pero las cifras de ingresos y COGS implican un margen bruto del 51 %. ¿Qué debe hacer?

Resumen de prompting financiero

El prompting financiero y cuantitativo requiere precisión, etiquetado y validación:

  • Prompts de extracción: especifique nombres exactos de campos y devuelva JSON para el procesamiento automático
  • Fórmula explícita: proporcione siempre la fórmula exacta para calcular ratios
  • GAAP frente a no GAAP: etiquete cada cifra; nunca las mezcle en los cálculos
  • Secciones de la SEC: dirija la extracción a secciones Item específicas para reducir el ruido
  • Validación: compruebe los datos mediante identidades contables para detectar errores de extracción
  • Avisos legales: introduzca siempre el aviso de exención de responsabilidad sobre inversiones en la capa de aplicación

Preguntas frecuentes

¿La lección «Prompts financieros y cuantitativos» es gratis?

Sí — el texto completo de «Prompts financieros y cuantitativos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Prompt Engineering, actualiza a CoddyKit PRO. El curso de AI Prompt Engineering incluye 4 lecciones en total.

¿Qué aprenderé en «Prompts financieros y cuantitativos»?

Análisis de resultados financieros, puntuación de riesgos y prompts para extraer información de informes de la SEC. Practicas AI Prompt Engineering con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Prompt Engineering?

No se requiere experiencia previa. AI Prompt Engineering en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Prompts financieros y cuantitativos»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Prompt Engineering?

Sí. Cada lección de AI Prompt Engineering incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Patrones de prompts para el ámbito jurídico
  2. Prompts médicos y clínicos
  3. Prompts financieros y cuantitativos
  4. Inyección de glosarios y ontologías de dominio
← Volver a AI Prompt Engineering